]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Introduce support/Cache.h
[lyx.git] / src / frontends / qt4 / 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 #include "Language.h"
20 #include "LyXRC.h"
21
22 #include "insets/Inset.h"
23
24 #include "support/convert.h"
25 #include "support/lassert.h"
26
27 #define DISABLE_PMPROF
28 #include "support/pmprof.h"
29
30 #include <QByteArray>
31
32 using namespace std;
33 using namespace lyx::support;
34
35 namespace std {
36
37 /*
38  * Argument-dependent lookup implies that this function shall be
39  * declared in the namespace of its argument. But this is std
40  * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
41  */
42 uint qHash(lyx::docstring const & s)
43 {
44         return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
45                                 s.size() * sizeof(lyx::docstring::value_type)));
46 }
47
48 }
49
50 namespace lyx {
51 namespace frontend {
52
53
54 int cache_metrics_width_size = 1 << 19;
55 int cache_metrics_breakat_size = 1 << 19;
56 // Qt 5.x already has its own caching of QTextLayout objects
57 #if (QT_VERSION < 0x050000)
58 int cache_metrics_qtextlayout_size = 500;
59 #else
60 int cache_metrics_qtextlayout_size = 0;
61 #endif
62
63
64 namespace {
65 /**
66  * Convert a UCS4 character into a QChar.
67  * This is a hack (it does only make sense for the common part of the UCS4
68  * and UTF16 encodings) and should not be used.
69  * This does only exist because of performance reasons (a real conversion
70  * using iconv is too slow on windows).
71  *
72  * This is no real conversion but a simple cast in reality. This is the reason
73  * why this works well for symbol fonts used in mathed too, even though
74  * these are not real ucs4 characters. These are codepoints in the
75  * computer modern fonts used, nothing unicode related.
76  * See comment in GuiPainter::text() for more explanation.
77  **/
78 inline QChar const ucs4_to_qchar(char_type const ucs4)
79 {
80         LATTEST(is_utf16(ucs4));
81         return QChar(static_cast<unsigned short>(ucs4));
82 }
83 } // anon namespace
84
85
86 /*
87  * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
88  * Limit qtextlayout_cache_ size to 500 elements (we do not know the
89  * size of the QTextLayout objects anyway).
90  * Note that all these numbers are arbitrary.
91  */
92 GuiFontMetrics::GuiFontMetrics(QFont const & font)
93         : font_(font), metrics_(font, 0),
94           strwidth_cache_(cache_metrics_width_size),
95           breakat_cache_(cache_metrics_breakat_size),
96           qtextlayout_cache_(cache_metrics_qtextlayout_size)
97 {
98 }
99
100
101 int GuiFontMetrics::maxAscent() const
102 {
103         return metrics_.ascent();
104 }
105
106
107 int GuiFontMetrics::maxDescent() const
108 {
109         // We add 1 as the value returned by QT is different than X
110         // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
111         return metrics_.descent() + 1;
112 }
113
114
115 int GuiFontMetrics::em() const
116 {
117         return QFontInfo(font_).pixelSize();
118 }
119
120
121 int GuiFontMetrics::lineWidth() const
122 {
123         return metrics_.lineWidth();
124 }
125
126
127 int GuiFontMetrics::underlinePos() const
128 {
129         return metrics_.underlinePos();
130 }
131
132
133 int GuiFontMetrics::strikeoutPos() const
134 {
135         return metrics_.strikeOutPos();
136 }
137
138
139 int GuiFontMetrics::lbearing(char_type c) const
140 {
141         if (!is_utf16(c))
142                 // FIXME: QFontMetrics::leftBearing does not support the
143                 //        full unicode range. Once it does, we could use:
144                 //return metrics_.leftBearing(toqstr(docstring(1, c)));
145                 return 0;
146
147         return metrics_.leftBearing(ucs4_to_qchar(c));
148 }
149
150
151 namespace {
152 int const outOfLimitMetric = -10000;
153 }
154
155
156 int GuiFontMetrics::rbearing(char_type c) const
157 {
158         int value = rbearing_cache_.value(c, outOfLimitMetric);
159         if (value != outOfLimitMetric)
160                 return value;
161
162         // Qt rbearing is from the right edge of the char's width().
163         if (is_utf16(c)) {
164                 QChar sc = ucs4_to_qchar(c);
165                 value = width(c) - metrics_.rightBearing(sc);
166         } else {
167                 // FIXME: QFontMetrics::leftBearing does not support the
168                 //        full unicode range. Once it does, we could use:
169                 // metrics_.rightBearing(toqstr(docstring(1, c)));
170                 value = width(c);
171         }
172
173         rbearing_cache_.insert(c, value);
174
175         return value;
176 }
177
178
179 int GuiFontMetrics::width(docstring const & s) const
180 {
181         PROFILE_THIS_BLOCK(width);
182         if (strwidth_cache_.contains(s))
183                 return strwidth_cache_[s];
184         PROFILE_CACHE_MISS(width);
185         /* For some reason QMetrics::width returns a wrong value with Qt5
186          * with some arabic text. OTOH, QTextLayout is broken for single
187          * characters with null width (like \not in mathed). Also, as a
188          * safety measure, always use QMetrics::width with our math fonts.
189         */
190         int w = 0;
191         if (s.length() == 1
192 #if QT_VERSION >= 0x040800
193             || font_.styleName() == "LyX"
194 #endif
195             )
196                 w = metrics_.width(toqstr(s));
197         else {
198                 QTextLayout tl;
199                 tl.setText(toqstr(s));
200                 tl.setFont(font_);
201                 tl.beginLayout();
202                 QTextLine line = tl.createLine();
203                 tl.endLayout();
204                 w = int(line.naturalTextWidth());
205         }
206         strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
207         return w;
208 }
209
210
211 int GuiFontMetrics::width(QString const & ucs2) const
212 {
213         return width(qstring_to_ucs4(ucs2));
214 }
215
216
217 int GuiFontMetrics::signedWidth(docstring const & s) const
218 {
219         if (s.empty())
220                 return 0;
221
222         if (s[0] == '-')
223                 return -width(s.substr(1, s.size() - 1));
224         else
225                 return width(s);
226 }
227
228
229 shared_ptr<QTextLayout const>
230 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
231                               double const wordspacing) const
232 {
233         PROFILE_THIS_BLOCK(getTextLayout);
234         docstring const s_cache =
235                 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
236         if (auto ptl = qtextlayout_cache_[s_cache])
237                 return ptl;
238         PROFILE_CACHE_MISS(getTextLayout);
239         auto const ptl = make_shared<QTextLayout>();
240         ptl->setCacheEnabled(true);
241         ptl->setText(toqstr(s));
242         QFont copy = font_;
243         copy.setWordSpacing(wordspacing);
244         ptl->setFont(copy);
245         // Note that both setFlags and the enums are undocumented
246         ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
247         ptl->beginLayout();
248         ptl->createLine();
249         ptl->endLayout();
250         qtextlayout_cache_.insert(s_cache, ptl);
251         return ptl;
252 }
253
254
255 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
256                           double const wordspacing) const
257 {
258         if (pos <= 0)
259                 pos = 0;
260         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
261         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
262          * not be the same when there are high-plan unicode characters
263          * (bug #10443).
264          */
265         int const qpos = toqstr(s.substr(0, pos)).length();
266         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
267 }
268
269
270 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
271                           double const wordspacing) const
272 {
273         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
274         int const qpos = tl->lineForTextPosition(0).xToCursor(x);
275         // correct x value to the actual cursor position.
276         x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
277         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
278          * not be the same when there are high-plan unicode characters
279          * (bug #10443).
280          */
281 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
282         return qstring_to_ucs4(tl->text().left(qpos)).length();
283 #else
284         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
285          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
286          * length. We work around the problem by trying all docstring
287          * positions until the right one is found. This is slow only if
288          * there are many high-plane Unicode characters. It might be
289          * worthwhile to implement a dichotomy search if this shows up
290          * under a profiler.
291          */
292         int pos = min(qpos, static_cast<int>(s.length()));
293         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
294                 --pos;
295         LASSERT(pos > 0 || qpos == 0, /**/);
296         return pos;
297 #endif
298 }
299
300
301 int GuiFontMetrics::countExpanders(docstring const & str) const
302 {
303         // Numbers of characters that are expanded by inter-word spacing.  These
304         // characters are spaces, except for characters 09-0D which are treated
305         // specially.  (From a combination of testing with the notepad found in qt's
306         // examples, and reading the source code.)  In addition, consecutive spaces
307         // only count as one expander.
308         bool wasspace = false;
309         int nexp = 0;
310         for (char_type c : str)
311                 if (c > 0x0d && QChar(c).isSpace()) {
312                         if (!wasspace) {
313                                 ++nexp;
314                                 wasspace = true;
315                         }
316                 } else
317                         wasspace = false;
318         return nexp;
319 }
320
321
322 pair<int, int>
323 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
324                                bool const rtl, bool const force) const
325 {
326         QTextLayout tl;
327         /* Qt will not break at a leading or trailing space, and we need
328          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
329          *
330          * To work around the problem, we enclose the string between
331          * zero-width characters so that the QTextLayout algorithm will
332          * agree to break the text at these extremal spaces.
333          */
334         // Unicode character ZERO WIDTH NO-BREAK SPACE
335         QChar const zerow_nbsp(0xfeff);
336         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
337 #if 1
338         /* Use unicode override characters to enforce drawing direction
339          * Source: http://www.iamcal.com/understanding-bidirectional-text/
340          */
341         if (rtl)
342                 // Right-to-left override: forces to draw text right-to-left
343                 qs = QChar(0x202E) + qs;
344         else
345                 // Left-to-right override: forces to draw text left-to-right
346                 qs =  QChar(0x202D) + qs;
347         int const offset = 2;
348 #else
349         // Alternative version that breaks with Qt5 and arabic text (#10436)
350         // Note that both setFlags and the enums are undocumented
351         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
352         int const offset = 1;
353 #endif
354
355         tl.setText(qs);
356         tl.setFont(font_);
357         QTextOption to;
358         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
359                              : QTextOption::WordWrap);
360         tl.setTextOption(to);
361         tl.beginLayout();
362         QTextLine line = tl.createLine();
363         line.setLineWidth(x);
364         tl.createLine();
365         tl.endLayout();
366         if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
367                 return {-1, -1};
368         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
369          * not be the same when there are high-plan unicode characters
370          * (bug #10443).
371          */
372         // The variable `offset' is here to account for the extra leading characters.
373         // The ending character zerow_nbsp has to be ignored if the line is complete.
374         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
375 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
376         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
377 #else
378         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
379          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
380          * length. We work around the problem by trying all docstring
381          * positions until the right one is found. This is slow only if
382          * there are many high-plane Unicode characters. It might be
383          * worthwhile to implement a dichotomy search if this shows up
384          * under a profiler.
385          */
386         int len = min(qlen, static_cast<int>(s.length()));
387         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
388                 --len;
389         LASSERT(len > 0 || qlen == 0, /**/);
390 #endif
391         // The -1 is here to account for the leading zerow_nbsp.
392         return {len, int(line.naturalTextWidth())};
393 }
394
395
396 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
397 {
398         PROFILE_THIS_BLOCK(breakAt);
399         if (s.empty())
400                 return false;
401
402         docstring const s_cache =
403                 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
404         pair<int, int> pp;
405
406         if (breakat_cache_.contains(s_cache))
407                 pp = breakat_cache_[s_cache];
408         else {
409                 PROFILE_CACHE_MISS(breakAt);
410                 pp = breakAt_helper(s, x, rtl, force);
411                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
412         }
413         if (pp.first == -1)
414                 return false;
415         s = s.substr(0, pp.first);
416         x = pp.second;
417         return true;
418 }
419
420
421 void GuiFontMetrics::rectText(docstring const & str,
422         int & w, int & ascent, int & descent) const
423 {
424         static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
425
426         w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
427         ascent = metrics_.ascent() + d;
428         descent = metrics_.descent() + d;
429 }
430
431
432 void GuiFontMetrics::buttonText(docstring const & str,
433         int & w, int & ascent, int & descent) const
434 {
435         rectText(str, w, ascent, descent);
436         w += Inset::TEXT_TO_INSET_OFFSET;
437 }
438
439
440 Dimension const GuiFontMetrics::defaultDimension() const
441 {
442         return Dimension(0, maxAscent(), maxDescent());
443 }
444
445
446 Dimension const GuiFontMetrics::dimension(char_type c) const
447 {
448         return Dimension(width(c), ascent(c), descent(c));
449 }
450
451
452 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
453                 char_type c) const
454 {
455         QRect r;
456         if (is_utf16(c))
457                 r = metrics_.boundingRect(ucs4_to_qchar(c));
458         else
459                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
460
461         AscendDescend ad = { -r.top(), r.bottom() + 1};
462         // We could as well compute the width but this is not really
463         // needed for now as it is done directly in width() below.
464         metrics_cache_.insert(c, ad);
465
466         return ad;
467 }
468
469
470 int GuiFontMetrics::width(char_type c) const
471 {
472         int value = width_cache_.value(c, outOfLimitMetric);
473         if (value != outOfLimitMetric)
474                 return value;
475
476         if (is_utf16(c))
477                 value = metrics_.width(ucs4_to_qchar(c));
478         else
479                 value = metrics_.width(toqstr(docstring(1, c)));
480
481         width_cache_.insert(c, value);
482
483         return value;
484 }
485
486
487 int GuiFontMetrics::ascent(char_type c) const
488 {
489         static AscendDescend const outOfLimitAD =
490                 {outOfLimitMetric, outOfLimitMetric};
491         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
492         if (value.ascent != outOfLimitMetric)
493                 return value.ascent;
494
495         value = fillMetricsCache(c);
496         return value.ascent;
497 }
498
499
500 int GuiFontMetrics::descent(char_type c) const
501 {
502         static AscendDescend const outOfLimitAD =
503                 {outOfLimitMetric, outOfLimitMetric};
504         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
505         if (value.descent != outOfLimitMetric)
506                 return value.descent;
507
508         value = fillMetricsCache(c);
509         return value.descent;
510 }
511
512 } // namespace frontend
513 } // namespace lyx