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