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