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