]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiFontMetrics.cpp
4a09d97dcf894c6d52d2850a05cc76cdc9c5e5c1
[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         if (math_char) {
249                 QString const qs = toqstr(s);
250                 int br_width = metrics_.boundingRect(qs).width();
251 #if QT_VERSION >= 0x050b00
252                 int s_width = metrics_.horizontalAdvance(qs);
253 #else
254                 int s_width = metrics_.width(qs);
255 #endif
256                 // keep value 0 for math chars with width 0
257                 if (s_width != 0)
258                         w = max(br_width, s_width);
259         } else {
260                 QTextLayout tl;
261                 tl.setText(toqstr(s));
262                 tl.setFont(font_);
263                 tl.beginLayout();
264                 QTextLine line = tl.createLine();
265                 tl.endLayout();
266                 w = iround(line.horizontalAdvance());
267         }
268         strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
269         return w;
270 }
271
272
273 int GuiFontMetrics::width(QString const & ucs2) const
274 {
275         return width(qstring_to_ucs4(ucs2));
276 }
277
278
279 int GuiFontMetrics::signedWidth(docstring const & s) const
280 {
281         if (s.empty())
282                 return 0;
283
284         if (s[0] == '-')
285                 return -width(s.substr(1, s.size() - 1));
286         else
287                 return width(s);
288 }
289
290
291 shared_ptr<QTextLayout const>
292 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
293                               double const wordspacing) const
294 {
295         PROFILE_THIS_BLOCK(getTextLayout);
296         docstring const s_cache =
297                 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
298         if (auto ptl = qtextlayout_cache_[s_cache])
299                 return ptl;
300         PROFILE_CACHE_MISS(getTextLayout);
301         auto const ptl = make_shared<QTextLayout>();
302         ptl->setCacheEnabled(true);
303         QFont copy = font_;
304         copy.setWordSpacing(wordspacing);
305         ptl->setFont(copy);
306
307 #ifdef BIDI_USE_FLAG
308         /* Use undocumented flag to enforce drawing direction
309          * FIXME: This does not work with Qt 5.11 (ticket #11284).
310          */
311         ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
312 #endif
313
314 #ifdef BIDI_USE_OVERRIDE
315         /* Use unicode override characters to enforce drawing direction
316          * Source: http://www.iamcal.com/understanding-bidirectional-text/
317          */
318         if (rtl)
319                 // Right-to-left override: forces to draw text right-to-left
320                 ptl->setText(QChar(0x202E) + toqstr(s));
321         else
322                 // Left-to-right override: forces to draw text left-to-right
323                 ptl->setText(QChar(0x202D) + toqstr(s));
324 #else
325         ptl->setText(toqstr(s));
326 #endif
327
328         ptl->beginLayout();
329         ptl->createLine();
330         ptl->endLayout();
331         qtextlayout_cache_.insert(s_cache, ptl);
332         return ptl;
333 }
334
335
336 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
337                           double const wordspacing) const
338 {
339         if (pos <= 0)
340                 pos = 0;
341         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
342         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
343          * not be the same when there are high-plan unicode characters
344          * (bug #10443).
345          */
346         // BIDI_OFFSET accounts for a possible direction override
347         // character in front of the string.
348         int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
349         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
350 }
351
352
353 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
354                           double const wordspacing) const
355 {
356         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
357         QTextLine const & tline = tl->lineForTextPosition(0);
358         int qpos = tline.xToCursor(x);
359         int newx = static_cast<int>(tline.cursorToX(qpos));
360         // The value of qpos may be wrong in rtl text (see ticket #10569).
361         // To work around this, let's have a look at adjacent positions to
362         // see whether we find closer matches.
363         if (rtl && newx < x) {
364                 while (qpos > 0) {
365                         int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
366                         if (abs(xm - x) < abs(newx - x)) {
367                                 --qpos;
368                                 newx = xm;
369                         } else
370                                 break;
371                 }
372         } else if (rtl && newx > x) {
373                 while (qpos < tline.textLength()) {
374                         int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
375                         if (abs(xp - x) < abs(newx - x)) {
376                                 ++qpos;
377                                 newx = xp;
378                         } else
379                                 break;
380                 }
381         }
382         // correct x value to the actual cursor position.
383         x = newx;
384
385         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
386          * not be the same when there are high-plan unicode characters
387          * (bug #10443).
388          */
389 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
390         int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
391         // there may be a direction override character in front of the string.
392         return max(pos - BIDI_OFFSET, 0);
393 #else
394         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
395          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
396          * length. We work around the problem by trying all docstring
397          * positions until the right one is found. This is slow only if
398          * there are many high-plane Unicode characters. It might be
399          * worthwhile to implement a dichotomy search if this shows up
400          * under a profiler.
401          */
402         // there may be a direction override character in front of the string.
403         qpos = max(qpos - BIDI_OFFSET, 0);
404         int pos = min(qpos, static_cast<int>(s.length()));
405         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
406                 --pos;
407         LASSERT(pos > 0 || qpos == 0, /**/);
408         return pos;
409 #endif
410 }
411
412
413 int GuiFontMetrics::countExpanders(docstring const & str) const
414 {
415         // Numbers of characters that are expanded by inter-word spacing.  These
416         // characters are spaces, except for characters 09-0D which are treated
417         // specially.  (From a combination of testing with the notepad found in qt's
418         // examples, and reading the source code.)  In addition, consecutive spaces
419         // only count as one expander.
420         bool wasspace = false;
421         int nexp = 0;
422         for (char_type c : str)
423                 if (c > 0x0d && QChar(c).isSpace()) {
424                         if (!wasspace) {
425                                 ++nexp;
426                                 wasspace = true;
427                         }
428                 } else
429                         wasspace = false;
430         return nexp;
431 }
432
433
434 pair<int, int>
435 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
436                                bool const rtl, bool const force) const
437 {
438         QTextLayout tl;
439         /* Qt will not break at a leading or trailing space, and we need
440          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
441          *
442          * To work around the problem, we enclose the string between
443          * zero-width characters so that the QTextLayout algorithm will
444          * agree to break the text at these extremal spaces.
445          */
446         // Unicode character ZERO WIDTH NO-BREAK SPACE
447         QChar const zerow_nbsp(0xfeff);
448         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
449 #ifdef BIDI_USE_FLAG
450         /* Use undocumented flag to enforce drawing direction
451          * FIXME: This does not work with Qt 5.11 (ticket #11284).
452          */
453         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
454 #endif
455
456 #ifdef BIDI_USE_OVERRIDE
457         /* Use unicode override characters to enforce drawing direction
458          * Source: http://www.iamcal.com/understanding-bidirectional-text/
459          */
460         if (rtl)
461                 // Right-to-left override: forces to draw text right-to-left
462                 qs = QChar(0x202E) + qs;
463         else
464                 // Left-to-right override: forces to draw text left-to-right
465                 qs =  QChar(0x202D) + qs;
466 #endif
467         int const offset = 1 + BIDI_OFFSET;
468
469         tl.setText(qs);
470         tl.setFont(font_);
471         QTextOption to;
472         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
473                              : QTextOption::WordWrap);
474         tl.setTextOption(to);
475         tl.beginLayout();
476         QTextLine line = tl.createLine();
477         line.setLineWidth(x);
478         tl.createLine();
479         tl.endLayout();
480         int const line_wid = iround(line.horizontalAdvance());
481         if ((force && line.textLength() == offset) || line_wid > x)
482                 return {-1, -1};
483         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
484          * not be the same when there are high-plan unicode characters
485          * (bug #10443).
486          */
487         // The variable `offset' is here to account for the extra leading characters.
488         // The ending character zerow_nbsp has to be ignored if the line is complete.
489         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
490 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
491         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
492 #else
493         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
494          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
495          * length. We work around the problem by trying all docstring
496          * positions until the right one is found. This is slow only if
497          * there are many high-plane Unicode characters. It might be
498          * worthwhile to implement a dichotomy search if this shows up
499          * under a profiler.
500          */
501         int len = min(qlen, static_cast<int>(s.length()));
502         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
503                 --len;
504         LASSERT(len > 0 || qlen == 0, /**/);
505 #endif
506         return {len, line_wid};
507 }
508
509
510 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
511 {
512         PROFILE_THIS_BLOCK(breakAt);
513         if (s.empty())
514                 return false;
515
516         docstring const s_cache =
517                 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
518         pair<int, int> pp;
519
520         if (breakat_cache_.contains(s_cache))
521                 pp = breakat_cache_[s_cache];
522         else {
523                 PROFILE_CACHE_MISS(breakAt);
524                 pp = breakAt_helper(s, x, rtl, force);
525                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
526         }
527         if (pp.first == -1)
528                 return false;
529         s = s.substr(0, pp.first);
530         x = pp.second;
531         return true;
532 }
533
534
535 void GuiFontMetrics::rectText(docstring const & str,
536         int & w, int & ascent, int & descent) const
537 {
538         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
539         int const offset = 4;
540
541         w = width(str) + offset;
542         ascent = metrics_.ascent() + offset / 2;
543         descent = metrics_.descent() + offset / 2;
544 }
545
546
547 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
548         int & w, int & ascent, int & descent) const
549 {
550         rectText(str, w, ascent, descent);
551         w += offset;
552 }
553
554
555 Dimension const GuiFontMetrics::defaultDimension() const
556 {
557         return Dimension(0, maxAscent(), maxDescent());
558 }
559
560
561 Dimension const GuiFontMetrics::dimension(char_type c) const
562 {
563         return Dimension(width(c), ascent(c), descent(c));
564 }
565
566
567 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
568                 char_type c) const
569 {
570         QRect r;
571         if (is_utf16(c))
572                 r = metrics_.boundingRect(ucs4_to_qchar(c));
573         else
574                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
575
576         AscendDescend ad = { -r.top(), r.bottom() + 1};
577         // We could as well compute the width but this is not really
578         // needed for now as it is done directly in width() below.
579         metrics_cache_.insert(c, ad);
580
581         return ad;
582 }
583
584
585 int GuiFontMetrics::width(char_type c) const
586 {
587         int value = width_cache_.value(c, outOfLimitMetric);
588         if (value != outOfLimitMetric)
589                 return value;
590
591         if (is_utf16(c))
592                 value = metrics_.width(ucs4_to_qchar(c));
593         else
594                 value = metrics_.width(toqstr(docstring(1, c)));
595
596         width_cache_.insert(c, value);
597
598         return value;
599 }
600
601
602 int GuiFontMetrics::ascent(char_type c) const
603 {
604         static AscendDescend const outOfLimitAD =
605                 {outOfLimitMetric, outOfLimitMetric};
606         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
607         if (value.ascent != outOfLimitMetric)
608                 return value.ascent;
609
610         value = fillMetricsCache(c);
611         return value.ascent;
612 }
613
614
615 int GuiFontMetrics::descent(char_type c) const
616 {
617         static AscendDescend const outOfLimitAD =
618                 {outOfLimitMetric, outOfLimitMetric};
619         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
620         if (value.descent != outOfLimitMetric)
621                 return value.descent;
622
623         value = fillMetricsCache(c);
624         return value.descent;
625 }
626
627 } // namespace frontend
628 } // namespace lyx