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