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