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/lstrings.h"
23 #include "support/lyxlib.h"
24 #include "support/debug.h"
26 #define DISABLE_PMPROF
27 #include "support/pmprof.h"
33 #if QT_VERSION >= 0x050100
36 #define qDegreesToRadians(degree) (degree * (M_PI / 180))
40 using namespace lyx::support;
42 /* Define what mechanism is used to enforce text direction. Different
43 * methods work with different Qt versions. Here we try to use both
46 // Define to use unicode override characters to force direction
47 #define BIDI_USE_OVERRIDE
48 // Define to use flag to force direction
51 #ifdef BIDI_USE_OVERRIDE
52 # define BIDI_OFFSET 1
54 # define BIDI_OFFSET 0
57 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
58 # error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
62 #if QT_VERSION < 0x050000
63 inline uint qHash(double key)
65 return qHash(QByteArray(reinterpret_cast<char const *>(&key), sizeof(key)));
73 * Argument-dependent lookup implies that this function shall be
74 * declared in the namespace of its argument. But this is std
75 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
77 uint qHash(lyx::docstring const & s)
79 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
80 s.size() * sizeof(lyx::docstring::value_type)));
90 * Limit (strwidth|breakstr)_cache_ size to 512kB of string data.
91 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
92 * size of the QTextLayout objects anyway).
93 * Note that all these numbers are arbitrary.
94 * Also, setting size to 0 is tantamount to disabling the cache.
96 int cache_metrics_width_size = 1 << 19;
97 int cache_metrics_breakstr_size = 1 << 19;
98 // Qt 5.x already has its own caching of QTextLayout objects
99 // but it does not seem to work well on MacOS X.
100 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
101 int cache_metrics_qtextlayout_size = 500;
103 int cache_metrics_qtextlayout_size = 0;
109 * Convert a UCS4 character into a QChar.
110 * This is a hack (it does only make sense for the common part of the UCS4
111 * and UTF16 encodings) and should not be used.
112 * This does only exist because of performance reasons (a real conversion
113 * using iconv is too slow on windows).
115 * This is no real conversion but a simple cast in reality. This is the reason
116 * why this works well for symbol fonts used in mathed too, even though
117 * these are not real ucs4 characters. These are codepoints in the
118 * computer modern fonts used, nothing unicode related.
119 * See comment in GuiPainter::text() for more explanation.
121 inline QChar const ucs4_to_qchar(char_type const ucs4)
123 LATTEST(is_utf16(ucs4));
124 return QChar(static_cast<unsigned short>(ucs4));
129 GuiFontMetrics::GuiFontMetrics(QFont const & font)
130 : font_(font), metrics_(font, 0),
131 strwidth_cache_(cache_metrics_width_size),
132 breakstr_cache_(cache_metrics_breakstr_size),
133 qtextlayout_cache_(cache_metrics_qtextlayout_size)
135 // Determine italic slope
136 double const defaultSlope = tan(qDegreesToRadians(19.0));
137 QRawFont raw = QRawFont::fromFont(font);
138 QByteArray post(raw.fontTable("post"));
139 if (post.length() == 0) {
140 slope_ = defaultSlope;
141 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
143 // post table description:
144 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
145 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
146 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
147 slope_ = -tan(qDegreesToRadians(angle));
148 // Correct italic fonts with zero slope
149 if (slope_ == 0.0 && font.italic())
150 slope_ = defaultSlope;
151 LYXERR(Debug::FONT, "Italic slope: " << slope_);
156 int GuiFontMetrics::maxAscent() const
158 return metrics_.ascent();
162 int GuiFontMetrics::maxDescent() const
164 // We add 1 as the value returned by QT is different than X
165 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
167 return metrics_.descent() + 1;
171 int GuiFontMetrics::em() const
173 return QFontInfo(font_).pixelSize();
177 int GuiFontMetrics::xHeight() const
179 // LATTEST(metrics_.xHeight() == ascent('x'));
180 return metrics_.xHeight();
184 int GuiFontMetrics::lineWidth() const
186 return metrics_.lineWidth();
190 int GuiFontMetrics::underlinePos() const
192 return metrics_.underlinePos();
196 int GuiFontMetrics::strikeoutPos() const
198 return metrics_.strikeOutPos();
202 bool GuiFontMetrics::italic() const
204 return font_.italic();
208 double GuiFontMetrics::italicSlope() const
215 int const outOfLimitMetric = -10000;
219 int GuiFontMetrics::lbearing(char_type c) const
221 int value = lbearing_cache_.value(c, outOfLimitMetric);
222 if (value != outOfLimitMetric)
226 value = metrics_.leftBearing(ucs4_to_qchar(c));
228 // FIXME: QFontMetrics::leftBearing does not support the
229 // full unicode range. Once it does, we could use:
230 // metrics_.leftBearing(toqstr(docstring(1, c)));
234 lbearing_cache_.insert(c, value);
240 int GuiFontMetrics::rbearing(char_type c) const
242 int value = rbearing_cache_.value(c, outOfLimitMetric);
243 if (value != outOfLimitMetric)
246 // Qt rbearing is from the right edge of the char's width().
248 QChar sc = ucs4_to_qchar(c);
249 value = width(c) - metrics_.rightBearing(sc);
251 // FIXME: QFontMetrics::leftBearing does not support the
252 // full unicode range. Once it does, we could use:
253 // metrics_.rightBearing(toqstr(docstring(1, c)));
257 rbearing_cache_.insert(c, value);
263 int GuiFontMetrics::width(docstring const & s) const
265 PROFILE_THIS_BLOCK(width);
266 if (int * wid_p = strwidth_cache_.object_ptr(s))
268 PROFILE_CACHE_MISS(width);
269 /* Several problems have to be taken into account:
270 * * QFontMetrics::width does not returns a wrong value with Qt5 with
271 * some arabic text, since the glyph-shaping operations are not
272 * done (documented in Qt5).
273 * * QTextLayout is broken for single characters with null width
274 * (like \not in mathed).
275 * * While QTextLine::horizontalAdvance is the right thing to use
276 * for text strings, it does not give a good result with some
277 * characters like the \int (gyph 4) of esint.
279 * The metrics of some of our math fonts (eg. esint) are such that
280 * QTextLine::horizontalAdvance leads, more or less, in the middle
281 * of a symbol. This is the horizontal position where a subscript
282 * should be drawn, so that the superscript has to be moved rightward.
283 * This is done when the kerning() method of the math insets returns
284 * a positive value. The problem with this choice is that navigating
285 * a formula becomes weird. For example, a selection extends only over
286 * about half of the symbol. In order to avoid this, with our math
287 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
288 * be drawn right after the symbol, and move the subscript leftward by
289 * recording a negative value for the kerning.
292 // is the string a single character from a math font ?
293 #if QT_VERSION >= 0x040800
294 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
296 bool const math_char = s.length() == 1;
299 QString const qs = toqstr(s);
300 int br_width = metrics_.boundingRect(qs).width();
301 #if QT_VERSION >= 0x050b00
302 int s_width = metrics_.horizontalAdvance(qs);
304 int s_width = metrics_.width(qs);
306 // keep value 0 for math chars with width 0
308 w = max(br_width, s_width);
311 tl.setText(toqstr(s));
314 QTextLine line = tl.createLine();
316 w = iround(line.horizontalAdvance());
318 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
323 int GuiFontMetrics::width(QString const & ucs2) const
325 return width(qstring_to_ucs4(ucs2));
329 int GuiFontMetrics::signedWidth(docstring const & s) const
335 return -width(s.substr(1, s.size() - 1));
341 uint qHash(TextLayoutKey const & key)
343 double params = (2 * key.rtl - 1) * key.ws;
344 return std::qHash(key.s) ^ ::qHash(params);
347 shared_ptr<QTextLayout const>
348 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
349 double const wordspacing) const
351 PROFILE_THIS_BLOCK(getTextLayout);
352 TextLayoutKey key{s, rtl, wordspacing};
353 if (auto ptl = qtextlayout_cache_[key])
355 PROFILE_CACHE_MISS(getTextLayout);
356 auto const ptl = make_shared<QTextLayout>();
357 ptl->setCacheEnabled(true);
359 copy.setWordSpacing(wordspacing);
363 /* Use undocumented flag to enforce drawing direction
364 * FIXME: This does not work with Qt 5.11 (ticket #11284).
366 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
369 #ifdef BIDI_USE_OVERRIDE
370 /* Use unicode override characters to enforce drawing direction
371 * Source: http://www.iamcal.com/understanding-bidirectional-text/
374 // Right-to-left override: forces to draw text right-to-left
375 ptl->setText(QChar(0x202E) + toqstr(s));
377 // Left-to-right override: forces to draw text left-to-right
378 ptl->setText(QChar(0x202D) + toqstr(s));
380 ptl->setText(toqstr(s));
386 qtextlayout_cache_.insert(key, ptl);
391 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
392 double const wordspacing) const
396 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
397 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
398 * not be the same when there are high-plan unicode characters
401 // BIDI_OFFSET accounts for a possible direction override
402 // character in front of the string.
403 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
404 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
408 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
409 double const wordspacing) const
411 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
412 QTextLine const & tline = tl->lineForTextPosition(0);
413 int qpos = tline.xToCursor(x);
414 int newx = static_cast<int>(tline.cursorToX(qpos));
415 // The value of qpos may be wrong in rtl text (see ticket #10569).
416 // To work around this, let's have a look at adjacent positions to
417 // see whether we find closer matches.
418 if (rtl && newx < x) {
420 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
421 if (abs(xm - x) < abs(newx - x)) {
427 } else if (rtl && newx > x) {
428 while (qpos < tline.textLength()) {
429 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
430 if (abs(xp - x) < abs(newx - x)) {
437 // correct x value to the actual cursor position.
440 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
441 * not be the same when there are high-plan unicode characters
444 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
445 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
446 // there may be a direction override character in front of the string.
447 return max(pos - BIDI_OFFSET, 0);
449 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
450 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
451 * length. We work around the problem by trying all docstring
452 * positions until the right one is found. This is slow only if
453 * there are many high-plane Unicode characters. It might be
454 * worthwhile to implement a dichotomy search if this shows up
457 // there may be a direction override character in front of the string.
458 qpos = max(qpos - BIDI_OFFSET, 0);
459 int pos = min(qpos, static_cast<int>(s.length()));
460 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
462 LASSERT(pos > 0 || qpos == 0, /**/);
468 int GuiFontMetrics::countExpanders(docstring const & str) const
470 // Numbers of characters that are expanded by inter-word spacing. These
471 // characters are spaces, except for characters 09-0D which are treated
472 // specially. (From a combination of testing with the notepad found in qt's
473 // examples, and reading the source code.) In addition, consecutive spaces
474 // only count as one expander.
475 bool wasspace = false;
477 for (char_type c : str)
478 if (c > 0x0d && QChar(c).isSpace()) {
491 const int brkStrOffset = 1 + BIDI_OFFSET;
494 QString createBreakableString(docstring const & s, bool rtl, QTextLayout & tl)
496 /* Qt will not break at a leading or trailing space, and we need
497 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
499 * To work around the problem, we enclose the string between
500 * zero-width characters so that the QTextLayout algorithm will
501 * agree to break the text at these extremal spaces.
503 // Unicode character ZERO WIDTH NO-BREAK SPACE
504 QChar const zerow_nbsp(0xfeff);
505 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
507 /* Use undocumented flag to enforce drawing direction
508 * FIXME: This does not work with Qt 5.11 (ticket #11284).
510 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
513 #ifdef BIDI_USE_OVERRIDE
514 /* Use unicode override characters to enforce drawing direction
515 * Source: http://www.iamcal.com/understanding-bidirectional-text/
518 // Right-to-left override: forces to draw text right-to-left
519 qs = QChar(0x202E) + qs;
521 // Left-to-right override: forces to draw text left-to-right
522 qs = QChar(0x202D) + qs;
528 docstring::size_type brkstr2str_pos(QString brkstr, docstring const & str, int pos)
530 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
531 * not be the same when there are high-plan unicode characters
534 // The variable `brkStrOffset' is here to account for the extra leading characters.
535 // The ending character zerow_nbsp has to be ignored if the line is complete.
536 int const qlen = pos - brkStrOffset - (pos == brkstr.length());
537 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
538 auto const len = qstring_to_ucs4(brkstr.mid(brkStrOffset, qlen)).length();
542 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
543 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
544 * length. We work around the problem by trying all docstring
545 * positions until the right one is found. This is slow only if
546 * there are many high-plane Unicode characters. It might be
547 * worthwhile to implement a dichotomy search if this shows up
550 int len = min(qlen, static_cast<int>(str.length()));
551 while (len >= 0 && toqstr(str.substr(0, len)).length() != qlen)
553 LASSERT(len > 0 || qlen == 0, /**/);
561 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
562 bool rtl, bool force) const
565 QString qs = createBreakableString(s, rtl, tl);
570 * Some Asian languages split lines anywhere (no notion of
571 * word). It seems that QTextLayout is not aware of this fact.
573 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
575 * FIXME: Something shall be done about characters which are
576 * not allowed at the beginning or end of line.
578 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
579 : QTextOption::WordWrap);
580 // Let QTextLine::naturalTextWidth() account for trailing spaces
581 // (horizontalAdvance() still does not).
582 to.setFlags(QTextOption::IncludeTrailingSpaces);
583 tl.setTextOption(to);
588 QTextLine line = tl.createLine();
591 line.setLineWidth(first ? first_wid : wid);
599 for (int i = 0 ; i < tl.lineCount() ; ++i) {
600 QTextLine const & line = tl.lineAt(i);
601 int const epos = brkstr2str_pos(qs, s, line.textStart() + line.textLength());
602 #if QT_VERSION >= 0x050000
603 int const wid = i + 1 < tl.lineCount() ? iround(line.horizontalAdvance())
604 : iround(line.naturalTextWidth());
606 // With some monospace fonts, the value of horizontalAdvance()
607 // can be wrong with Qt4. One hypothesis is that the invisible
608 // characters that we use are given a non-null width.
609 // FIXME: this is slower than it could be but we'll get rid of Qt4 anyway
610 int const wid = i + 1 < tl.lineCount() ? width(rtrim(s.substr(pos, epos - pos)))
611 : width(s.substr(pos, epos - pos));
613 breaks.emplace_back(epos - pos, wid);
616 // FIXME: should it be kept in some form?
617 if ((force && line.textLength() == brkStrOffset) || line_wid > x)
618 return {-1, line_wid};
627 uint qHash(BreakStringKey const & key)
629 // assume widths are less than 10000. This fits in 32 bits.
630 uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
631 return std::qHash(key.s) ^ ::qHash(params);
635 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
636 bool rtl, bool force) const
638 PROFILE_THIS_BLOCK(breakString);
642 BreakStringKey key{s, first_wid, wid, rtl, force};
644 if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
647 PROFILE_CACHE_MISS(breakString);
648 brks = breakString_helper(s, first_wid, wid, rtl, force);
649 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
655 void GuiFontMetrics::rectText(docstring const & str,
656 int & w, int & ascent, int & descent) const
658 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
659 int const offset = 4;
661 w = width(str) + offset;
662 ascent = metrics_.ascent() + offset / 2;
663 descent = metrics_.descent() + offset / 2;
667 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
668 int & w, int & ascent, int & descent) const
670 rectText(str, w, ascent, descent);
675 Dimension const GuiFontMetrics::defaultDimension() const
677 return Dimension(0, maxAscent(), maxDescent());
681 Dimension const GuiFontMetrics::dimension(char_type c) const
683 return Dimension(width(c), ascent(c), descent(c));
687 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
692 r = metrics_.boundingRect(ucs4_to_qchar(c));
694 r = metrics_.boundingRect(toqstr(docstring(1, c)));
696 AscendDescend ad = { -r.top(), r.bottom() + 1};
697 // We could as well compute the width but this is not really
698 // needed for now as it is done directly in width() below.
699 metrics_cache_.insert(c, ad);
705 int GuiFontMetrics::width(char_type c) const
707 int value = width_cache_.value(c, outOfLimitMetric);
708 if (value != outOfLimitMetric)
711 #if QT_VERSION >= 0x050b00
713 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
715 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
718 value = metrics_.width(ucs4_to_qchar(c));
720 value = metrics_.width(toqstr(docstring(1, c)));
723 width_cache_.insert(c, value);
729 int GuiFontMetrics::ascent(char_type c) const
731 static AscendDescend const outOfLimitAD =
732 {outOfLimitMetric, outOfLimitMetric};
733 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
734 if (value.ascent != outOfLimitMetric)
737 value = fillMetricsCache(c);
742 int GuiFontMetrics::descent(char_type c) const
744 static AscendDescend const outOfLimitAD =
745 {outOfLimitMetric, outOfLimitMetric};
746 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
747 if (value.descent != outOfLimitMetric)
748 return value.descent;
750 value = fillMetricsCache(c);
751 return value.descent;
754 } // namespace frontend