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"
23 #include "support/debug.h"
25 #define DISABLE_PMPROF
26 #include "support/pmprof.h"
32 #if QT_VERSION >= 0x050100
35 #define qDegreesToRadians(degree) (degree * (M_PI / 180))
39 using namespace lyx::support;
41 /* Define what mechanism is used to enforce text direction. Different
42 * methods work with different Qt versions. Here we try to use both
45 // Define to use unicode override characters to force direction
46 #define BIDI_USE_OVERRIDE
47 // Define to use flag to force direction
50 #ifdef BIDI_USE_OVERRIDE
51 # define BIDI_OFFSET 1
53 # define BIDI_OFFSET 0
56 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
57 # error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
61 #if QT_VERSION < 0x050000
62 inline uint qHash(double key)
64 return qHash(QByteArray(reinterpret_cast<char const *>(&key), sizeof(key)));
72 * Argument-dependent lookup implies that this function shall be
73 * declared in the namespace of its argument. But this is std
74 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
76 uint qHash(lyx::docstring const & s)
78 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
79 s.size() * sizeof(lyx::docstring::value_type)));
89 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
90 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
91 * size of the QTextLayout objects anyway).
92 * Note that all these numbers are arbitrary.
93 * Also, setting size to 0 is tantamount to disabling the cache.
95 int cache_metrics_width_size = 1 << 19;
96 int cache_metrics_breakat_size = 1 << 19;
97 // Qt 5.x already has its own caching of QTextLayout objects
98 // but it does not seem to work well on MacOS X.
99 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
100 int cache_metrics_qtextlayout_size = 500;
102 int cache_metrics_qtextlayout_size = 0;
108 * Convert a UCS4 character into a QChar.
109 * This is a hack (it does only make sense for the common part of the UCS4
110 * and UTF16 encodings) and should not be used.
111 * This does only exist because of performance reasons (a real conversion
112 * using iconv is too slow on windows).
114 * This is no real conversion but a simple cast in reality. This is the reason
115 * why this works well for symbol fonts used in mathed too, even though
116 * these are not real ucs4 characters. These are codepoints in the
117 * computer modern fonts used, nothing unicode related.
118 * See comment in GuiPainter::text() for more explanation.
120 inline QChar const ucs4_to_qchar(char_type const ucs4)
122 LATTEST(is_utf16(ucs4));
123 return QChar(static_cast<unsigned short>(ucs4));
128 GuiFontMetrics::GuiFontMetrics(QFont const & font)
129 : font_(font), metrics_(font, 0),
130 strwidth_cache_(cache_metrics_width_size),
131 breakat_cache_(cache_metrics_breakat_size),
132 qtextlayout_cache_(cache_metrics_qtextlayout_size)
134 // Determine italic slope
135 double const defaultSlope = tan(qDegreesToRadians(19.0));
136 QRawFont raw = QRawFont::fromFont(font);
137 QByteArray post(raw.fontTable("post"));
138 if (post.length() == 0) {
139 slope_ = defaultSlope;
140 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
142 // post table description:
143 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
144 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
145 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
146 slope_ = -tan(qDegreesToRadians(angle));
147 // Correct italic fonts with zero slope
148 if (slope_ == 0.0 && font.italic())
149 slope_ = defaultSlope;
150 LYXERR(Debug::FONT, "Italic slope: " << slope_);
155 int GuiFontMetrics::maxAscent() const
157 return metrics_.ascent();
161 int GuiFontMetrics::maxDescent() const
163 // We add 1 as the value returned by QT is different than X
164 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
166 return metrics_.descent() + 1;
170 int GuiFontMetrics::em() const
172 return QFontInfo(font_).pixelSize();
176 int GuiFontMetrics::xHeight() const
178 // LATTEST(metrics_.xHeight() == ascent('x'));
179 return metrics_.xHeight();
183 int GuiFontMetrics::lineWidth() const
185 return metrics_.lineWidth();
189 int GuiFontMetrics::underlinePos() const
191 return metrics_.underlinePos();
195 int GuiFontMetrics::strikeoutPos() const
197 return metrics_.strikeOutPos();
201 bool GuiFontMetrics::italic() const
203 return font_.italic();
207 double GuiFontMetrics::italicSlope() const
214 int const outOfLimitMetric = -10000;
218 int GuiFontMetrics::lbearing(char_type c) const
220 int value = lbearing_cache_.value(c, outOfLimitMetric);
221 if (value != outOfLimitMetric)
225 value = metrics_.leftBearing(ucs4_to_qchar(c));
227 // FIXME: QFontMetrics::leftBearing does not support the
228 // full unicode range. Once it does, we could use:
229 // metrics_.leftBearing(toqstr(docstring(1, c)));
233 lbearing_cache_.insert(c, value);
239 int GuiFontMetrics::rbearing(char_type c) const
241 int value = rbearing_cache_.value(c, outOfLimitMetric);
242 if (value != outOfLimitMetric)
245 // Qt rbearing is from the right edge of the char's width().
247 QChar sc = ucs4_to_qchar(c);
248 value = width(c) - metrics_.rightBearing(sc);
250 // FIXME: QFontMetrics::leftBearing does not support the
251 // full unicode range. Once it does, we could use:
252 // metrics_.rightBearing(toqstr(docstring(1, c)));
256 rbearing_cache_.insert(c, value);
262 int GuiFontMetrics::width(docstring const & s) const
264 PROFILE_THIS_BLOCK(width);
265 if (int * wid_p = strwidth_cache_.object_ptr(s))
267 PROFILE_CACHE_MISS(width);
268 /* Several problems have to be taken into account:
269 * * QFontMetrics::width does not returns a wrong value with Qt5 with
270 * some arabic text, since the glyph-shaping operations are not
271 * done (documented in Qt5).
272 * * QTextLayout is broken for single characters with null width
273 * (like \not in mathed).
274 * * While QTextLine::horizontalAdvance is the right thing to use
275 * for text strings, it does not give a good result with some
276 * characters like the \int (gyph 4) of esint.
278 * The metrics of some of our math fonts (eg. esint) are such that
279 * QTextLine::horizontalAdvance leads, more or less, in the middle
280 * of a symbol. This is the horizontal position where a subscript
281 * should be drawn, so that the superscript has to be moved rightward.
282 * This is done when the kerning() method of the math insets returns
283 * a positive value. The problem with this choice is that navigating
284 * a formula becomes weird. For example, a selection extends only over
285 * about half of the symbol. In order to avoid this, with our math
286 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
287 * be drawn right after the symbol, and move the subscript leftward by
288 * recording a negative value for the kerning.
291 // is the string a single character from a math font ?
292 #if QT_VERSION >= 0x040800
293 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
295 bool const math_char = s.length() == 1;
298 QString const qs = toqstr(s);
299 int br_width = metrics_.boundingRect(qs).width();
300 #if QT_VERSION >= 0x050b00
301 int s_width = metrics_.horizontalAdvance(qs);
303 int s_width = metrics_.width(qs);
305 // keep value 0 for math chars with width 0
307 w = max(br_width, s_width);
310 tl.setText(toqstr(s));
313 QTextLine line = tl.createLine();
315 w = iround(line.horizontalAdvance());
317 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
322 int GuiFontMetrics::width(QString const & ucs2) const
324 return width(qstring_to_ucs4(ucs2));
328 int GuiFontMetrics::signedWidth(docstring const & s) const
334 return -width(s.substr(1, s.size() - 1));
340 uint qHash(TextLayoutKey const & key)
342 double params = (2 * key.rtl - 1) * key.ws;
343 return std::qHash(key.s) ^ ::qHash(params);
346 shared_ptr<QTextLayout const>
347 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
348 double const wordspacing) const
350 PROFILE_THIS_BLOCK(getTextLayout);
351 TextLayoutKey key{s, rtl, wordspacing};
352 if (auto ptl = qtextlayout_cache_[key])
354 PROFILE_CACHE_MISS(getTextLayout);
355 auto const ptl = make_shared<QTextLayout>();
356 ptl->setCacheEnabled(true);
358 copy.setWordSpacing(wordspacing);
362 /* Use undocumented flag to enforce drawing direction
363 * FIXME: This does not work with Qt 5.11 (ticket #11284).
365 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
368 #ifdef BIDI_USE_OVERRIDE
369 /* Use unicode override characters to enforce drawing direction
370 * Source: http://www.iamcal.com/understanding-bidirectional-text/
373 // Right-to-left override: forces to draw text right-to-left
374 ptl->setText(QChar(0x202E) + toqstr(s));
376 // Left-to-right override: forces to draw text left-to-right
377 ptl->setText(QChar(0x202D) + toqstr(s));
379 ptl->setText(toqstr(s));
385 qtextlayout_cache_.insert(key, ptl);
390 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
391 double const wordspacing) const
395 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
396 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
397 * not be the same when there are high-plan unicode characters
400 // BIDI_OFFSET accounts for a possible direction override
401 // character in front of the string.
402 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
403 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
407 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
408 double const wordspacing) const
410 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
411 QTextLine const & tline = tl->lineForTextPosition(0);
412 int qpos = tline.xToCursor(x);
413 int newx = static_cast<int>(tline.cursorToX(qpos));
414 // The value of qpos may be wrong in rtl text (see ticket #10569).
415 // To work around this, let's have a look at adjacent positions to
416 // see whether we find closer matches.
417 if (rtl && newx < x) {
419 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
420 if (abs(xm - x) < abs(newx - x)) {
426 } else if (rtl && newx > x) {
427 while (qpos < tline.textLength()) {
428 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
429 if (abs(xp - x) < abs(newx - x)) {
436 // correct x value to the actual cursor position.
439 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
440 * not be the same when there are high-plan unicode characters
443 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
444 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
445 // there may be a direction override character in front of the string.
446 return max(pos - BIDI_OFFSET, 0);
448 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
449 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
450 * length. We work around the problem by trying all docstring
451 * positions until the right one is found. This is slow only if
452 * there are many high-plane Unicode characters. It might be
453 * worthwhile to implement a dichotomy search if this shows up
456 // there may be a direction override character in front of the string.
457 qpos = max(qpos - BIDI_OFFSET, 0);
458 int pos = min(qpos, static_cast<int>(s.length()));
459 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
461 LASSERT(pos > 0 || qpos == 0, /**/);
467 int GuiFontMetrics::countExpanders(docstring const & str) const
469 // Numbers of characters that are expanded by inter-word spacing. These
470 // characters are spaces, except for characters 09-0D which are treated
471 // specially. (From a combination of testing with the notepad found in qt's
472 // examples, and reading the source code.) In addition, consecutive spaces
473 // only count as one expander.
474 bool wasspace = false;
476 for (char_type c : str)
477 if (c > 0x0d && QChar(c).isSpace()) {
489 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
490 bool const rtl, bool const force) const
493 /* Qt will not break at a leading or trailing space, and we need
494 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
496 * To work around the problem, we enclose the string between
497 * zero-width characters so that the QTextLayout algorithm will
498 * agree to break the text at these extremal spaces.
500 // Unicode character ZERO WIDTH NO-BREAK SPACE
501 QChar const zerow_nbsp(0xfeff);
502 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
504 /* Use undocumented flag to enforce drawing direction
505 * FIXME: This does not work with Qt 5.11 (ticket #11284).
507 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
510 #ifdef BIDI_USE_OVERRIDE
511 /* Use unicode override characters to enforce drawing direction
512 * Source: http://www.iamcal.com/understanding-bidirectional-text/
515 // Right-to-left override: forces to draw text right-to-left
516 qs = QChar(0x202E) + qs;
518 // Left-to-right override: forces to draw text left-to-right
519 qs = QChar(0x202D) + qs;
521 int const offset = 1 + BIDI_OFFSET;
526 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
527 : QTextOption::WordWrap);
528 tl.setTextOption(to);
530 QTextLine line = tl.createLine();
531 line.setLineWidth(x);
534 int line_wid = iround(line.horizontalAdvance());
535 if ((force && line.textLength() == offset) || line_wid > x)
536 return {-1, line_wid};
537 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
538 * not be the same when there are high-plan unicode characters
541 // The variable `offset' is here to account for the extra leading characters.
542 // The ending character zerow_nbsp has to be ignored if the line is complete.
543 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
544 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
545 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
547 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
548 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
549 * length. We work around the problem by trying all docstring
550 * positions until the right one is found. This is slow only if
551 * there are many high-plane Unicode characters. It might be
552 * worthwhile to implement a dichotomy search if this shows up
555 int len = min(qlen, static_cast<int>(s.length()));
556 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
558 LASSERT(len > 0 || qlen == 0, /**/);
560 // Do not cut is the string is already short enough
561 if (len == static_cast<int>(s.length())) {
563 #if QT_VERSION < 0x050000
564 // With some monospace fonts, the value of horizontalAdvance()
565 // can be wrong with Qt4. One hypothesis is that the invisible
566 // characters that we use are given a non-null width.
570 return {len, line_wid};
574 uint qHash(BreakAtKey const & key)
576 int params = key.force + 2 * key.rtl + 4 * key.x;
577 return std::qHash(key.s) ^ ::qHash(params);
581 int GuiFontMetrics::breakAt(docstring const & s, int & x, bool const rtl, bool const force) const
583 PROFILE_THIS_BLOCK(breakAt);
587 BreakAtKey key{s, x, rtl, force};
589 if (auto * pp_ptr = breakat_cache_.object_ptr(key))
592 PROFILE_CACHE_MISS(breakAt);
593 pp = breakAt_helper(s, x, rtl, force);
594 breakat_cache_.insert(key, pp, sizeof(key) + s.size() * sizeof(char_type));
601 void GuiFontMetrics::rectText(docstring const & str,
602 int & w, int & ascent, int & descent) const
604 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
605 int const offset = 4;
607 w = width(str) + offset;
608 ascent = metrics_.ascent() + offset / 2;
609 descent = metrics_.descent() + offset / 2;
613 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
614 int & w, int & ascent, int & descent) const
616 rectText(str, w, ascent, descent);
621 Dimension const GuiFontMetrics::defaultDimension() const
623 return Dimension(0, maxAscent(), maxDescent());
627 Dimension const GuiFontMetrics::dimension(char_type c) const
629 return Dimension(width(c), ascent(c), descent(c));
633 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
638 r = metrics_.boundingRect(ucs4_to_qchar(c));
640 r = metrics_.boundingRect(toqstr(docstring(1, c)));
642 AscendDescend ad = { -r.top(), r.bottom() + 1};
643 // We could as well compute the width but this is not really
644 // needed for now as it is done directly in width() below.
645 metrics_cache_.insert(c, ad);
651 int GuiFontMetrics::width(char_type c) const
653 int value = width_cache_.value(c, outOfLimitMetric);
654 if (value != outOfLimitMetric)
657 #if QT_VERSION >= 0x050b00
659 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
661 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
664 value = metrics_.width(ucs4_to_qchar(c));
666 value = metrics_.width(toqstr(docstring(1, c)));
669 width_cache_.insert(c, value);
675 int GuiFontMetrics::ascent(char_type c) const
677 static AscendDescend const outOfLimitAD =
678 {outOfLimitMetric, outOfLimitMetric};
679 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
680 if (value.ascent != outOfLimitMetric)
683 value = fillMetricsCache(c);
688 int GuiFontMetrics::descent(char_type c) const
690 static AscendDescend const outOfLimitAD =
691 {outOfLimitMetric, outOfLimitMetric};
692 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
693 if (value.descent != outOfLimitMetric)
694 return value.descent;
696 value = fillMetricsCache(c);
697 return value.descent;
700 } // namespace frontend