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