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