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