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