]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Generalize uppercase test
[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         // For some reason QMetrics::width returns a wrong value with Qt5
186         // int w = metrics_.width(toqstr(s));
187         PROFILE_CACHE_MISS(width)
188 #endif
189         QTextLayout tl;
190         tl.setText(toqstr(s));
191         tl.setFont(font_);
192         tl.beginLayout();
193         QTextLine line = tl.createLine();
194         tl.endLayout();
195         int w = int(line.naturalTextWidth());
196 #ifdef CACHE_METRICS_WIDTH
197         strwidth_cache_.insert(s, new int(w), s.size() * sizeof(char_type));
198 #endif
199         return w;
200 }
201
202
203 int GuiFontMetrics::width(QString const & ucs2) const
204 {
205         return width(qstring_to_ucs4(ucs2));
206 }
207
208
209 int GuiFontMetrics::signedWidth(docstring const & s) const
210 {
211         if (s.empty())
212                 return 0;
213
214         if (s[0] == '-')
215                 return -width(s.substr(1, s.size() - 1));
216         else
217                 return width(s);
218 }
219
220
221 QTextLayout const *
222 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
223                               double const wordspacing) const
224 {
225         PROFILE_THIS_BLOCK(getTextLayout)
226         QTextLayout * ptl;
227 #ifdef CACHE_METRICS_QTEXTLAYOUT
228         docstring const s_cache = s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
229         ptl = qtextlayout_cache_[s_cache];
230         if (!ptl) {
231                 PROFILE_CACHE_MISS(getTextLayout)
232 #endif
233                 ptl = new QTextLayout();
234                 ptl->setCacheEnabled(true);
235                 ptl->setText(toqstr(s));
236                 QFont copy = font_;
237                 copy.setWordSpacing(wordspacing);
238                 ptl->setFont(copy);
239                 // Note that both setFlags and the enums are undocumented
240                 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
241                 ptl->beginLayout();
242                 ptl->createLine();
243                 ptl->endLayout();
244 #ifdef CACHE_METRICS_QTEXTLAYOUT
245                 qtextlayout_cache_.insert(s_cache, ptl);
246         }
247 #endif
248         return ptl;
249 }
250
251
252 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
253                           double const wordspacing) const
254 {
255         if (pos <= 0)
256                 return rtl ? width(s) : 0;
257         QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
258         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
259          * not be the same when there are high-plan unicode characters
260          * (bug #10443).
261          */
262         int const qpos = toqstr(s.substr(0, pos)).length();
263         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
264 }
265
266
267 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
268                           double const wordspacing) const
269 {
270         QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
271         int const qpos = tl->lineForTextPosition(0).xToCursor(x);
272         // correct x value to the actual cursor position.
273         x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
274         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
275          * not be the same when there are high-plan unicode characters
276          * (bug #10443).
277          */
278 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
279         return qstring_to_ucs4(tl->text().left(qpos)).length();
280 #else
281         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
282          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
283          * length. We work around the problem by trying all docstring
284          * positions until the right one is found. This is slow only if
285          * there are many high-plane Unicode characters. It might be
286          * worthwhile to implement a dichotomy search if this shows up
287          * under a profiler.
288          */
289         int pos = min(qpos, static_cast<int>(s.length()));
290         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
291                 --pos;
292         LASSERT(pos > 0 || qpos == 0, /**/);
293         return pos;
294 #endif
295 }
296
297
298 int GuiFontMetrics::countExpanders(docstring const & str) const
299 {
300         // Numbers of characters that are expanded by inter-word spacing.  These
301         // characters are spaces, except for characters 09-0D which are treated
302         // specially.  (From a combination of testing with the notepad found in qt's
303         // examples, and reading the source code.)  In addition, consecutive spaces
304         // only count as one expander.
305         bool wasspace = false;
306         int nexp = 0;
307         for (char_type c : str)
308                 if (c > 0x0d && QChar(c).isSpace()) {
309                         if (!wasspace) {
310                                 ++nexp;
311                                 wasspace = true;
312                         }
313                 } else
314                         wasspace = false;
315         return nexp;
316 }
317
318
319 pair<int, int> *
320 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
321                                bool const rtl, bool const force) const
322 {
323         QTextLayout tl;
324         /* Qt will not break at a leading or trailing space, and we need
325          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
326          *
327          * To work around the problem, we enclose the string between
328          * zero-width characters so that the QTextLayout algorithm will
329          * agree to break the text at these extremal spaces.
330          */
331         // Unicode character ZERO WIDTH NO-BREAK SPACE
332         QChar const zerow_nbsp(0xfeff);
333         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
334 #if 1
335         /* Use unicode override characters to enforce drawing direction
336          * Source: http://www.iamcal.com/understanding-bidirectional-text/
337          */
338         if (rtl)
339                 // Right-to-left override: forces to draw text right-to-left
340                 qs = QChar(0x202E) + qs;
341         else
342                 // Left-to-right override: forces to draw text left-to-right
343                 qs =  QChar(0x202D) + qs;
344         int const offset = 2;
345 #else
346         // Alternative version that breaks with Qt5 and arabic text (#10436)
347         // Note that both setFlags and the enums are undocumented
348         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
349         int const offset = 1;
350 #endif
351
352         tl.setText(qs);
353         tl.setFont(font_);
354         QTextOption to;
355         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
356                              : QTextOption::WordWrap);
357         tl.setTextOption(to);
358         tl.beginLayout();
359         QTextLine line = tl.createLine();
360         line.setLineWidth(x);
361         tl.createLine();
362         tl.endLayout();
363         if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
364                 return new pair<int, int>(-1, -1);
365         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
366          * not be the same when there are high-plan unicode characters
367          * (bug #10443).
368          */
369         // The variable `offset' is here to account for the extra leading characters.
370         // The ending character zerow_nbsp has to be ignored if the line is complete.
371         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
372 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
373         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
374 #else
375         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
376          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
377          * length. We work around the problem by trying all docstring
378          * positions until the right one is found. This is slow only if
379          * there are many high-plane Unicode characters. It might be
380          * worthwhile to implement a dichotomy search if this shows up
381          * under a profiler.
382          */
383         int len = min(qlen, static_cast<int>(s.length()));
384         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
385                 --len;
386         LASSERT(len > 0 || qlen == 0, /**/);
387 #endif
388         // The -1 is here to account for the leading zerow_nbsp.
389         return new pair<int, int>(len, int(line.naturalTextWidth()));
390 }
391
392
393 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
394 {
395         PROFILE_THIS_BLOCK(breakAt)
396         if (s.empty())
397                 return false;
398         pair<int, int> * pp;
399 #ifdef CACHE_METRICS_BREAKAT
400         docstring const s_cache = s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
401
402         pp = breakat_cache_[s_cache];
403         if (!pp) {
404                 PROFILE_CACHE_MISS(breakAt)
405 #endif
406                 pp = breakAt_helper(s, x, rtl, force);
407 #ifdef CACHE_METRICS_BREAKAT
408                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
409         }
410 #endif
411         if (pp->first == -1)
412                 return false;
413         s = s.substr(0, pp->first);
414         x = pp->second;
415 #ifndef CACHE_METRICS_BREAKAT
416         delete pp;
417 #endif
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