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();
165 int const outOfLimitMetric = -10000;
169 int GuiFontMetrics::lbearing(char_type c) const
171 int value = lbearing_cache_.value(c, outOfLimitMetric);
172 if (value != outOfLimitMetric)
176 value = metrics_.leftBearing(ucs4_to_qchar(c));
178 // FIXME: QFontMetrics::leftBearing does not support the
179 // full unicode range. Once it does, we could use:
180 // metrics_.leftBearing(toqstr(docstring(1, c)));
184 lbearing_cache_.insert(c, value);
190 int GuiFontMetrics::rbearing(char_type c) const
192 int value = rbearing_cache_.value(c, outOfLimitMetric);
193 if (value != outOfLimitMetric)
196 // Qt rbearing is from the right edge of the char's width().
198 QChar sc = ucs4_to_qchar(c);
199 value = width(c) - metrics_.rightBearing(sc);
201 // FIXME: QFontMetrics::leftBearing does not support the
202 // full unicode range. Once it does, we could use:
203 // metrics_.rightBearing(toqstr(docstring(1, c)));
207 rbearing_cache_.insert(c, value);
213 int GuiFontMetrics::width(docstring const & s) const
215 PROFILE_THIS_BLOCK(width);
216 if (strwidth_cache_.contains(s))
217 return strwidth_cache_[s];
218 PROFILE_CACHE_MISS(width);
219 /* Several problems have to be taken into account:
220 * * QFontMetrics::width does not returns a wrong value with Qt5 with
221 * some arabic text, since the glyph-shaping operations are not
222 * done (documented in Qt5).
223 * * QTextLayout is broken for single characters with null width
224 * (like \not in mathed).
225 * * While QTextLine::horizontalAdvance is the right thing to use
226 * for text strings, it does not give a good result with some
227 * characters like the \int (gyph 4) of esint.
229 * Also, as a safety measure, always use QFontMetrics::width with
233 // is the string a single character from a math font ?
234 #if QT_VERSION >= 0x040800
235 bool const math_char = s.length() == 1 || font_.styleName() == "LyX";
237 bool const math_char = s.length() == 1;
239 // keep value 0 for math chars with width 0
240 if (!math_char || metrics_.width(toqstr(s)) != 0) {
242 tl.setText(toqstr(s));
245 QTextLine line = tl.createLine();
248 w = iround(line.naturalTextWidth());
250 w = iround(line.horizontalAdvance());
252 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
257 int GuiFontMetrics::width(QString const & ucs2) const
259 return width(qstring_to_ucs4(ucs2));
263 int GuiFontMetrics::signedWidth(docstring const & s) const
269 return -width(s.substr(1, s.size() - 1));
275 shared_ptr<QTextLayout const>
276 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
277 double const wordspacing) const
279 PROFILE_THIS_BLOCK(getTextLayout);
280 docstring const s_cache =
281 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
282 if (auto ptl = qtextlayout_cache_[s_cache])
284 PROFILE_CACHE_MISS(getTextLayout);
285 auto const ptl = make_shared<QTextLayout>();
286 ptl->setCacheEnabled(true);
288 copy.setWordSpacing(wordspacing);
292 /* Use undocumented flag to enforce drawing direction
293 * FIXME: This does not work with Qt 5.11 (ticket #11284).
295 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
298 #ifdef BIDI_USE_OVERRIDE
299 /* Use unicode override characters to enforce drawing direction
300 * Source: http://www.iamcal.com/understanding-bidirectional-text/
303 // Right-to-left override: forces to draw text right-to-left
304 ptl->setText(QChar(0x202E) + toqstr(s));
306 // Left-to-right override: forces to draw text left-to-right
307 ptl->setText(QChar(0x202D) + toqstr(s));
309 ptl->setText(toqstr(s));
315 qtextlayout_cache_.insert(s_cache, ptl);
320 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
321 double const wordspacing) const
325 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
326 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
327 * not be the same when there are high-plan unicode characters
330 // BIDI_OFFSET accounts for a possible direction override
331 // character in front of the string.
332 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
333 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
337 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
338 double const wordspacing) const
340 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
341 QTextLine const & tline = tl->lineForTextPosition(0);
342 int qpos = tline.xToCursor(x);
343 int newx = static_cast<int>(tline.cursorToX(qpos));
344 // The value of qpos may be wrong in rtl text (see ticket #10569).
345 // To work around this, let's have a look at adjacent positions to
346 // see whether we find closer matches.
347 if (rtl && newx < x) {
349 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
350 if (abs(xm - x) < abs(newx - x)) {
356 } else if (rtl && newx > x) {
357 while (qpos < tline.textLength()) {
358 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
359 if (abs(xp - x) < abs(newx - x)) {
366 // correct x value to the actual cursor position.
369 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
370 * not be the same when there are high-plan unicode characters
373 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
374 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
375 // there may be a direction override character in front of the string.
376 return max(pos - BIDI_OFFSET, 0);
378 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
379 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
380 * length. We work around the problem by trying all docstring
381 * positions until the right one is found. This is slow only if
382 * there are many high-plane Unicode characters. It might be
383 * worthwhile to implement a dichotomy search if this shows up
386 // there may be a direction override character in front of the string.
387 qpos = max(qpos - BIDI_OFFSET, 0);
388 int pos = min(qpos, static_cast<int>(s.length()));
389 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
391 LASSERT(pos > 0 || qpos == 0, /**/);
397 int GuiFontMetrics::countExpanders(docstring const & str) const
399 // Numbers of characters that are expanded by inter-word spacing. These
400 // characters are spaces, except for characters 09-0D which are treated
401 // specially. (From a combination of testing with the notepad found in qt's
402 // examples, and reading the source code.) In addition, consecutive spaces
403 // only count as one expander.
404 bool wasspace = false;
406 for (char_type c : str)
407 if (c > 0x0d && QChar(c).isSpace()) {
419 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
420 bool const rtl, bool const force) const
423 /* Qt will not break at a leading or trailing space, and we need
424 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
426 * To work around the problem, we enclose the string between
427 * zero-width characters so that the QTextLayout algorithm will
428 * agree to break the text at these extremal spaces.
430 // Unicode character ZERO WIDTH NO-BREAK SPACE
431 QChar const zerow_nbsp(0xfeff);
432 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
434 /* Use undocumented flag to enforce drawing direction
435 * FIXME: This does not work with Qt 5.11 (ticket #11284).
437 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
440 #ifdef BIDI_USE_OVERRIDE
441 /* Use unicode override characters to enforce drawing direction
442 * Source: http://www.iamcal.com/understanding-bidirectional-text/
445 // Right-to-left override: forces to draw text right-to-left
446 qs = QChar(0x202E) + qs;
448 // Left-to-right override: forces to draw text left-to-right
449 qs = QChar(0x202D) + qs;
451 int const offset = 1 + BIDI_OFFSET;
456 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
457 : QTextOption::WordWrap);
458 tl.setTextOption(to);
460 QTextLine line = tl.createLine();
461 line.setLineWidth(x);
464 int const line_wid = iround(line.horizontalAdvance());
465 if ((force && line.textLength() == offset) || line_wid > x)
467 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
468 * not be the same when there are high-plan unicode characters
471 // The variable `offset' is here to account for the extra leading characters.
472 // The ending character zerow_nbsp has to be ignored if the line is complete.
473 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
474 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
475 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
477 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
478 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
479 * length. We work around the problem by trying all docstring
480 * positions until the right one is found. This is slow only if
481 * there are many high-plane Unicode characters. It might be
482 * worthwhile to implement a dichotomy search if this shows up
485 int len = min(qlen, static_cast<int>(s.length()));
486 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
488 LASSERT(len > 0 || qlen == 0, /**/);
490 return {len, line_wid};
494 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
496 PROFILE_THIS_BLOCK(breakAt);
500 docstring const s_cache =
501 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
504 if (breakat_cache_.contains(s_cache))
505 pp = breakat_cache_[s_cache];
507 PROFILE_CACHE_MISS(breakAt);
508 pp = breakAt_helper(s, x, rtl, force);
509 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
513 s = s.substr(0, pp.first);
519 void GuiFontMetrics::rectText(docstring const & str,
520 int & w, int & ascent, int & descent) const
522 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
523 int const offset = 4;
525 w = width(str) + offset;
526 ascent = metrics_.ascent() + offset / 2;
527 descent = metrics_.descent() + offset / 2;
531 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
532 int & w, int & ascent, int & descent) const
534 rectText(str, w, ascent, descent);
539 Dimension const GuiFontMetrics::defaultDimension() const
541 return Dimension(0, maxAscent(), maxDescent());
545 Dimension const GuiFontMetrics::dimension(char_type c) const
547 return Dimension(width(c), ascent(c), descent(c));
551 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
556 r = metrics_.boundingRect(ucs4_to_qchar(c));
558 r = metrics_.boundingRect(toqstr(docstring(1, c)));
560 AscendDescend ad = { -r.top(), r.bottom() + 1};
561 // We could as well compute the width but this is not really
562 // needed for now as it is done directly in width() below.
563 metrics_cache_.insert(c, ad);
569 int GuiFontMetrics::width(char_type c) const
571 int value = width_cache_.value(c, outOfLimitMetric);
572 if (value != outOfLimitMetric)
576 value = metrics_.width(ucs4_to_qchar(c));
578 value = metrics_.width(toqstr(docstring(1, c)));
580 width_cache_.insert(c, value);
586 int GuiFontMetrics::ascent(char_type c) const
588 static AscendDescend const outOfLimitAD =
589 {outOfLimitMetric, outOfLimitMetric};
590 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
591 if (value.ascent != outOfLimitMetric)
594 value = fillMetricsCache(c);
599 int GuiFontMetrics::descent(char_type c) const
601 static AscendDescend const outOfLimitAD =
602 {outOfLimitMetric, outOfLimitMetric};
603 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
604 if (value.descent != outOfLimitMetric)
605 return value.descent;
607 value = fillMetricsCache(c);
608 return value.descent;
611 } // namespace frontend