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