]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiFontMetrics.cpp
Fixup 572b06d6: reduce cache size for breakString
[features.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/debug.h"
22 #include "support/lassert.h"
23 #include "support/lstrings.h" // for breakString_helper with qt4
24 #include "support/lyxlib.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 breakstr_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 = 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 namespace {
471
472 const int brkStrOffset = 1 + BIDI_OFFSET;
473
474
475 QString createBreakableString(docstring const & s, bool rtl, QTextLayout & tl)
476 {
477         /* Qt will not break at a leading or trailing space, and we need
478          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
479          *
480          * To work around the problem, we enclose the string between
481          * zero-width characters so that the QTextLayout algorithm will
482          * agree to break the text at these extremal spaces.
483          */
484         // Unicode character ZERO WIDTH NO-BREAK SPACE
485         QChar const zerow_nbsp(0xfeff);
486         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
487 #ifdef BIDI_USE_FLAG
488         /* Use undocumented flag to enforce drawing direction
489          * FIXME: This does not work with Qt 5.11 (ticket #11284).
490          */
491         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
492 #endif
493
494 #ifdef BIDI_USE_OVERRIDE
495         /* Use unicode override characters to enforce drawing direction
496          * Source: http://www.iamcal.com/understanding-bidirectional-text/
497          */
498         if (rtl)
499                 // Right-to-left override: forces to draw text right-to-left
500                 qs = QChar(0x202E) + qs;
501         else
502                 // Left-to-right override: forces to draw text left-to-right
503                 qs =  QChar(0x202D) + qs;
504 #endif
505         return qs;
506 }
507
508
509 docstring::size_type brkstr2str_pos(QString brkstr, docstring const & str, int pos)
510 {
511         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
512          * not be the same when there are high-plan unicode characters
513          * (bug #10443).
514          */
515         // The variable `brkStrOffset' is here to account for the extra leading characters.
516         // The ending character zerow_nbsp has to be ignored if the line is complete.
517         int const qlen = max(pos - brkStrOffset - (pos == brkstr.length()), 0);
518 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
519         auto const len = qstring_to_ucs4(brkstr.mid(brkStrOffset, qlen)).length();
520         // Avoid warning
521         (void)str;
522 #else
523         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
524          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
525          * length. We work around the problem by trying all docstring
526          * positions until the right one is found. This is slow only if
527          * there are many high-plane Unicode characters. It might be
528          * worthwhile to implement a dichotomy search if this shows up
529          * under a profiler.
530          */
531         int len = min(qlen, static_cast<int>(str.length()));
532         while (len >= 0 && toqstr(str.substr(0, len)).length() != qlen)
533                 --len;
534         LASSERT(len > 0 || qlen == 0, /**/);
535 #endif
536         return len;
537 }
538
539 }
540
541 FontMetrics::Breaks
542 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
543                                    bool rtl, bool force) const
544 {
545         QTextLayout tl;
546         QString qs = createBreakableString(s, rtl, tl);
547         tl.setText(qs);
548         tl.setFont(font_);
549         QTextOption to;
550         /*
551          * Some Asian languages split lines anywhere (no notion of
552          * word). It seems that QTextLayout is not aware of this fact.
553          * See for reference:
554          *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
555          *
556          * FIXME: Something shall be done about characters which are
557          * not allowed at the beginning or end of line.
558          */
559         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
560                              : QTextOption::WordWrap);
561         tl.setTextOption(to);
562
563         bool first = true;
564         tl.beginLayout();
565         while(true) {
566                 QTextLine line = tl.createLine();
567                 if (!line.isValid())
568                         break;
569                 line.setLineWidth(first ? first_wid : wid);
570                 first = false;
571         }
572         tl.endLayout();
573
574         Breaks breaks;
575         int pos = 0;
576         for (int i = 0 ; i < tl.lineCount() ; ++i) {
577                 QTextLine const & line = tl.lineAt(i);
578                 int const line_epos = line.textStart() + line.textLength();
579                 int const epos = brkstr2str_pos(qs, s, line_epos);
580 #if QT_VERSION >= 0x050000
581                 // This does not take trailing spaces into account, except for the last line.
582                 int const wid = iround(line.naturalTextWidth());
583                 // If the line is not the last one, trailing space is always omitted.
584                 int nspc_wid = wid;
585                 // For the last line, compute the width without trailing space
586                 if (i + 1 == tl.lineCount()) {
587                         // trim_pos points to the last character that is not a space
588                         auto trim_pos = s.find_last_not_of(from_ascii(" "));
589                         if (trim_pos == docstring::npos)
590                                 nspc_wid = 0;
591                         else if (trim_pos + 1 < s.length()) {
592                                 int const num_spaces = s.length() - trim_pos - 1;
593                                 // find the position on the line before trailing
594                                 // spaces. Remove 1 to account for the ending
595                                 // non-breaking space of qs.
596                                 nspc_wid = iround(line.cursorToX(line_epos - num_spaces - 1));
597                         }
598                 }
599 #else
600                 // With some monospace fonts, the value of horizontalAdvance()
601                 // can be wrong with Qt4. One hypothesis is that the invisible
602                 // characters that we use are given a non-null width.
603                 // FIXME: this is slower than it could be but we'll get rid of Qt4 anyway
604                 docstring const ss = s.substr(pos, epos - pos);
605                 int const wid = width(ss);
606                 int const nspc_wid = i + 1 < tl.lineCount() ? width(rtrim(ss)) : wid;
607 #endif
608                 breaks.emplace_back(epos - pos, wid, nspc_wid);
609                 pos = epos;
610 #if 0
611                 // FIXME: should it be kept in some form?
612                 if ((force && line.textLength() == brkStrOffset) || line_wid > x)
613                         return {-1, line_wid};
614 #endif
615         }
616
617         return breaks;
618 }
619
620
621 uint qHash(BreakStringKey const & key)
622 {
623         // assume widths are less than 10000. This fits in 32 bits.
624         uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
625         return std::qHash(key.s) ^ ::qHash(params);
626 }
627
628
629 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
630                                                 bool rtl, bool force) const
631 {
632         PROFILE_THIS_BLOCK(breakString);
633         if (s.empty())
634                 return Breaks();
635
636         BreakStringKey key{s, first_wid, wid, rtl, force};
637         Breaks brks;
638         if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
639                 brks = *brks_ptr;
640         else {
641                 PROFILE_CACHE_MISS(breakString);
642                 brks = breakString_helper(s, first_wid, wid, rtl, force);
643                 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
644         }
645         return brks;
646 }
647
648
649 void GuiFontMetrics::rectText(docstring const & str,
650         int & w, int & ascent, int & descent) const
651 {
652         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
653         int const offset = 4;
654
655         w = width(str) + offset;
656         ascent = metrics_.ascent() + offset / 2;
657         descent = metrics_.descent() + offset / 2;
658 }
659
660
661 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
662         int & w, int & ascent, int & descent) const
663 {
664         rectText(str, w, ascent, descent);
665         w += offset;
666 }
667
668
669 Dimension const GuiFontMetrics::defaultDimension() const
670 {
671         return Dimension(0, maxAscent(), maxDescent());
672 }
673
674
675 Dimension const GuiFontMetrics::dimension(char_type c) const
676 {
677         return Dimension(width(c), ascent(c), descent(c));
678 }
679
680
681 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
682                 char_type c) const
683 {
684         QRect r;
685         if (is_utf16(c))
686                 r = metrics_.boundingRect(ucs4_to_qchar(c));
687         else
688                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
689
690         AscendDescend ad = { -r.top(), r.bottom() + 1};
691         // We could as well compute the width but this is not really
692         // needed for now as it is done directly in width() below.
693         metrics_cache_.insert(c, ad);
694
695         return ad;
696 }
697
698
699 int GuiFontMetrics::width(char_type c) const
700 {
701         int value = width_cache_.value(c, outOfLimitMetric);
702         if (value != outOfLimitMetric)
703                 return value;
704
705 #if QT_VERSION >= 0x050b00
706         if (is_utf16(c))
707                 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
708         else
709                 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
710 #else
711         if (is_utf16(c))
712                 value = metrics_.width(ucs4_to_qchar(c));
713         else
714                 value = metrics_.width(toqstr(docstring(1, c)));
715 #endif
716
717         width_cache_.insert(c, value);
718
719         return value;
720 }
721
722
723 int GuiFontMetrics::ascent(char_type c) const
724 {
725         static AscendDescend const outOfLimitAD =
726                 {outOfLimitMetric, outOfLimitMetric};
727         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
728         if (value.ascent != outOfLimitMetric)
729                 return value.ascent;
730
731         value = fillMetricsCache(c);
732         return value.ascent;
733 }
734
735
736 int GuiFontMetrics::descent(char_type c) const
737 {
738         static AscendDescend const outOfLimitAD =
739                 {outOfLimitMetric, outOfLimitMetric};
740         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
741         if (value.descent != outOfLimitMetric)
742                 return value.descent;
743
744         value = fillMetricsCache(c);
745         return value.descent;
746 }
747
748 } // namespace frontend
749 } // namespace lyx