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