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