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 // Maximal size/cost for various caches. See QCache documentation to
91 // see what cost means.
93 // Limit strwidth_cache_ total cost to 1MB of string data.
94 int const strwidth_cache_max_cost = 1024 * 1024;
95 // Limit breakat_cache_ total cost to 10MB of string data.
96 // This is useful for documents with very large insets.
97 int const breakstr_cache_max_cost = 10 * 1024 * 1024;
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 // Limit qtextlayout_cache_ size to 500 elements (we do not know the
102 // size of the QTextLayout objects anyway).
103 int const qtextlayout_cache_max_size = 500;
106 int const qtextlayout_cache_max_size = 0;
111 * Convert a UCS4 character into a QChar.
112 * This is a hack (it does only make sense for the common part of the UCS4
113 * and UTF16 encodings) and should not be used.
114 * This does only exist because of performance reasons (a real conversion
115 * using iconv is too slow on windows).
117 * This is no real conversion but a simple cast in reality. This is the reason
118 * why this works well for symbol fonts used in mathed too, even though
119 * these are not real ucs4 characters. These are codepoints in the
120 * computer modern fonts used, nothing unicode related.
121 * See comment in GuiPainter::text() for more explanation.
123 inline QChar const ucs4_to_qchar(char_type const ucs4)
125 LATTEST(is_utf16(ucs4));
126 return QChar(static_cast<unsigned short>(ucs4));
131 GuiFontMetrics::GuiFontMetrics(QFont const & font)
132 : font_(font), metrics_(font, 0),
133 strwidth_cache_(strwidth_cache_max_cost),
134 breakstr_cache_(breakstr_cache_max_cost),
135 qtextlayout_cache_(qtextlayout_cache_max_size)
137 // Determine italic slope
138 double const defaultSlope = tan(qDegreesToRadians(19.0));
139 QRawFont raw = QRawFont::fromFont(font);
140 QByteArray post(raw.fontTable("post"));
141 if (post.length() == 0) {
142 slope_ = defaultSlope;
143 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
145 // post table description:
146 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
147 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
148 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
149 slope_ = -tan(qDegreesToRadians(angle));
150 // Correct italic fonts with zero slope
151 if (slope_ == 0.0 && font.italic())
152 slope_ = defaultSlope;
153 LYXERR(Debug::FONT, "Italic slope: " << slope_);
158 int GuiFontMetrics::maxAscent() const
160 return metrics_.ascent();
164 int GuiFontMetrics::maxDescent() const
166 // We add 1 as the value returned by QT is different than X
167 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
169 return metrics_.descent() + 1;
173 int GuiFontMetrics::em() const
175 return QFontInfo(font_).pixelSize();
179 int GuiFontMetrics::xHeight() const
181 // LATTEST(metrics_.xHeight() == ascent('x'));
182 return metrics_.xHeight();
186 int GuiFontMetrics::lineWidth() const
188 return metrics_.lineWidth();
192 int GuiFontMetrics::underlinePos() const
194 return metrics_.underlinePos();
198 int GuiFontMetrics::strikeoutPos() const
200 return metrics_.strikeOutPos();
204 bool GuiFontMetrics::italic() const
206 return font_.italic();
210 double GuiFontMetrics::italicSlope() const
217 int const outOfLimitMetric = -10000;
221 int GuiFontMetrics::lbearing(char_type c) const
223 int value = lbearing_cache_.value(c, outOfLimitMetric);
224 if (value != outOfLimitMetric)
228 value = metrics_.leftBearing(ucs4_to_qchar(c));
230 // FIXME: QFontMetrics::leftBearing does not support the
231 // full unicode range. Once it does, we could use:
232 // metrics_.leftBearing(toqstr(docstring(1, c)));
236 lbearing_cache_.insert(c, value);
242 int GuiFontMetrics::rbearing(char_type c) const
244 int value = rbearing_cache_.value(c, outOfLimitMetric);
245 if (value != outOfLimitMetric)
248 // Qt rbearing is from the right edge of the char's width().
250 QChar sc = ucs4_to_qchar(c);
251 value = width(c) - metrics_.rightBearing(sc);
253 // FIXME: QFontMetrics::leftBearing does not support the
254 // full unicode range. Once it does, we could use:
255 // metrics_.rightBearing(toqstr(docstring(1, c)));
259 rbearing_cache_.insert(c, value);
265 int GuiFontMetrics::width(docstring const & s) const
267 PROFILE_THIS_BLOCK(width);
268 if (int * wid_p = strwidth_cache_.object_ptr(s))
270 PROFILE_CACHE_MISS(width);
271 /* Several problems have to be taken into account:
272 * * QFontMetrics::width does not returns a wrong value with Qt5 with
273 * some arabic text, since the glyph-shaping operations are not
274 * done (documented in Qt5).
275 * * QTextLayout is broken for single characters with null width
276 * (like \not in mathed).
277 * * While QTextLine::horizontalAdvance is the right thing to use
278 * for text strings, it does not give a good result with some
279 * characters like the \int (gyph 4) of esint.
281 * The metrics of some of our math fonts (eg. esint) are such that
282 * QTextLine::horizontalAdvance leads, more or less, in the middle
283 * of a symbol. This is the horizontal position where a subscript
284 * should be drawn, so that the superscript has to be moved rightward.
285 * This is done when the kerning() method of the math insets returns
286 * a positive value. The problem with this choice is that navigating
287 * a formula becomes weird. For example, a selection extends only over
288 * about half of the symbol. In order to avoid this, with our math
289 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
290 * be drawn right after the symbol, and move the subscript leftward by
291 * recording a negative value for the kerning.
294 // is the string a single character from a math font ?
295 #if QT_VERSION >= 0x040800
296 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
298 bool const math_char = s.length() == 1;
301 QString const qs = toqstr(s);
302 int br_width = metrics_.boundingRect(qs).width();
303 #if QT_VERSION >= 0x050b00
304 int s_width = metrics_.horizontalAdvance(qs);
306 int s_width = metrics_.width(qs);
308 // keep value 0 for math chars with width 0
310 w = max(br_width, s_width);
313 tl.setText(toqstr(s));
316 QTextLine line = tl.createLine();
318 w = iround(line.horizontalAdvance());
320 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
325 int GuiFontMetrics::width(QString const & ucs2) const
327 return width(qstring_to_ucs4(ucs2));
331 int GuiFontMetrics::signedWidth(docstring const & s) const
337 return -width(s.substr(1, s.size() - 1));
343 uint qHash(TextLayoutKey const & key)
345 double params = (2 * key.rtl - 1) * key.ws;
346 return std::qHash(key.s) ^ ::qHash(params);
349 shared_ptr<QTextLayout const>
350 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
351 double const wordspacing) const
353 PROFILE_THIS_BLOCK(getTextLayout);
354 TextLayoutKey key{s, rtl, wordspacing};
355 if (auto ptl = qtextlayout_cache_[key])
357 PROFILE_CACHE_MISS(getTextLayout);
358 auto const ptl = make_shared<QTextLayout>();
359 ptl->setCacheEnabled(true);
361 copy.setWordSpacing(wordspacing);
365 /* Use undocumented flag to enforce drawing direction
366 * FIXME: This does not work with Qt 5.11 (ticket #11284).
368 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
371 #ifdef BIDI_USE_OVERRIDE
372 /* Use unicode override characters to enforce drawing direction
373 * Source: http://www.iamcal.com/understanding-bidirectional-text/
376 // Right-to-left override: forces to draw text right-to-left
377 ptl->setText(QChar(0x202E) + toqstr(s));
379 // Left-to-right override: forces to draw text left-to-right
380 ptl->setText(QChar(0x202D) + toqstr(s));
382 ptl->setText(toqstr(s));
388 qtextlayout_cache_.insert(key, ptl);
393 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
394 double const wordspacing) const
398 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
399 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
400 * not be the same when there are high-plan unicode characters
403 // BIDI_OFFSET accounts for a possible direction override
404 // character in front of the string.
405 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
406 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
410 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
411 double const wordspacing) const
413 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
414 QTextLine const & tline = tl->lineForTextPosition(0);
415 int qpos = tline.xToCursor(x);
416 int newx = static_cast<int>(tline.cursorToX(qpos));
417 // The value of qpos may be wrong in rtl text (see ticket #10569).
418 // To work around this, let's have a look at adjacent positions to
419 // see whether we find closer matches.
420 if (rtl && newx < x) {
422 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
423 if (abs(xm - x) < abs(newx - x)) {
429 } else if (rtl && newx > x) {
430 while (qpos < tline.textLength()) {
431 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
432 if (abs(xp - x) < abs(newx - x)) {
439 // correct x value to the actual cursor position.
442 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
443 * not be the same when there are high-plan unicode characters
446 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
447 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
448 // there may be a direction override character in front of the string.
449 return max(pos - BIDI_OFFSET, 0);
451 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
452 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
453 * length. We work around the problem by trying all docstring
454 * positions until the right one is found. This is slow only if
455 * there are many high-plane Unicode characters. It might be
456 * worthwhile to implement a dichotomy search if this shows up
459 // there may be a direction override character in front of the string.
460 qpos = max(qpos - BIDI_OFFSET, 0);
461 int pos = min(qpos, static_cast<int>(s.length()));
462 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
464 LASSERT(pos > 0 || qpos == 0, /**/);
470 int GuiFontMetrics::countExpanders(docstring const & str) const
472 // Numbers of characters that are expanded by inter-word spacing. These
473 // characters are spaces, except for characters 09-0D which are treated
474 // specially. (From a combination of testing with the notepad found in qt's
475 // examples, and reading the source code.) In addition, consecutive spaces
476 // only count as one expander.
477 bool wasspace = false;
479 for (char_type c : str)
480 if (c > 0x0d && QChar(c).isSpace()) {
493 const int brkStrOffset = 1 + BIDI_OFFSET;
496 QString createBreakableString(docstring const & s, bool rtl, QTextLayout & tl)
498 /* Qt will not break at a leading or trailing space, and we need
499 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
501 * To work around the problem, we enclose the string between
502 * zero-width characters so that the QTextLayout algorithm will
503 * agree to break the text at these extremal spaces.
505 // Unicode character ZERO WIDTH NO-BREAK SPACE
506 QChar const zerow_nbsp(0xfeff);
507 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
509 /* Use undocumented flag to enforce drawing direction
510 * FIXME: This does not work with Qt 5.11 (ticket #11284).
512 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
515 #ifdef BIDI_USE_OVERRIDE
516 /* Use unicode override characters to enforce drawing direction
517 * Source: http://www.iamcal.com/understanding-bidirectional-text/
520 // Right-to-left override: forces to draw text right-to-left
521 qs = QChar(0x202E) + qs;
523 // Left-to-right override: forces to draw text left-to-right
524 qs = QChar(0x202D) + qs;
530 docstring::size_type brkstr2str_pos(QString brkstr, docstring const & str, int pos)
532 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
533 * not be the same when there are high-plan unicode characters
536 // The variable `brkStrOffset' is here to account for the extra leading characters.
537 // The ending character zerow_nbsp has to be ignored if the line is complete.
538 int const qlen = pos - brkStrOffset - (pos == brkstr.length());
539 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
540 auto const len = qstring_to_ucs4(brkstr.mid(brkStrOffset, qlen)).length();
544 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
545 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
546 * length. We work around the problem by trying all docstring
547 * positions until the right one is found. This is slow only if
548 * there are many high-plane Unicode characters. It might be
549 * worthwhile to implement a dichotomy search if this shows up
552 int len = min(qlen, static_cast<int>(str.length()));
553 while (len >= 0 && toqstr(str.substr(0, len)).length() != qlen)
555 LASSERT(len > 0 || qlen == 0, /**/);
563 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
564 bool rtl, bool force) const
567 QString qs = createBreakableString(s, rtl, tl);
572 * Some Asian languages split lines anywhere (no notion of
573 * word). It seems that QTextLayout is not aware of this fact.
575 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
577 * FIXME: Something shall be done about characters which are
578 * not allowed at the beginning or end of line.
580 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
581 : QTextOption::WordWrap);
582 // Let QTextLine::naturalTextWidth() account for trailing spaces
583 // (horizontalAdvance() still does not).
584 to.setFlags(QTextOption::IncludeTrailingSpaces);
585 tl.setTextOption(to);
590 QTextLine line = tl.createLine();
593 line.setLineWidth(first ? first_wid : wid);
601 for (int i = 0 ; i < tl.lineCount() ; ++i) {
602 QTextLine const & line = tl.lineAt(i);
603 int const epos = brkstr2str_pos(qs, s, line.textStart() + line.textLength());
604 #if QT_VERSION >= 0x050000
605 int const wid = i + 1 < tl.lineCount() ? iround(line.horizontalAdvance())
606 : iround(line.naturalTextWidth());
608 // With some monospace fonts, the value of horizontalAdvance()
609 // can be wrong with Qt4. One hypothesis is that the invisible
610 // characters that we use are given a non-null width.
611 // FIXME: this is slower than it could be but we'll get rid of Qt4 anyway
612 int const wid = i + 1 < tl.lineCount() ? width(rtrim(s.substr(pos, epos - pos)))
613 : width(s.substr(pos, epos - pos));
615 breaks.emplace_back(epos - pos, wid);
618 // FIXME: should it be kept in some form?
619 if ((force && line.textLength() == brkStrOffset) || line_wid > x)
620 return {-1, line_wid};
629 uint qHash(BreakStringKey const & key)
631 // assume widths are less than 10000. This fits in 32 bits.
632 uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
633 return std::qHash(key.s) ^ ::qHash(params);
637 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
638 bool rtl, bool force) const
640 PROFILE_THIS_BLOCK(breakString);
644 BreakStringKey key{s, first_wid, wid, rtl, force};
646 if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
649 PROFILE_CACHE_MISS(breakString);
650 brks = breakString_helper(s, first_wid, wid, rtl, force);
651 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
657 void GuiFontMetrics::rectText(docstring const & str,
658 int & w, int & ascent, int & descent) const
660 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
661 int const offset = 4;
663 w = width(str) + offset;
664 ascent = metrics_.ascent() + offset / 2;
665 descent = metrics_.descent() + offset / 2;
669 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
670 int & w, int & ascent, int & descent) const
672 rectText(str, w, ascent, descent);
677 Dimension const GuiFontMetrics::defaultDimension() const
679 return Dimension(0, maxAscent(), maxDescent());
683 Dimension const GuiFontMetrics::dimension(char_type c) const
685 return Dimension(width(c), ascent(c), descent(c));
689 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
694 r = metrics_.boundingRect(ucs4_to_qchar(c));
696 r = metrics_.boundingRect(toqstr(docstring(1, c)));
698 AscendDescend ad = { -r.top(), r.bottom() + 1};
699 // We could as well compute the width but this is not really
700 // needed for now as it is done directly in width() below.
701 metrics_cache_.insert(c, ad);
707 int GuiFontMetrics::width(char_type c) const
709 int value = width_cache_.value(c, outOfLimitMetric);
710 if (value != outOfLimitMetric)
713 #if QT_VERSION >= 0x050b00
715 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
717 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
720 value = metrics_.width(ucs4_to_qchar(c));
722 value = metrics_.width(toqstr(docstring(1, c)));
725 width_cache_.insert(c, value);
731 int GuiFontMetrics::ascent(char_type c) const
733 static AscendDescend const outOfLimitAD =
734 {outOfLimitMetric, outOfLimitMetric};
735 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
736 if (value.ascent != outOfLimitMetric)
739 value = fillMetricsCache(c);
744 int GuiFontMetrics::descent(char_type c) const
746 static AscendDescend const outOfLimitAD =
747 {outOfLimitMetric, outOfLimitMetric};
748 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
749 if (value.descent != outOfLimitMetric)
750 return value.descent;
752 value = fillMetricsCache(c);
753 return value.descent;
756 } // namespace frontend