]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiFontMetrics.cpp
Cleanup: fix comments, move declarations around
[features.git] / src / frontends / qt / 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 #include "support/debug.h"
24
25 #define DISABLE_PMPROF
26 #include "support/pmprof.h"
27
28 #include <QByteArray>
29 #include <QRawFont>
30 #include <QtEndian>
31
32 #if QT_VERSION >= 0x050100
33 #include <QtMath>
34 #else
35 #define qDegreesToRadians(degree) (degree * (M_PI / 180))
36 #endif
37
38 using namespace std;
39 using namespace lyx::support;
40
41 /* Define what mechanism is used to enforce text direction. Different
42  * methods work with different Qt versions. Here we try to use both
43  * methods together.
44  */
45 // Define to use unicode override characters to force direction
46 #define BIDI_USE_OVERRIDE
47 // Define to use flag to force direction
48 #define BIDI_USE_FLAG
49
50 #ifdef BIDI_USE_OVERRIDE
51 # define BIDI_OFFSET 1
52 #else
53 # define BIDI_OFFSET 0
54 #endif
55
56 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
57 #  error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
58 #endif
59
60 namespace std {
61
62 /*
63  * Argument-dependent lookup implies that this function shall be
64  * declared in the namespace of its argument. But this is std
65  * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
66  */
67 uint qHash(lyx::docstring const & s)
68 {
69         return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
70                                 s.size() * sizeof(lyx::docstring::value_type)));
71 }
72
73 } // namespace std
74
75 namespace lyx {
76 namespace frontend {
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  * Also, setting size to 0 is tantamount to disabling the cache.
85  */
86 int cache_metrics_width_size = 1 << 19;
87 int cache_metrics_breakat_size = 1 << 19;
88 // Qt 5.x already has its own caching of QTextLayout objects
89 // but it does not seem to work well on MacOS X.
90 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
91 int cache_metrics_qtextlayout_size = 500;
92 #else
93 int cache_metrics_qtextlayout_size = 0;
94 #endif
95
96
97 namespace {
98 /**
99  * Convert a UCS4 character into a QChar.
100  * This is a hack (it does only make sense for the common part of the UCS4
101  * and UTF16 encodings) and should not be used.
102  * This does only exist because of performance reasons (a real conversion
103  * using iconv is too slow on windows).
104  *
105  * This is no real conversion but a simple cast in reality. This is the reason
106  * why this works well for symbol fonts used in mathed too, even though
107  * these are not real ucs4 characters. These are codepoints in the
108  * computer modern fonts used, nothing unicode related.
109  * See comment in GuiPainter::text() for more explanation.
110  **/
111 inline QChar const ucs4_to_qchar(char_type const ucs4)
112 {
113         LATTEST(is_utf16(ucs4));
114         return QChar(static_cast<unsigned short>(ucs4));
115 }
116 } // namespace
117
118
119 GuiFontMetrics::GuiFontMetrics(QFont const & font)
120         : font_(font), metrics_(font, 0),
121           strwidth_cache_(cache_metrics_width_size),
122           breakat_cache_(cache_metrics_breakat_size),
123           qtextlayout_cache_(cache_metrics_qtextlayout_size)
124 {
125         // Determine italic slope
126         double const defaultSlope = tan(qDegreesToRadians(19.0));
127         QRawFont raw = QRawFont::fromFont(font);
128         QByteArray post(raw.fontTable("post"));
129         if (post.length() == 0) {
130                 slope_ = defaultSlope;
131                 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
132         } else {
133                 // post table description:
134                 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
135                 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
136                 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
137                 slope_ = -tan(qDegreesToRadians(angle));
138                 // Correct italic fonts with zero slope
139                 if (slope_ == 0.0 && font.italic())
140                         slope_ = defaultSlope;
141                 LYXERR(Debug::FONT, "Italic slope: " << slope_);
142         }
143 }
144
145
146 int GuiFontMetrics::maxAscent() const
147 {
148         return metrics_.ascent();
149 }
150
151
152 int GuiFontMetrics::maxDescent() const
153 {
154         // We add 1 as the value returned by QT is different than X
155         // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
156         // FIXME: check this
157         return metrics_.descent() + 1;
158 }
159
160
161 int GuiFontMetrics::em() const
162 {
163         return QFontInfo(font_).pixelSize();
164 }
165
166
167 int GuiFontMetrics::xHeight() const
168 {
169 //      LATTEST(metrics_.xHeight() == ascent('x'));
170         return metrics_.xHeight();
171 }
172
173
174 int GuiFontMetrics::lineWidth() const
175 {
176         return metrics_.lineWidth();
177 }
178
179
180 int GuiFontMetrics::underlinePos() const
181 {
182         return metrics_.underlinePos();
183 }
184
185
186 int GuiFontMetrics::strikeoutPos() const
187 {
188         return metrics_.strikeOutPos();
189 }
190
191
192 bool GuiFontMetrics::italic() const
193 {
194         return font_.italic();
195 }
196
197
198 double GuiFontMetrics::italicSlope() const
199 {
200         return slope_;
201 }
202
203
204 namespace {
205 int const outOfLimitMetric = -10000;
206 }
207
208
209 int GuiFontMetrics::lbearing(char_type c) const
210 {
211         int value = lbearing_cache_.value(c, outOfLimitMetric);
212         if (value != outOfLimitMetric)
213                 return value;
214
215         if (is_utf16(c))
216                 value = metrics_.leftBearing(ucs4_to_qchar(c));
217         else {
218                 // FIXME: QFontMetrics::leftBearing does not support the
219                 //        full unicode range. Once it does, we could use:
220                 // metrics_.leftBearing(toqstr(docstring(1, c)));
221                 value = 0;
222         }
223
224         lbearing_cache_.insert(c, value);
225
226         return value;
227 }
228
229
230 int GuiFontMetrics::rbearing(char_type c) const
231 {
232         int value = rbearing_cache_.value(c, outOfLimitMetric);
233         if (value != outOfLimitMetric)
234                 return value;
235
236         // Qt rbearing is from the right edge of the char's width().
237         if (is_utf16(c)) {
238                 QChar sc = ucs4_to_qchar(c);
239                 value = width(c) - metrics_.rightBearing(sc);
240         } else {
241                 // FIXME: QFontMetrics::leftBearing does not support the
242                 //        full unicode range. Once it does, we could use:
243                 // metrics_.rightBearing(toqstr(docstring(1, c)));
244                 value = width(c);
245         }
246
247         rbearing_cache_.insert(c, value);
248
249         return value;
250 }
251
252
253 int GuiFontMetrics::width(docstring const & s) const
254 {
255         PROFILE_THIS_BLOCK(width);
256         if (strwidth_cache_.contains(s))
257                 return strwidth_cache_[s];
258         PROFILE_CACHE_MISS(width);
259         /* Several problems have to be taken into account:
260          * * QFontMetrics::width does not returns a wrong value with Qt5 with
261          *   some arabic text, since the glyph-shaping operations are not
262          *   done (documented in Qt5).
263          * * QTextLayout is broken for single characters with null width
264          *   (like \not in mathed).
265          * * While QTextLine::horizontalAdvance is the right thing to use
266      *   for text strings, it does not give a good result with some
267      *   characters like the \int (gyph 4) of esint.
268
269          * The metrics of some of our math fonts (eg. esint) are such that
270          * QTextLine::horizontalAdvance leads, more or less, in the middle
271          * of a symbol. This is the horizontal position where a subscript
272          * should be drawn, so that the superscript has to be moved rightward.
273          * This is done when the kerning() method of the math insets returns
274          * a positive value. The problem with this choice is that navigating
275          * a formula becomes weird. For example, a selection extends only over
276          * about half of the symbol. In order to avoid this, with our math
277          * fonts we use QTextLine::naturalTextWidth, so that a superscript can
278          * be drawn right after the symbol, and move the subscript leftward by
279          * recording a negative value for the kerning.
280         */
281         int w = 0;
282         // is the string a single character from a math font ?
283 #if QT_VERSION >= 0x040800
284         bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
285 #else
286         bool const math_char = s.length() == 1;
287 #endif
288         if (math_char) {
289                 QString const qs = toqstr(s);
290                 int br_width = metrics_.boundingRect(qs).width();
291 #if QT_VERSION >= 0x050b00
292                 int s_width = metrics_.horizontalAdvance(qs);
293 #else
294                 int s_width = metrics_.width(qs);
295 #endif
296                 // keep value 0 for math chars with width 0
297                 if (s_width != 0)
298                         w = max(br_width, s_width);
299         } else {
300                 QTextLayout tl;
301                 tl.setText(toqstr(s));
302                 tl.setFont(font_);
303                 tl.beginLayout();
304                 QTextLine line = tl.createLine();
305                 tl.endLayout();
306                 w = iround(line.horizontalAdvance());
307         }
308         strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
309         return w;
310 }
311
312
313 int GuiFontMetrics::width(QString const & ucs2) const
314 {
315         return width(qstring_to_ucs4(ucs2));
316 }
317
318
319 int GuiFontMetrics::signedWidth(docstring const & s) const
320 {
321         if (s.empty())
322                 return 0;
323
324         if (s[0] == '-')
325                 return -width(s.substr(1, s.size() - 1));
326         else
327                 return width(s);
328 }
329
330
331 shared_ptr<QTextLayout const>
332 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
333                               double const wordspacing) const
334 {
335         PROFILE_THIS_BLOCK(getTextLayout);
336         docstring const s_cache =
337                 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
338         if (auto ptl = qtextlayout_cache_[s_cache])
339                 return ptl;
340         PROFILE_CACHE_MISS(getTextLayout);
341         auto const ptl = make_shared<QTextLayout>();
342         ptl->setCacheEnabled(true);
343         QFont copy = font_;
344         copy.setWordSpacing(wordspacing);
345         ptl->setFont(copy);
346
347 #ifdef BIDI_USE_FLAG
348         /* Use undocumented flag to enforce drawing direction
349          * FIXME: This does not work with Qt 5.11 (ticket #11284).
350          */
351         ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
352 #endif
353
354 #ifdef BIDI_USE_OVERRIDE
355         /* Use unicode override characters to enforce drawing direction
356          * Source: http://www.iamcal.com/understanding-bidirectional-text/
357          */
358         if (rtl)
359                 // Right-to-left override: forces to draw text right-to-left
360                 ptl->setText(QChar(0x202E) + toqstr(s));
361         else
362                 // Left-to-right override: forces to draw text left-to-right
363                 ptl->setText(QChar(0x202D) + toqstr(s));
364 #else
365         ptl->setText(toqstr(s));
366 #endif
367
368         ptl->beginLayout();
369         ptl->createLine();
370         ptl->endLayout();
371         qtextlayout_cache_.insert(s_cache, ptl);
372         return ptl;
373 }
374
375
376 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
377                           double const wordspacing) const
378 {
379         if (pos <= 0)
380                 pos = 0;
381         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
382         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
383          * not be the same when there are high-plan unicode characters
384          * (bug #10443).
385          */
386         // BIDI_OFFSET accounts for a possible direction override
387         // character in front of the string.
388         int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
389         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
390 }
391
392
393 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
394                           double const wordspacing) const
395 {
396         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
397         QTextLine const & tline = tl->lineForTextPosition(0);
398         int qpos = tline.xToCursor(x);
399         int newx = static_cast<int>(tline.cursorToX(qpos));
400         // The value of qpos may be wrong in rtl text (see ticket #10569).
401         // To work around this, let's have a look at adjacent positions to
402         // see whether we find closer matches.
403         if (rtl && newx < x) {
404                 while (qpos > 0) {
405                         int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
406                         if (abs(xm - x) < abs(newx - x)) {
407                                 --qpos;
408                                 newx = xm;
409                         } else
410                                 break;
411                 }
412         } else if (rtl && newx > x) {
413                 while (qpos < tline.textLength()) {
414                         int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
415                         if (abs(xp - x) < abs(newx - x)) {
416                                 ++qpos;
417                                 newx = xp;
418                         } else
419                                 break;
420                 }
421         }
422         // correct x value to the actual cursor position.
423         x = newx;
424
425         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
426          * not be the same when there are high-plan unicode characters
427          * (bug #10443).
428          */
429 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
430         int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
431         // there may be a direction override character in front of the string.
432         return max(pos - BIDI_OFFSET, 0);
433 #else
434         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
435          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
436          * length. We work around the problem by trying all docstring
437          * positions until the right one is found. This is slow only if
438          * there are many high-plane Unicode characters. It might be
439          * worthwhile to implement a dichotomy search if this shows up
440          * under a profiler.
441          */
442         // there may be a direction override character in front of the string.
443         qpos = max(qpos - BIDI_OFFSET, 0);
444         int pos = min(qpos, static_cast<int>(s.length()));
445         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
446                 --pos;
447         LASSERT(pos > 0 || qpos == 0, /**/);
448         return pos;
449 #endif
450 }
451
452
453 int GuiFontMetrics::countExpanders(docstring const & str) const
454 {
455         // Numbers of characters that are expanded by inter-word spacing.  These
456         // characters are spaces, except for characters 09-0D which are treated
457         // specially.  (From a combination of testing with the notepad found in qt's
458         // examples, and reading the source code.)  In addition, consecutive spaces
459         // only count as one expander.
460         bool wasspace = false;
461         int nexp = 0;
462         for (char_type c : str)
463                 if (c > 0x0d && QChar(c).isSpace()) {
464                         if (!wasspace) {
465                                 ++nexp;
466                                 wasspace = true;
467                         }
468                 } else
469                         wasspace = false;
470         return nexp;
471 }
472
473
474 pair<int, int>
475 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
476                                bool const rtl, bool const force) const
477 {
478         QTextLayout tl;
479         /* Qt will not break at a leading or trailing space, and we need
480          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
481          *
482          * To work around the problem, we enclose the string between
483          * zero-width characters so that the QTextLayout algorithm will
484          * agree to break the text at these extremal spaces.
485          */
486         // Unicode character ZERO WIDTH NO-BREAK SPACE
487         QChar const zerow_nbsp(0xfeff);
488         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
489 #ifdef BIDI_USE_FLAG
490         /* Use undocumented flag to enforce drawing direction
491          * FIXME: This does not work with Qt 5.11 (ticket #11284).
492          */
493         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
494 #endif
495
496 #ifdef BIDI_USE_OVERRIDE
497         /* Use unicode override characters to enforce drawing direction
498          * Source: http://www.iamcal.com/understanding-bidirectional-text/
499          */
500         if (rtl)
501                 // Right-to-left override: forces to draw text right-to-left
502                 qs = QChar(0x202E) + qs;
503         else
504                 // Left-to-right override: forces to draw text left-to-right
505                 qs =  QChar(0x202D) + qs;
506 #endif
507         int const offset = 1 + BIDI_OFFSET;
508
509         tl.setText(qs);
510         tl.setFont(font_);
511         QTextOption to;
512         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
513                              : QTextOption::WordWrap);
514         tl.setTextOption(to);
515         tl.beginLayout();
516         QTextLine line = tl.createLine();
517         line.setLineWidth(x);
518         tl.createLine();
519         tl.endLayout();
520         int const line_wid = iround(line.horizontalAdvance());
521         if ((force && line.textLength() == offset) || line_wid > x)
522                 return {-1, -1};
523         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
524          * not be the same when there are high-plan unicode characters
525          * (bug #10443).
526          */
527         // The variable `offset' is here to account for the extra leading characters.
528         // The ending character zerow_nbsp has to be ignored if the line is complete.
529         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
530 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
531         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
532 #else
533         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
534          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
535          * length. We work around the problem by trying all docstring
536          * positions until the right one is found. This is slow only if
537          * there are many high-plane Unicode characters. It might be
538          * worthwhile to implement a dichotomy search if this shows up
539          * under a profiler.
540          */
541         int len = min(qlen, static_cast<int>(s.length()));
542         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
543                 --len;
544         LASSERT(len > 0 || qlen == 0, /**/);
545 #endif
546         return {len, line_wid};
547 }
548
549
550 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
551 {
552         PROFILE_THIS_BLOCK(breakAt);
553         if (s.empty())
554                 return false;
555
556         docstring const s_cache =
557                 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
558         pair<int, int> pp;
559
560         if (breakat_cache_.contains(s_cache))
561                 pp = breakat_cache_[s_cache];
562         else {
563                 PROFILE_CACHE_MISS(breakAt);
564                 pp = breakAt_helper(s, x, rtl, force);
565                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
566         }
567         if (pp.first == -1)
568                 return false;
569         s = s.substr(0, pp.first);
570         x = pp.second;
571         return true;
572 }
573
574
575 void GuiFontMetrics::rectText(docstring const & str,
576         int & w, int & ascent, int & descent) const
577 {
578         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
579         int const offset = 4;
580
581         w = width(str) + offset;
582         ascent = metrics_.ascent() + offset / 2;
583         descent = metrics_.descent() + offset / 2;
584 }
585
586
587 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
588         int & w, int & ascent, int & descent) const
589 {
590         rectText(str, w, ascent, descent);
591         w += offset;
592 }
593
594
595 Dimension const GuiFontMetrics::defaultDimension() const
596 {
597         return Dimension(0, maxAscent(), maxDescent());
598 }
599
600
601 Dimension const GuiFontMetrics::dimension(char_type c) const
602 {
603         return Dimension(width(c), ascent(c), descent(c));
604 }
605
606
607 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
608                 char_type c) const
609 {
610         QRect r;
611         if (is_utf16(c))
612                 r = metrics_.boundingRect(ucs4_to_qchar(c));
613         else
614                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
615
616         AscendDescend ad = { -r.top(), r.bottom() + 1};
617         // We could as well compute the width but this is not really
618         // needed for now as it is done directly in width() below.
619         metrics_cache_.insert(c, ad);
620
621         return ad;
622 }
623
624
625 int GuiFontMetrics::width(char_type c) const
626 {
627         int value = width_cache_.value(c, outOfLimitMetric);
628         if (value != outOfLimitMetric)
629                 return value;
630
631 #if QT_VERSION >= 0x050b00
632         if (is_utf16(c))
633                 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
634         else
635                 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
636 #else
637         if (is_utf16(c))
638                 value = metrics_.width(ucs4_to_qchar(c));
639         else
640                 value = metrics_.width(toqstr(docstring(1, c)));
641 #endif
642
643         width_cache_.insert(c, value);
644
645         return value;
646 }
647
648
649 int GuiFontMetrics::ascent(char_type c) const
650 {
651         static AscendDescend const outOfLimitAD =
652                 {outOfLimitMetric, outOfLimitMetric};
653         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
654         if (value.ascent != outOfLimitMetric)
655                 return value.ascent;
656
657         value = fillMetricsCache(c);
658         return value.ascent;
659 }
660
661
662 int GuiFontMetrics::descent(char_type c) const
663 {
664         static AscendDescend const outOfLimitAD =
665                 {outOfLimitMetric, outOfLimitMetric};
666         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
667         if (value.descent != outOfLimitMetric)
668                 return value.descent;
669
670         value = fillMetricsCache(c);
671         return value.descent;
672 }
673
674 } // namespace frontend
675 } // namespace lyx