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