]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiFontMetrics.cpp
Refactor GuiFontMetrics::getLayout
[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 // This holds a translation table between the original string and the
356 // QString that we can use with QTextLayout.
357 struct TextLayoutHelper
358 {
359         /// Create the helper
360         /// \c s is the original string
361         /// \c isrtl is true if the string is right-to-left
362         /// \c naked is true to disable the insertion of zero width annotations
363         TextLayoutHelper(docstring const & s, bool isrtl, bool naked = false);
364
365         /// translate QString index to docstring index
366         docstring::size_type qpos2pos(int qpos) const
367         {
368                 return lower_bound(pos2qpos_.begin(), pos2qpos_.end(), qpos) - pos2qpos_.begin();
369         }
370
371         /// Translate docstring index to QString index
372         int pos2qpos(docstring::size_type pos) const { return pos2qpos_[pos]; }
373
374         // The original string
375         docstring docstr;
376         // The mirror string
377         QString qstr;
378         // is string right-to-left?
379         bool rtl;
380
381 private:
382         // This vector contains the QString pos for each string position
383         vector<int> pos2qpos_;
384 };
385
386
387 TextLayoutHelper::TextLayoutHelper(docstring const & s, bool isrtl, bool naked)
388         : docstr(s), rtl(isrtl)
389 {
390         // Reserve memory for performance purpose
391         pos2qpos_.reserve(s.size());
392         qstr.reserve(2 * s.size());
393
394         /* Qt will not break at a leading or trailing space, and we need
395          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
396          *
397          * To work around the problem, we enclose the string between
398          * word joiner characters so that the QTextLayout algorithm will
399          * agree to break the text at these extremal spaces.
400          */
401         // Unicode character WORD JOINER
402         QChar const word_joiner(0x2060);
403         if (!naked)
404                 qstr += word_joiner;
405
406 #ifdef BIDI_USE_OVERRIDE
407         if (!naked)
408                 qstr += bidi_override[rtl];
409 #endif
410
411         // Now translate the string character-by-character.
412         bool was_space = false;
413         for (char_type const c : s) {
414                 // insert a word joiner character between consecutive spaces
415                 bool const is_space = isSpace(c);
416                 if (!naked && is_space && was_space)
417                         qstr += word_joiner;
418                 was_space = is_space;
419                 // Remember the QString index at this point
420                 pos2qpos_.push_back(qstr.size());
421                 // Performance: UTF-16 characters are easier
422                 if (is_utf16(c))
423                         qstr += ucs4_to_qchar(c);
424                 else
425                         qstr += toqstr(c);
426         }
427
428         // Final word joiner (see above)
429         if (!naked)
430                 qstr += word_joiner;
431
432         // Add virtual position at the end of the string
433         pos2qpos_.push_back(qstr.size());
434
435         //QString dump = qstr;
436         //LYXERR0("TLH: " << dump.replace(word_joiner, "|").toStdString());
437 }
438
439
440 namespace {
441
442 shared_ptr<QTextLayout>
443 getTextLayout_helper(TextLayoutHelper const & tlh, double const wordspacing,
444                      QFont font)
445 {
446         auto const ptl = make_shared<QTextLayout>();
447         ptl->setCacheEnabled(true);
448         font.setWordSpacing(wordspacing);
449         ptl->setFont(font);
450 #ifdef BIDI_USE_FLAG
451         /* Use undocumented flag to enforce drawing direction
452          * FIXME: This does not work with Qt 5.11 (ticket #11284).
453          */
454         ptl->setFlags(tlh.rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
455 #endif
456         ptl->setText(tlh.qstr);
457
458         ptl->beginLayout();
459         ptl->createLine();
460         ptl->endLayout();
461
462         return ptl;
463 }
464
465 }
466
467 shared_ptr<QTextLayout const>
468 GuiFontMetrics::getTextLayout(TextLayoutHelper const & tlh,
469                               double const wordspacing) const
470 {
471         PROFILE_THIS_BLOCK(getTextLayout_TLH);
472         TextLayoutKey key{tlh.docstr, tlh.rtl, wordspacing};
473         if (auto ptl = qtextlayout_cache_[key])
474                 return ptl;
475         PROFILE_CACHE_MISS(getTextLayout_TLH);
476         auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
477         qtextlayout_cache_.insert(key, ptl);
478         return ptl;
479 }
480
481
482 shared_ptr<QTextLayout const>
483 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
484                               double const wordspacing) const
485 {
486         PROFILE_THIS_BLOCK(getTextLayout);
487         TextLayoutKey key{s, rtl, wordspacing};
488         if (auto ptl = qtextlayout_cache_[key])
489                 return ptl;
490         PROFILE_CACHE_MISS(getTextLayout);
491         TextLayoutHelper tlh(s, rtl);
492         auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
493         qtextlayout_cache_.insert(key, ptl);
494         return ptl;
495 }
496
497
498 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
499                           double const wordspacing) const
500 {
501         if (pos <= 0)
502                 pos = 0;
503         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
504         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
505          * not be the same when there are high-plan unicode characters
506          * (bug #10443).
507          */
508         // BIDI_OFFSET accounts for a possible direction override
509         // character in front of the string.
510         int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
511         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
512 }
513
514
515 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
516                           double const wordspacing) const
517 {
518         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
519         QTextLine const & tline = tl->lineForTextPosition(0);
520         int qpos = tline.xToCursor(x);
521         int newx = static_cast<int>(tline.cursorToX(qpos));
522         // The value of qpos may be wrong in rtl text (see ticket #10569).
523         // To work around this, let's have a look at adjacent positions to
524         // see whether we find closer matches.
525         if (rtl && newx < x) {
526                 while (qpos > 0) {
527                         int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
528                         if (abs(xm - x) < abs(newx - x)) {
529                                 --qpos;
530                                 newx = xm;
531                         } else
532                                 break;
533                 }
534         } else if (rtl && newx > x) {
535                 while (qpos < tline.textLength()) {
536                         int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
537                         if (abs(xp - x) < abs(newx - x)) {
538                                 ++qpos;
539                                 newx = xp;
540                         } else
541                                 break;
542                 }
543         }
544         // correct x value to the actual cursor position.
545         x = newx;
546
547         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
548          * not be the same when there are high-plan unicode characters
549          * (bug #10443).
550          */
551 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
552         int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
553         // there may be a direction override character in front of the string.
554         return max(pos - BIDI_OFFSET, 0);
555 #else
556         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
557          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
558          * length. We work around the problem by trying all docstring
559          * positions until the right one is found. This is slow only if
560          * there are many high-plane Unicode characters. It might be
561          * worthwhile to implement a dichotomy search if this shows up
562          * under a profiler.
563          */
564         // there may be a direction override character in front of the string.
565         qpos = max(qpos - BIDI_OFFSET, 0);
566         int pos = min(qpos, static_cast<int>(s.length()));
567         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
568                 --pos;
569         LASSERT(pos > 0 || qpos == 0, /**/);
570         return pos;
571 #endif
572 }
573
574
575 FontMetrics::Breaks
576 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
577                                    bool rtl, bool force) const
578 {
579         TextLayoutHelper const tlh(s, rtl);
580
581         QTextLayout tl;
582 #ifdef BIDI_USE_FLAG
583         /* Use undocumented flag to enforce drawing direction
584          * FIXME: This does not work with Qt 5.11 (ticket #11284).
585          */
586         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
587 #endif
588         tl.setText(tlh.qstr);
589         tl.setFont(font_);
590         QTextOption to;
591         /*
592          * Some Asian languages split lines anywhere (no notion of
593          * word). It seems that QTextLayout is not aware of this fact.
594          * See for reference:
595          *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
596          *
597          * FIXME: Something shall be done about characters which are
598          * not allowed at the beginning or end of line.
599          */
600         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
601                              : QTextOption::WordWrap);
602         tl.setTextOption(to);
603
604         bool first = true;
605         tl.beginLayout();
606         while(true) {
607                 QTextLine line = tl.createLine();
608                 if (!line.isValid())
609                         break;
610                 line.setLineWidth(first ? first_wid : wid);
611                 first = false;
612         }
613         tl.endLayout();
614
615         Breaks breaks;
616         int pos = 0;
617         for (int i = 0 ; i < tl.lineCount() ; ++i) {
618                 QTextLine const & line = tl.lineAt(i);
619                 int const line_epos = line.textStart() + line.textLength();
620                 int const epos = tlh.qpos2pos(line_epos);
621 #if QT_VERSION >= 0x050000
622                 // This does not take trailing spaces into account, except for the last line.
623                 int const wid = iround(line.naturalTextWidth());
624                 // If the line is not the last one, trailing space is always omitted.
625                 int nspc_wid = wid;
626                 // For the last line, compute the width without trailing space
627                 if (i + 1 == tl.lineCount() && !s.empty() && isSpace(s.back())
628                     && line.textStart() <= tlh.pos2qpos(s.size() - 1))
629                         nspc_wid = iround(line.cursorToX(tlh.pos2qpos(s.size() - 1)));
630 #else
631                 // With some monospace fonts, the value of horizontalAdvance()
632                 // can be wrong with Qt4. One hypothesis is that the invisible
633                 // characters that we use are given a non-null width.
634                 // FIXME: this is slower than it could be but we'll get rid of Qt4 anyway
635                 docstring ss = s.substr(pos, epos - pos);
636                 int const wid = width(ss);
637                 if (!ss.empty() && isSpace(ss.back()))
638                         ss.pop_back();
639                 int const nspc_wid = i + 1 < tl.lineCount() ? width(ss) : wid;
640 #endif
641                 breaks.emplace_back(epos - pos, wid, nspc_wid);
642                 pos = epos;
643 #if 0
644                 // FIXME: should it be kept in some form?
645                 if ((force && line.textLength() == brkStrOffset) || line_wid > x)
646                         return {-1, line_wid};
647 #endif
648         }
649
650         return breaks;
651 }
652
653
654 uint qHash(BreakStringKey const & key)
655 {
656         // assume widths are less than 10000. This fits in 32 bits.
657         uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
658         return std::qHash(key.s) ^ ::qHash(params);
659 }
660
661
662 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
663                                                 bool rtl, bool force) const
664 {
665         PROFILE_THIS_BLOCK(breakString);
666         if (s.empty())
667                 return Breaks();
668
669         BreakStringKey key{s, first_wid, wid, rtl, force};
670         Breaks brks;
671         if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
672                 brks = *brks_ptr;
673         else {
674                 PROFILE_CACHE_MISS(breakString);
675                 brks = breakString_helper(s, first_wid, wid, rtl, force);
676                 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
677         }
678         return brks;
679 }
680
681
682 void GuiFontMetrics::rectText(docstring const & str,
683         int & w, int & ascent, int & descent) const
684 {
685         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
686         int const offset = 4;
687
688         w = width(str) + offset;
689         ascent = metrics_.ascent() + offset / 2;
690         descent = metrics_.descent() + offset / 2;
691 }
692
693
694 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
695         int & w, int & ascent, int & descent) const
696 {
697         rectText(str, w, ascent, descent);
698         w += offset;
699 }
700
701
702 Dimension const GuiFontMetrics::defaultDimension() const
703 {
704         return Dimension(0, maxAscent(), maxDescent());
705 }
706
707
708 Dimension const GuiFontMetrics::dimension(char_type c) const
709 {
710         return Dimension(width(c), ascent(c), descent(c));
711 }
712
713
714 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
715                 char_type c) const
716 {
717         QRect r;
718         if (is_utf16(c))
719                 r = metrics_.boundingRect(ucs4_to_qchar(c));
720         else
721                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
722
723         AscendDescend ad = { -r.top(), r.bottom() + 1};
724         // We could as well compute the width but this is not really
725         // needed for now as it is done directly in width() below.
726         metrics_cache_.insert(c, ad);
727
728         return ad;
729 }
730
731
732 int GuiFontMetrics::width(char_type c) const
733 {
734         int value = width_cache_.value(c, outOfLimitMetric);
735         if (value != outOfLimitMetric)
736                 return value;
737
738 #if QT_VERSION >= 0x050b00
739         if (is_utf16(c))
740                 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
741         else
742                 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
743 #else
744         if (is_utf16(c))
745                 value = metrics_.width(ucs4_to_qchar(c));
746         else
747                 value = metrics_.width(toqstr(docstring(1, c)));
748 #endif
749
750         width_cache_.insert(c, value);
751
752         return value;
753 }
754
755
756 int GuiFontMetrics::ascent(char_type c) const
757 {
758         static AscendDescend const outOfLimitAD =
759                 {outOfLimitMetric, outOfLimitMetric};
760         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
761         if (value.ascent != outOfLimitMetric)
762                 return value.ascent;
763
764         value = fillMetricsCache(c);
765         return value.ascent;
766 }
767
768
769 int GuiFontMetrics::descent(char_type c) const
770 {
771         static AscendDescend const outOfLimitAD =
772                 {outOfLimitMetric, outOfLimitMetric};
773         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
774         if (value.descent != outOfLimitMetric)
775                 return value.descent;
776
777         value = fillMetricsCache(c);
778         return value.descent;
779 }
780
781 } // namespace frontend
782 } // namespace lyx