2 * \file GuiFontMetrics.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
14 #include "GuiFontMetrics.h"
16 #include "qt_helpers.h"
18 #include "Dimension.h"
20 #include "support/convert.h"
21 #include "support/lassert.h"
22 #include "support/lyxlib.h"
24 #define DISABLE_PMPROF
25 #include "support/pmprof.h"
30 using namespace lyx::support;
32 /* Define what mechanism is used to enforce text direction. Different
33 * methods work with different Qt versions. Here we try to use both
36 // Define to use unicode override characters to force direction
37 #define BIDI_USE_OVERRIDE
38 // Define to use flag to force direction
41 #ifdef BIDI_USE_OVERRIDE
42 # define BIDI_OFFSET 1
44 # define BIDI_OFFSET 0
47 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
48 # error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
54 * Argument-dependent lookup implies that this function shall be
55 * declared in the namespace of its argument. But this is std
56 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
58 uint qHash(lyx::docstring const & s)
60 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
61 s.size() * sizeof(lyx::docstring::value_type)));
71 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
72 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
73 * size of the QTextLayout objects anyway).
74 * Note that all these numbers are arbitrary.
75 * Also, setting size to 0 is tantamount to disabling the cache.
77 int cache_metrics_width_size = 1 << 19;
78 int cache_metrics_breakat_size = 1 << 19;
79 // Qt 5.x already has its own caching of QTextLayout objects
80 // but it does not seem to work well on MacOS X.
81 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
82 int cache_metrics_qtextlayout_size = 500;
84 int cache_metrics_qtextlayout_size = 0;
90 * Convert a UCS4 character into a QChar.
91 * This is a hack (it does only make sense for the common part of the UCS4
92 * and UTF16 encodings) and should not be used.
93 * This does only exist because of performance reasons (a real conversion
94 * using iconv is too slow on windows).
96 * This is no real conversion but a simple cast in reality. This is the reason
97 * why this works well for symbol fonts used in mathed too, even though
98 * these are not real ucs4 characters. These are codepoints in the
99 * computer modern fonts used, nothing unicode related.
100 * See comment in GuiPainter::text() for more explanation.
102 inline QChar const ucs4_to_qchar(char_type const ucs4)
104 LATTEST(is_utf16(ucs4));
105 return QChar(static_cast<unsigned short>(ucs4));
110 GuiFontMetrics::GuiFontMetrics(QFont const & font)
111 : font_(font), metrics_(font, 0),
112 strwidth_cache_(cache_metrics_width_size),
113 breakat_cache_(cache_metrics_breakat_size),
114 qtextlayout_cache_(cache_metrics_qtextlayout_size)
119 int GuiFontMetrics::maxAscent() const
121 return metrics_.ascent();
125 int GuiFontMetrics::maxDescent() const
127 // We add 1 as the value returned by QT is different than X
128 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
129 return metrics_.descent() + 1;
133 int GuiFontMetrics::em() const
135 return QFontInfo(font_).pixelSize();
139 int GuiFontMetrics::xHeight() const
141 // LATTEST(metrics_.xHeight() == ascent('x'));
142 return metrics_.xHeight();
146 int GuiFontMetrics::lineWidth() const
148 return metrics_.lineWidth();
152 int GuiFontMetrics::underlinePos() const
154 return metrics_.underlinePos();
158 int GuiFontMetrics::strikeoutPos() const
160 return metrics_.strikeOutPos();
164 bool GuiFontMetrics::italic() const
166 return font_.italic();
171 int const outOfLimitMetric = -10000;
175 int GuiFontMetrics::lbearing(char_type c) const
177 int value = lbearing_cache_.value(c, outOfLimitMetric);
178 if (value != outOfLimitMetric)
182 value = metrics_.leftBearing(ucs4_to_qchar(c));
184 // FIXME: QFontMetrics::leftBearing does not support the
185 // full unicode range. Once it does, we could use:
186 // metrics_.leftBearing(toqstr(docstring(1, c)));
190 lbearing_cache_.insert(c, value);
196 int GuiFontMetrics::rbearing(char_type c) const
198 int value = rbearing_cache_.value(c, outOfLimitMetric);
199 if (value != outOfLimitMetric)
202 // Qt rbearing is from the right edge of the char's width().
204 QChar sc = ucs4_to_qchar(c);
205 value = width(c) - metrics_.rightBearing(sc);
207 // FIXME: QFontMetrics::leftBearing does not support the
208 // full unicode range. Once it does, we could use:
209 // metrics_.rightBearing(toqstr(docstring(1, c)));
213 rbearing_cache_.insert(c, value);
219 int GuiFontMetrics::width(docstring const & s) const
221 PROFILE_THIS_BLOCK(width);
222 if (strwidth_cache_.contains(s))
223 return strwidth_cache_[s];
224 PROFILE_CACHE_MISS(width);
225 /* Several problems have to be taken into account:
226 * * QFontMetrics::width does not returns a wrong value with Qt5 with
227 * some arabic text, since the glyph-shaping operations are not
228 * done (documented in Qt5).
229 * * QTextLayout is broken for single characters with null width
230 * (like \not in mathed).
231 * * While QTextLine::horizontalAdvance is the right thing to use
232 * for text strings, it does not give a good result with some
233 * characters like the \int (gyph 4) of esint.
235 * The metrics of some of our math fonts (eg. esint) are such that
236 * QTextLine::horizontalAdvance leads, more or less, in the middle
237 * of a symbol. This is the horizontal position where a subscript
238 * should be drawn, so that the superscript has to be moved rightward.
239 * This is done when the kerning() method of the math insets returns
240 * a positive value. The problem with this choice is that navigating
241 * a formula becomes weird. For example, a selection extends only over
242 * about half of the symbol. In order to avoid this, with our math
243 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
244 * be drawn right after the symbol, and move the subscript leftward by
245 * recording a negative value for the kerning.
248 // is the string a single character from a math font ?
249 #if QT_VERSION >= 0x040800
250 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
252 bool const math_char = s.length() == 1;
255 QString const qs = toqstr(s);
256 int br_width = metrics_.boundingRect(qs).width();
257 #if QT_VERSION >= 0x050b00
258 int s_width = metrics_.horizontalAdvance(qs);
260 int s_width = metrics_.width(qs);
262 // keep value 0 for math chars with width 0
264 w = max(br_width, s_width);
267 tl.setText(toqstr(s));
270 QTextLine line = tl.createLine();
272 w = iround(line.horizontalAdvance());
274 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
279 int GuiFontMetrics::width(QString const & ucs2) const
281 return width(qstring_to_ucs4(ucs2));
285 int GuiFontMetrics::signedWidth(docstring const & s) const
291 return -width(s.substr(1, s.size() - 1));
297 shared_ptr<QTextLayout const>
298 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
299 double const wordspacing) const
301 PROFILE_THIS_BLOCK(getTextLayout);
302 docstring const s_cache =
303 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
304 if (auto ptl = qtextlayout_cache_[s_cache])
306 PROFILE_CACHE_MISS(getTextLayout);
307 auto const ptl = make_shared<QTextLayout>();
308 ptl->setCacheEnabled(true);
310 copy.setWordSpacing(wordspacing);
314 /* Use undocumented flag to enforce drawing direction
315 * FIXME: This does not work with Qt 5.11 (ticket #11284).
317 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
320 #ifdef BIDI_USE_OVERRIDE
321 /* Use unicode override characters to enforce drawing direction
322 * Source: http://www.iamcal.com/understanding-bidirectional-text/
325 // Right-to-left override: forces to draw text right-to-left
326 ptl->setText(QChar(0x202E) + toqstr(s));
328 // Left-to-right override: forces to draw text left-to-right
329 ptl->setText(QChar(0x202D) + toqstr(s));
331 ptl->setText(toqstr(s));
337 qtextlayout_cache_.insert(s_cache, ptl);
342 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
343 double const wordspacing) const
347 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
348 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
349 * not be the same when there are high-plan unicode characters
352 // BIDI_OFFSET accounts for a possible direction override
353 // character in front of the string.
354 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
355 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
359 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
360 double const wordspacing) const
362 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
363 QTextLine const & tline = tl->lineForTextPosition(0);
364 int qpos = tline.xToCursor(x);
365 int newx = static_cast<int>(tline.cursorToX(qpos));
366 // The value of qpos may be wrong in rtl text (see ticket #10569).
367 // To work around this, let's have a look at adjacent positions to
368 // see whether we find closer matches.
369 if (rtl && newx < x) {
371 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
372 if (abs(xm - x) < abs(newx - x)) {
378 } else if (rtl && newx > x) {
379 while (qpos < tline.textLength()) {
380 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
381 if (abs(xp - x) < abs(newx - x)) {
388 // correct x value to the actual cursor position.
391 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
392 * not be the same when there are high-plan unicode characters
395 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
396 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
397 // there may be a direction override character in front of the string.
398 return max(pos - BIDI_OFFSET, 0);
400 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
401 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
402 * length. We work around the problem by trying all docstring
403 * positions until the right one is found. This is slow only if
404 * there are many high-plane Unicode characters. It might be
405 * worthwhile to implement a dichotomy search if this shows up
408 // there may be a direction override character in front of the string.
409 qpos = max(qpos - BIDI_OFFSET, 0);
410 int pos = min(qpos, static_cast<int>(s.length()));
411 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
413 LASSERT(pos > 0 || qpos == 0, /**/);
419 int GuiFontMetrics::countExpanders(docstring const & str) const
421 // Numbers of characters that are expanded by inter-word spacing. These
422 // characters are spaces, except for characters 09-0D which are treated
423 // specially. (From a combination of testing with the notepad found in qt's
424 // examples, and reading the source code.) In addition, consecutive spaces
425 // only count as one expander.
426 bool wasspace = false;
428 for (char_type c : str)
429 if (c > 0x0d && QChar(c).isSpace()) {
441 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
442 bool const rtl, bool const force) const
445 /* Qt will not break at a leading or trailing space, and we need
446 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
448 * To work around the problem, we enclose the string between
449 * zero-width characters so that the QTextLayout algorithm will
450 * agree to break the text at these extremal spaces.
452 // Unicode character ZERO WIDTH NO-BREAK SPACE
453 QChar const zerow_nbsp(0xfeff);
454 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
456 /* Use undocumented flag to enforce drawing direction
457 * FIXME: This does not work with Qt 5.11 (ticket #11284).
459 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
462 #ifdef BIDI_USE_OVERRIDE
463 /* Use unicode override characters to enforce drawing direction
464 * Source: http://www.iamcal.com/understanding-bidirectional-text/
467 // Right-to-left override: forces to draw text right-to-left
468 qs = QChar(0x202E) + qs;
470 // Left-to-right override: forces to draw text left-to-right
471 qs = QChar(0x202D) + qs;
473 int const offset = 1 + BIDI_OFFSET;
478 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
479 : QTextOption::WordWrap);
480 tl.setTextOption(to);
482 QTextLine line = tl.createLine();
483 line.setLineWidth(x);
486 int const line_wid = iround(line.horizontalAdvance());
487 if ((force && line.textLength() == offset) || line_wid > x)
489 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
490 * not be the same when there are high-plan unicode characters
493 // The variable `offset' is here to account for the extra leading characters.
494 // The ending character zerow_nbsp has to be ignored if the line is complete.
495 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
496 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
497 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
499 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
500 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
501 * length. We work around the problem by trying all docstring
502 * positions until the right one is found. This is slow only if
503 * there are many high-plane Unicode characters. It might be
504 * worthwhile to implement a dichotomy search if this shows up
507 int len = min(qlen, static_cast<int>(s.length()));
508 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
510 LASSERT(len > 0 || qlen == 0, /**/);
512 return {len, line_wid};
516 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
518 PROFILE_THIS_BLOCK(breakAt);
522 docstring const s_cache =
523 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
526 if (breakat_cache_.contains(s_cache))
527 pp = breakat_cache_[s_cache];
529 PROFILE_CACHE_MISS(breakAt);
530 pp = breakAt_helper(s, x, rtl, force);
531 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
535 s = s.substr(0, pp.first);
541 void GuiFontMetrics::rectText(docstring const & str,
542 int & w, int & ascent, int & descent) const
544 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
545 int const offset = 4;
547 w = width(str) + offset;
548 ascent = metrics_.ascent() + offset / 2;
549 descent = metrics_.descent() + offset / 2;
553 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
554 int & w, int & ascent, int & descent) const
556 rectText(str, w, ascent, descent);
561 Dimension const GuiFontMetrics::defaultDimension() const
563 return Dimension(0, maxAscent(), maxDescent());
567 Dimension const GuiFontMetrics::dimension(char_type c) const
569 return Dimension(width(c), ascent(c), descent(c));
573 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
578 r = metrics_.boundingRect(ucs4_to_qchar(c));
580 r = metrics_.boundingRect(toqstr(docstring(1, c)));
582 AscendDescend ad = { -r.top(), r.bottom() + 1};
583 // We could as well compute the width but this is not really
584 // needed for now as it is done directly in width() below.
585 metrics_cache_.insert(c, ad);
591 int GuiFontMetrics::width(char_type c) const
593 int value = width_cache_.value(c, outOfLimitMetric);
594 if (value != outOfLimitMetric)
598 value = metrics_.width(ucs4_to_qchar(c));
600 value = metrics_.width(toqstr(docstring(1, c)));
602 width_cache_.insert(c, value);
608 int GuiFontMetrics::ascent(char_type c) const
610 static AscendDescend const outOfLimitAD =
611 {outOfLimitMetric, outOfLimitMetric};
612 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
613 if (value.ascent != outOfLimitMetric)
616 value = fillMetricsCache(c);
621 int GuiFontMetrics::descent(char_type c) const
623 static AscendDescend const outOfLimitAD =
624 {outOfLimitMetric, outOfLimitMetric};
625 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
626 if (value.descent != outOfLimitMetric)
627 return value.descent;
629 value = fillMetricsCache(c);
630 return value.descent;
633 } // namespace frontend