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