]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Mention style-dependency of some features in the tooltips.
[lyx.git] / src / frontends / qt4 / GuiFontMetrics.cpp
1 /**
2  * \file GuiFontMetrics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiFontMetrics.h"
15
16 #include "qt_helpers.h"
17
18 #include "Dimension.h"
19 #include "Language.h"
20 #include "LyXRC.h"
21
22 #include "insets/Inset.h"
23
24 #include "support/convert.h"
25 #include "support/lassert.h"
26
27 #define DISABLE_PMPROF
28 #include "support/pmprof.h"
29
30 #ifdef CACHE_SOME_METRICS
31 #include <QByteArray>
32 #endif
33
34 using namespace std;
35 using namespace lyx::support;
36
37 #ifdef CACHE_SOME_METRICS
38 namespace std {
39
40 /*
41  * Argument-dependent lookup implies that this function shall be
42  * declared in the namespace of its argument. But this is std
43  * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
44  */
45 uint qHash(lyx::docstring const & s)
46 {
47         return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
48                                 s.size() * sizeof(lyx::docstring::value_type)));
49 }
50
51 }
52 #endif
53
54 namespace lyx {
55 namespace frontend {
56
57 namespace {
58 /**
59  * Convert a UCS4 character into a QChar.
60  * This is a hack (it does only make sense for the common part of the UCS4
61  * and UTF16 encodings) and should not be used.
62  * This does only exist because of performance reasons (a real conversion
63  * using iconv is too slow on windows).
64  *
65  * This is no real conversion but a simple cast in reality. This is the reason
66  * why this works well for symbol fonts used in mathed too, even though
67  * these are not real ucs4 characters. These are codepoints in the
68  * computer modern fonts used, nothing unicode related.
69  * See comment in GuiPainter::text() for more explanation.
70  **/
71 inline QChar const ucs4_to_qchar(char_type const ucs4)
72 {
73         LATTEST(is_utf16(ucs4));
74         return QChar(static_cast<unsigned short>(ucs4));
75 }
76 } // anon namespace
77
78
79 /*
80  * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
81  * Limit qtextlayout_cache_ size to 500 elements (we do not know the
82  * size of the QTextLayout objects anyway).
83  * Note that all these numbers are arbitrary.
84  */
85 GuiFontMetrics::GuiFontMetrics(QFont const & font)
86         : font_(font), metrics_(font, 0)
87 #ifdef CACHE_METRICS_WIDTH
88         , strwidth_cache_(1 << 19)
89 #endif
90 #ifdef CACHE_METRICS_BREAKAT
91         , breakat_cache_(1 << 19)
92 #endif
93 #ifdef CACHE_METRICS_QTEXTLAYOUT
94         ,  qtextlayout_cache_(500)
95 #endif
96 {
97 }
98
99
100 int GuiFontMetrics::maxAscent() const
101 {
102         return metrics_.ascent();
103 }
104
105
106 int GuiFontMetrics::maxDescent() const
107 {
108         // We add 1 as the value returned by QT is different than X
109         // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
110         return metrics_.descent() + 1;
111 }
112
113
114 int GuiFontMetrics::em() const
115 {
116         return QFontInfo(font_).pixelSize();
117 }
118
119
120 int GuiFontMetrics::lineWidth() const
121 {
122         return metrics_.lineWidth();
123 }
124
125
126 int GuiFontMetrics::underlinePos() const
127 {
128         return metrics_.underlinePos();
129 }
130
131
132 int GuiFontMetrics::strikeoutPos() const
133 {
134         return metrics_.strikeOutPos();
135 }
136
137
138 int GuiFontMetrics::lbearing(char_type c) const
139 {
140         if (!is_utf16(c))
141                 // FIXME: QFontMetrics::leftBearing does not support the
142                 //        full unicode range. Once it does, we could use:
143                 //return metrics_.leftBearing(toqstr(docstring(1, c)));
144                 return 0;
145
146         return metrics_.leftBearing(ucs4_to_qchar(c));
147 }
148
149
150 namespace {
151 int const outOfLimitMetric = -10000;
152 }
153
154
155 int GuiFontMetrics::rbearing(char_type c) const
156 {
157         int value = rbearing_cache_.value(c, outOfLimitMetric);
158         if (value != outOfLimitMetric)
159                 return value;
160
161         // Qt rbearing is from the right edge of the char's width().
162         if (is_utf16(c)) {
163                 QChar sc = ucs4_to_qchar(c);
164                 value = width(c) - metrics_.rightBearing(sc);
165         } else {
166                 // FIXME: QFontMetrics::leftBearing does not support the
167                 //        full unicode range. Once it does, we could use:
168                 // metrics_.rightBearing(toqstr(docstring(1, c)));
169                 value = width(c);
170         }
171
172         rbearing_cache_.insert(c, value);
173
174         return value;
175 }
176
177
178 int GuiFontMetrics::width(docstring const & s) const
179 {
180         PROFILE_THIS_BLOCK(width)
181 #ifdef CACHE_METRICS_WIDTH
182         int * pw = strwidth_cache_[s];
183         if (pw)
184                 return *pw;
185         PROFILE_CACHE_MISS(width)
186 #endif
187         /* For some reason QMetrics::width returns a wrong value with Qt5
188          * with some arabic text. OTOH, QTextLayout is broken for single
189          * characters with null width (like \not in mathed). Also, as a
190          * safety measure, always use QMetrics::width with our math fonts.
191         */
192         int w = 0;
193         if (s.length() == 1
194 #if QT_VERSION >= 0x040800
195             || font_.styleName() == "LyX"
196 #endif
197             )
198                 w = metrics_.width(toqstr(s));
199         else {
200                 QTextLayout tl;
201                 tl.setText(toqstr(s));
202                 tl.setFont(font_);
203                 tl.beginLayout();
204                 QTextLine line = tl.createLine();
205                 tl.endLayout();
206                 w = int(line.naturalTextWidth());
207         }
208 #ifdef CACHE_METRICS_WIDTH
209         strwidth_cache_.insert(s, new int(w), s.size() * sizeof(char_type));
210 #endif
211         return w;
212 }
213
214
215 int GuiFontMetrics::width(QString const & ucs2) const
216 {
217         return width(qstring_to_ucs4(ucs2));
218 }
219
220
221 int GuiFontMetrics::signedWidth(docstring const & s) const
222 {
223         if (s.empty())
224                 return 0;
225
226         if (s[0] == '-')
227                 return -width(s.substr(1, s.size() - 1));
228         else
229                 return width(s);
230 }
231
232
233 QTextLayout const *
234 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
235                               double const wordspacing) const
236 {
237         PROFILE_THIS_BLOCK(getTextLayout)
238         QTextLayout * ptl;
239 #ifdef CACHE_METRICS_QTEXTLAYOUT
240         docstring const s_cache = s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
241         ptl = qtextlayout_cache_[s_cache];
242         if (!ptl) {
243                 PROFILE_CACHE_MISS(getTextLayout)
244 #endif
245                 ptl = new QTextLayout();
246                 ptl->setCacheEnabled(true);
247                 ptl->setText(toqstr(s));
248                 QFont copy = font_;
249                 copy.setWordSpacing(wordspacing);
250                 ptl->setFont(copy);
251                 // Note that both setFlags and the enums are undocumented
252                 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
253                 ptl->beginLayout();
254                 ptl->createLine();
255                 ptl->endLayout();
256 #ifdef CACHE_METRICS_QTEXTLAYOUT
257                 qtextlayout_cache_.insert(s_cache, ptl);
258         }
259 #endif
260         return ptl;
261 }
262
263
264 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
265                           double const wordspacing) const
266 {
267         if (pos <= 0)
268                 return rtl ? width(s) : 0;
269         QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
270         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
271          * not be the same when there are high-plan unicode characters
272          * (bug #10443).
273          */
274         int const qpos = toqstr(s.substr(0, pos)).length();
275         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
276 }
277
278
279 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
280                           double const wordspacing) const
281 {
282         QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
283         int const qpos = tl->lineForTextPosition(0).xToCursor(x);
284         // correct x value to the actual cursor position.
285         x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
286         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
287          * not be the same when there are high-plan unicode characters
288          * (bug #10443).
289          */
290 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
291         return qstring_to_ucs4(tl->text().left(qpos)).length();
292 #else
293         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
294          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
295          * length. We work around the problem by trying all docstring
296          * positions until the right one is found. This is slow only if
297          * there are many high-plane Unicode characters. It might be
298          * worthwhile to implement a dichotomy search if this shows up
299          * under a profiler.
300          */
301         int pos = min(qpos, static_cast<int>(s.length()));
302         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
303                 --pos;
304         LASSERT(pos > 0 || qpos == 0, /**/);
305         return pos;
306 #endif
307 }
308
309
310 int GuiFontMetrics::countExpanders(docstring const & str) const
311 {
312         // Numbers of characters that are expanded by inter-word spacing.  These
313         // characters are spaces, except for characters 09-0D which are treated
314         // specially.  (From a combination of testing with the notepad found in qt's
315         // examples, and reading the source code.)  In addition, consecutive spaces
316         // only count as one expander.
317         bool wasspace = false;
318         int nexp = 0;
319         for (char_type c : str)
320                 if (c > 0x0d && QChar(c).isSpace()) {
321                         if (!wasspace) {
322                                 ++nexp;
323                                 wasspace = true;
324                         }
325                 } else
326                         wasspace = false;
327         return nexp;
328 }
329
330
331 pair<int, int> *
332 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
333                                bool const rtl, bool const force) const
334 {
335         QTextLayout tl;
336         /* Qt will not break at a leading or trailing space, and we need
337          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
338          *
339          * To work around the problem, we enclose the string between
340          * zero-width characters so that the QTextLayout algorithm will
341          * agree to break the text at these extremal spaces.
342          */
343         // Unicode character ZERO WIDTH NO-BREAK SPACE
344         QChar const zerow_nbsp(0xfeff);
345         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
346 #if 1
347         /* Use unicode override characters to enforce drawing direction
348          * Source: http://www.iamcal.com/understanding-bidirectional-text/
349          */
350         if (rtl)
351                 // Right-to-left override: forces to draw text right-to-left
352                 qs = QChar(0x202E) + qs;
353         else
354                 // Left-to-right override: forces to draw text left-to-right
355                 qs =  QChar(0x202D) + qs;
356         int const offset = 2;
357 #else
358         // Alternative version that breaks with Qt5 and arabic text (#10436)
359         // Note that both setFlags and the enums are undocumented
360         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
361         int const offset = 1;
362 #endif
363
364         tl.setText(qs);
365         tl.setFont(font_);
366         QTextOption to;
367         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
368                              : QTextOption::WordWrap);
369         tl.setTextOption(to);
370         tl.beginLayout();
371         QTextLine line = tl.createLine();
372         line.setLineWidth(x);
373         tl.createLine();
374         tl.endLayout();
375         if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
376                 return new pair<int, int>(-1, -1);
377         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
378          * not be the same when there are high-plan unicode characters
379          * (bug #10443).
380          */
381         // The variable `offset' is here to account for the extra leading characters.
382         // The ending character zerow_nbsp has to be ignored if the line is complete.
383         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
384 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
385         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
386 #else
387         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
388          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
389          * length. We work around the problem by trying all docstring
390          * positions until the right one is found. This is slow only if
391          * there are many high-plane Unicode characters. It might be
392          * worthwhile to implement a dichotomy search if this shows up
393          * under a profiler.
394          */
395         int len = min(qlen, static_cast<int>(s.length()));
396         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
397                 --len;
398         LASSERT(len > 0 || qlen == 0, /**/);
399 #endif
400         // The -1 is here to account for the leading zerow_nbsp.
401         return new pair<int, int>(len, int(line.naturalTextWidth()));
402 }
403
404
405 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
406 {
407         PROFILE_THIS_BLOCK(breakAt)
408         if (s.empty())
409                 return false;
410         pair<int, int> * pp;
411 #ifdef CACHE_METRICS_BREAKAT
412         docstring const s_cache = s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
413
414         pp = breakat_cache_[s_cache];
415         if (!pp) {
416                 PROFILE_CACHE_MISS(breakAt)
417 #endif
418                 pp = breakAt_helper(s, x, rtl, force);
419 #ifdef CACHE_METRICS_BREAKAT
420                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
421         }
422 #endif
423         if (pp->first == -1)
424                 return false;
425         s = s.substr(0, pp->first);
426         x = pp->second;
427 #ifndef CACHE_METRICS_BREAKAT
428         delete pp;
429 #endif
430         return true;
431 }
432
433
434 void GuiFontMetrics::rectText(docstring const & str,
435         int & w, int & ascent, int & descent) const
436 {
437         static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
438
439         w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
440         ascent = metrics_.ascent() + d;
441         descent = metrics_.descent() + d;
442 }
443
444
445 void GuiFontMetrics::buttonText(docstring const & str,
446         int & w, int & ascent, int & descent) const
447 {
448         rectText(str, w, ascent, descent);
449         w += Inset::TEXT_TO_INSET_OFFSET;
450 }
451
452
453 Dimension const GuiFontMetrics::defaultDimension() const
454 {
455         return Dimension(0, maxAscent(), maxDescent());
456 }
457
458
459 Dimension const GuiFontMetrics::dimension(char_type c) const
460 {
461         return Dimension(width(c), ascent(c), descent(c));
462 }
463
464
465 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
466                 char_type c) const
467 {
468         QRect r;
469         if (is_utf16(c))
470                 r = metrics_.boundingRect(ucs4_to_qchar(c));
471         else
472                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
473
474         AscendDescend ad = { -r.top(), r.bottom() + 1};
475         // We could as well compute the width but this is not really
476         // needed for now as it is done directly in width() below.
477         metrics_cache_.insert(c, ad);
478
479         return ad;
480 }
481
482
483 int GuiFontMetrics::width(char_type c) const
484 {
485         int value = width_cache_.value(c, outOfLimitMetric);
486         if (value != outOfLimitMetric)
487                 return value;
488
489         if (is_utf16(c))
490                 value = metrics_.width(ucs4_to_qchar(c));
491         else
492                 value = metrics_.width(toqstr(docstring(1, c)));
493
494         width_cache_.insert(c, value);
495
496         return value;
497 }
498
499
500 int GuiFontMetrics::ascent(char_type c) const
501 {
502         static AscendDescend const outOfLimitAD =
503                 {outOfLimitMetric, outOfLimitMetric};
504         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
505         if (value.ascent != outOfLimitMetric)
506                 return value.ascent;
507
508         value = fillMetricsCache(c);
509         return value.ascent;
510 }
511
512
513 int GuiFontMetrics::descent(char_type c) const
514 {
515         static AscendDescend const outOfLimitAD =
516                 {outOfLimitMetric, outOfLimitMetric};
517         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
518         if (value.descent != outOfLimitMetric)
519                 return value.descent;
520
521         value = fillMetricsCache(c);
522         return value.descent;
523 }
524
525 } // namespace frontend
526 } // namespace lyx