]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Introducing table templates
[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::leading() const
115 {
116         return metrics_.leading();
117 }
118
119
120 int GuiFontMetrics::em() const
121 {
122         return QFontInfo(font_).pixelSize();
123 }
124
125
126 int GuiFontMetrics::xHeight() const
127 {
128 //      LATTEST(metrics_.xHeight() == ascent('x'));
129         return metrics_.xHeight();
130 }
131
132
133 int GuiFontMetrics::lineWidth() const
134 {
135         return metrics_.lineWidth();
136 }
137
138
139 int GuiFontMetrics::underlinePos() const
140 {
141         return metrics_.underlinePos();
142 }
143
144
145 int GuiFontMetrics::strikeoutPos() const
146 {
147         return metrics_.strikeOutPos();
148 }
149
150
151 namespace {
152 int const outOfLimitMetric = -10000;
153 }
154
155
156 int GuiFontMetrics::lbearing(char_type c) const
157 {
158         int value = lbearing_cache_.value(c, outOfLimitMetric);
159         if (value != outOfLimitMetric)
160                 return value;
161
162         if (is_utf16(c))
163                 value = metrics_.leftBearing(ucs4_to_qchar(c));
164         else {
165                 // FIXME: QFontMetrics::leftBearing does not support the
166                 //        full unicode range. Once it does, we could use:
167                 // metrics_.leftBearing(toqstr(docstring(1, c)));
168                 value = 0;
169         }
170
171         lbearing_cache_.insert(c, value);
172
173         return value;
174 }
175
176
177 int GuiFontMetrics::rbearing(char_type c) const
178 {
179         int value = rbearing_cache_.value(c, outOfLimitMetric);
180         if (value != outOfLimitMetric)
181                 return value;
182
183         // Qt rbearing is from the right edge of the char's width().
184         if (is_utf16(c)) {
185                 QChar sc = ucs4_to_qchar(c);
186                 value = width(c) - metrics_.rightBearing(sc);
187         } else {
188                 // FIXME: QFontMetrics::leftBearing does not support the
189                 //        full unicode range. Once it does, we could use:
190                 // metrics_.rightBearing(toqstr(docstring(1, c)));
191                 value = width(c);
192         }
193
194         rbearing_cache_.insert(c, value);
195
196         return value;
197 }
198
199
200 int GuiFontMetrics::width(docstring const & s) const
201 {
202         PROFILE_THIS_BLOCK(width);
203         if (strwidth_cache_.contains(s))
204                 return strwidth_cache_[s];
205         PROFILE_CACHE_MISS(width);
206         /* Several problems have to be taken into account:
207          * * QFontMetrics::width does not returns a wrong value with Qt5 with
208          *   some arabic text, since the glyph-shaping operations are not
209          *   done (documented in Qt5).
210          * * QTextLayout is broken for single characters with null width
211          *   (like \not in mathed).
212          * * While QTextLine::horizontalAdvance is the right thing to use
213      *   for text strings, it does not give a good result with some
214      *   characters like the \int (gyph 4) of esint.
215
216          * Also, as a safety measure, always use QFontMetrics::width with
217          * our math fonts.
218         */
219         int w = 0;
220         // is the string a single character from a math font ?
221 #if QT_VERSION >= 0x040800
222         bool const math_char = s.length() == 1 || font_.styleName() == "LyX";
223 #else
224         bool const math_char = s.length() == 1;
225 #endif
226         // keep value 0 for math chars with width 0
227         if (!math_char || metrics_.width(toqstr(s)) != 0) {
228                 QTextLayout tl;
229                 tl.setText(toqstr(s));
230                 tl.setFont(font_);
231                 tl.beginLayout();
232                 QTextLine line = tl.createLine();
233                 tl.endLayout();
234                 if (math_char)
235                         w = iround(line.naturalTextWidth());
236                 else
237                         w = iround(line.horizontalAdvance());
238         }
239         strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
240         return w;
241 }
242
243
244 int GuiFontMetrics::width(QString const & ucs2) const
245 {
246         return width(qstring_to_ucs4(ucs2));
247 }
248
249
250 int GuiFontMetrics::signedWidth(docstring const & s) const
251 {
252         if (s.empty())
253                 return 0;
254
255         if (s[0] == '-')
256                 return -width(s.substr(1, s.size() - 1));
257         else
258                 return width(s);
259 }
260
261
262 shared_ptr<QTextLayout const>
263 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
264                               double const wordspacing) const
265 {
266         PROFILE_THIS_BLOCK(getTextLayout);
267         docstring const s_cache =
268                 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
269         if (auto ptl = qtextlayout_cache_[s_cache])
270                 return ptl;
271         PROFILE_CACHE_MISS(getTextLayout);
272         auto const ptl = make_shared<QTextLayout>();
273         ptl->setCacheEnabled(true);
274         QFont copy = font_;
275         copy.setWordSpacing(wordspacing);
276         ptl->setFont(copy);
277 #if 1
278         /* Use unicode override characters to enforce drawing direction
279          * Source: http://www.iamcal.com/understanding-bidirectional-text/
280          */
281         if (rtl)
282                 // Right-to-left override: forces to draw text right-to-left
283                 ptl->setText(QChar(0x202E) + toqstr(s));
284         else
285                 // Left-to-right override: forces to draw text left-to-right
286                 ptl->setText(QChar(0x202D) + toqstr(s));
287 #define TEXTLAYOUT_OFFSET 1
288 #else
289         // FIXME: This does not work with Qt 5.11 (ticket #11284).
290         // Note that both setFlags and the enums are undocumented
291         ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
292         ptl->setText(toqstr(s));
293 #define TEXTLAYOUT_OFFSET 0
294 #endif
295         ptl->beginLayout();
296         ptl->createLine();
297         ptl->endLayout();
298         qtextlayout_cache_.insert(s_cache, ptl);
299         return ptl;
300 }
301
302
303 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
304                           double const wordspacing) const
305 {
306         if (pos <= 0)
307                 pos = 0;
308         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
309         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
310          * not be the same when there are high-plan unicode characters
311          * (bug #10443).
312          */
313         // TEXTLAYOUT_OFFSET accounts for a possible direction override
314         // character in front of the string.
315         int const qpos = toqstr(s.substr(0, pos)).length() + TEXTLAYOUT_OFFSET;
316         return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
317 }
318
319
320 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
321                           double const wordspacing) const
322 {
323         shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
324         QTextLine const & tline = tl->lineForTextPosition(0);
325         int qpos = tline.xToCursor(x);
326         int newx = static_cast<int>(tline.cursorToX(qpos));
327         // The value of qpos may be wrong in rtl text (see ticket #10569).
328         // To work around this, let's have a look at adjacent positions to
329         // see whether we find closer matches.
330         if (rtl && newx < x) {
331                 while (qpos > 0) {
332                         int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
333                         if (abs(xm - x) < abs(newx - x)) {
334                                 --qpos;
335                                 newx = xm;
336                         } else
337                                 break;
338                 }
339         } else if (rtl && newx > x) {
340                 while (qpos < tline.textLength()) {
341                         int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
342                         if (abs(xp - x) < abs(newx - x)) {
343                                 ++qpos;
344                                 newx = xp;
345                         } else
346                                 break;
347                 }
348         }
349         // correct x value to the actual cursor position.
350         x = newx;
351
352         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
353          * not be the same when there are high-plan unicode characters
354          * (bug #10443).
355          */
356 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
357         int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
358         // there may be a direction override character in front of the string.
359         return max(pos - TEXTLAYOUT_OFFSET, 0);
360 #else
361         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
362          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
363          * length. We work around the problem by trying all docstring
364          * positions until the right one is found. This is slow only if
365          * there are many high-plane Unicode characters. It might be
366          * worthwhile to implement a dichotomy search if this shows up
367          * under a profiler.
368          */
369         // there may be a direction override character in front of the string.
370         qpos = max(qpos - TEXTLAYOUT_OFFSET, 0);
371         int pos = min(qpos, static_cast<int>(s.length()));
372         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
373                 --pos;
374         LASSERT(pos > 0 || qpos == 0, /**/);
375         return pos;
376 #endif
377 }
378
379
380 int GuiFontMetrics::countExpanders(docstring const & str) const
381 {
382         // Numbers of characters that are expanded by inter-word spacing.  These
383         // characters are spaces, except for characters 09-0D which are treated
384         // specially.  (From a combination of testing with the notepad found in qt's
385         // examples, and reading the source code.)  In addition, consecutive spaces
386         // only count as one expander.
387         bool wasspace = false;
388         int nexp = 0;
389         for (char_type c : str)
390                 if (c > 0x0d && QChar(c).isSpace()) {
391                         if (!wasspace) {
392                                 ++nexp;
393                                 wasspace = true;
394                         }
395                 } else
396                         wasspace = false;
397         return nexp;
398 }
399
400
401 pair<int, int>
402 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
403                                bool const rtl, bool const force) const
404 {
405         QTextLayout tl;
406         /* Qt will not break at a leading or trailing space, and we need
407          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
408          *
409          * To work around the problem, we enclose the string between
410          * zero-width characters so that the QTextLayout algorithm will
411          * agree to break the text at these extremal spaces.
412          */
413         // Unicode character ZERO WIDTH NO-BREAK SPACE
414         QChar const zerow_nbsp(0xfeff);
415         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
416 #if 1
417         /* Use unicode override characters to enforce drawing direction
418          * Source: http://www.iamcal.com/understanding-bidirectional-text/
419          */
420         if (rtl)
421                 // Right-to-left override: forces to draw text right-to-left
422                 qs = QChar(0x202E) + qs;
423         else
424                 // Left-to-right override: forces to draw text left-to-right
425                 qs =  QChar(0x202D) + qs;
426         int const offset = 2;
427 #else
428         // Alternative version that breaks with Qt5 and arabic text (#10436)
429         // Note that both setFlags and the enums are undocumented
430         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
431         int const offset = 1;
432 #endif
433
434         tl.setText(qs);
435         tl.setFont(font_);
436         QTextOption to;
437         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
438                              : QTextOption::WordWrap);
439         tl.setTextOption(to);
440         tl.beginLayout();
441         QTextLine line = tl.createLine();
442         line.setLineWidth(x);
443         tl.createLine();
444         tl.endLayout();
445         int const line_wid = iround(line.horizontalAdvance());
446         if ((force && line.textLength() == offset) || line_wid > x)
447                 return {-1, -1};
448         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
449          * not be the same when there are high-plan unicode characters
450          * (bug #10443).
451          */
452         // The variable `offset' is here to account for the extra leading characters.
453         // The ending character zerow_nbsp has to be ignored if the line is complete.
454         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
455 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
456         int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
457 #else
458         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
459          * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
460          * length. We work around the problem by trying all docstring
461          * positions until the right one is found. This is slow only if
462          * there are many high-plane Unicode characters. It might be
463          * worthwhile to implement a dichotomy search if this shows up
464          * under a profiler.
465          */
466         int len = min(qlen, static_cast<int>(s.length()));
467         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
468                 --len;
469         LASSERT(len > 0 || qlen == 0, /**/);
470 #endif
471         return {len, line_wid};
472 }
473
474
475 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
476 {
477         PROFILE_THIS_BLOCK(breakAt);
478         if (s.empty())
479                 return false;
480
481         docstring const s_cache =
482                 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
483         pair<int, int> pp;
484
485         if (breakat_cache_.contains(s_cache))
486                 pp = breakat_cache_[s_cache];
487         else {
488                 PROFILE_CACHE_MISS(breakAt);
489                 pp = breakAt_helper(s, x, rtl, force);
490                 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
491         }
492         if (pp.first == -1)
493                 return false;
494         s = s.substr(0, pp.first);
495         x = pp.second;
496         return true;
497 }
498
499
500 void GuiFontMetrics::rectText(docstring const & str,
501         int & w, int & ascent, int & descent) const
502 {
503         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
504         int const offset = 4;
505
506         w = width(str) + offset;
507         ascent = metrics_.ascent() + offset / 2;
508         descent = metrics_.descent() + offset / 2;
509 }
510
511
512 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
513         int & w, int & ascent, int & descent) const
514 {
515         rectText(str, w, ascent, descent);
516         w += offset;
517 }
518
519
520 Dimension const GuiFontMetrics::defaultDimension() const
521 {
522         return Dimension(0, maxAscent(), maxDescent());
523 }
524
525
526 Dimension const GuiFontMetrics::dimension(char_type c) const
527 {
528         return Dimension(width(c), ascent(c), descent(c));
529 }
530
531
532 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
533                 char_type c) const
534 {
535         QRect r;
536         if (is_utf16(c))
537                 r = metrics_.boundingRect(ucs4_to_qchar(c));
538         else
539                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
540
541         AscendDescend ad = { -r.top(), r.bottom() + 1};
542         // We could as well compute the width but this is not really
543         // needed for now as it is done directly in width() below.
544         metrics_cache_.insert(c, ad);
545
546         return ad;
547 }
548
549
550 int GuiFontMetrics::width(char_type c) const
551 {
552         int value = width_cache_.value(c, outOfLimitMetric);
553         if (value != outOfLimitMetric)
554                 return value;
555
556         if (is_utf16(c))
557                 value = metrics_.width(ucs4_to_qchar(c));
558         else
559                 value = metrics_.width(toqstr(docstring(1, c)));
560
561         width_cache_.insert(c, value);
562
563         return value;
564 }
565
566
567 int GuiFontMetrics::ascent(char_type c) const
568 {
569         static AscendDescend const outOfLimitAD =
570                 {outOfLimitMetric, outOfLimitMetric};
571         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
572         if (value.ascent != outOfLimitMetric)
573                 return value.ascent;
574
575         value = fillMetricsCache(c);
576         return value.ascent;
577 }
578
579
580 int GuiFontMetrics::descent(char_type c) const
581 {
582         static AscendDescend const outOfLimitAD =
583                 {outOfLimitMetric, outOfLimitMetric};
584         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
585         if (value.descent != outOfLimitMetric)
586                 return value.descent;
587
588         value = fillMetricsCache(c);
589         return value.descent;
590 }
591
592 } // namespace frontend
593 } // namespace lyx