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