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