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/debug.h"
22 #include "support/lassert.h"
23 #include "support/lstrings.h" // for breakString_helper with qt4
24 #include "support/lyxlib.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 breakstr_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 = 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, /**/);
472 const int brkStrOffset = 1 + BIDI_OFFSET;
475 QString createBreakableString(docstring const & s, bool rtl, QTextLayout & tl)
477 /* Qt will not break at a leading or trailing space, and we need
478 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
480 * To work around the problem, we enclose the string between
481 * zero-width characters so that the QTextLayout algorithm will
482 * agree to break the text at these extremal spaces.
484 // Unicode character ZERO WIDTH NO-BREAK SPACE
485 QChar const zerow_nbsp(0xfeff);
486 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
488 /* Use undocumented flag to enforce drawing direction
489 * FIXME: This does not work with Qt 5.11 (ticket #11284).
491 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
494 #ifdef BIDI_USE_OVERRIDE
495 /* Use unicode override characters to enforce drawing direction
496 * Source: http://www.iamcal.com/understanding-bidirectional-text/
499 // Right-to-left override: forces to draw text right-to-left
500 qs = QChar(0x202E) + qs;
502 // Left-to-right override: forces to draw text left-to-right
503 qs = QChar(0x202D) + qs;
509 docstring::size_type brkstr2str_pos(QString brkstr, docstring const & str, int pos)
511 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
512 * not be the same when there are high-plan unicode characters
515 // The variable `brkStrOffset' is here to account for the extra leading characters.
516 // The ending character zerow_nbsp has to be ignored if the line is complete.
517 int const qlen = max(pos - brkStrOffset - (pos == brkstr.length()), 0);
518 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
519 auto const len = qstring_to_ucs4(brkstr.mid(brkStrOffset, qlen)).length();
523 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
524 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
525 * length. We work around the problem by trying all docstring
526 * positions until the right one is found. This is slow only if
527 * there are many high-plane Unicode characters. It might be
528 * worthwhile to implement a dichotomy search if this shows up
531 int len = min(qlen, static_cast<int>(str.length()));
532 while (len >= 0 && toqstr(str.substr(0, len)).length() != qlen)
534 LASSERT(len > 0 || qlen == 0, /**/);
542 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
543 bool rtl, bool force) const
546 QString qs = createBreakableString(s, rtl, tl);
551 * Some Asian languages split lines anywhere (no notion of
552 * word). It seems that QTextLayout is not aware of this fact.
554 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
556 * FIXME: Something shall be done about characters which are
557 * not allowed at the beginning or end of line.
559 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
560 : QTextOption::WordWrap);
561 tl.setTextOption(to);
566 QTextLine line = tl.createLine();
569 line.setLineWidth(first ? first_wid : wid);
576 for (int i = 0 ; i < tl.lineCount() ; ++i) {
577 QTextLine const & line = tl.lineAt(i);
578 int const line_epos = line.textStart() + line.textLength();
579 int const epos = brkstr2str_pos(qs, s, line_epos);
580 #if QT_VERSION >= 0x050000
581 // This does not take trailing spaces into account, except for the last line.
582 int const wid = iround(line.naturalTextWidth());
583 // If the line is not the last one, trailing space is always omitted.
585 // For the last line, compute the width without trailing space
586 if (i + 1 == tl.lineCount()) {
587 // trim_pos points to the last character that is not a space
588 auto trim_pos = s.find_last_not_of(from_ascii(" "));
589 if (trim_pos == docstring::npos)
591 else if (trim_pos + 1 < s.length()) {
592 int const num_spaces = s.length() - trim_pos - 1;
593 // find the position on the line before trailing
594 // spaces. Remove 1 to account for the ending
595 // non-breaking space of qs.
596 nspc_wid = iround(line.cursorToX(line_epos - num_spaces - 1));
600 // With some monospace fonts, the value of horizontalAdvance()
601 // can be wrong with Qt4. One hypothesis is that the invisible
602 // characters that we use are given a non-null width.
603 // FIXME: this is slower than it could be but we'll get rid of Qt4 anyway
604 docstring const ss = s.substr(pos, epos - pos);
605 int const wid = width(ss);
606 int const nspc_wid = i + 1 < tl.lineCount() ? width(rtrim(ss)) : wid;
608 breaks.emplace_back(epos - pos, wid, nspc_wid);
611 // FIXME: should it be kept in some form?
612 if ((force && line.textLength() == brkStrOffset) || line_wid > x)
613 return {-1, line_wid};
621 uint qHash(BreakStringKey const & key)
623 // assume widths are less than 10000. This fits in 32 bits.
624 uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
625 return std::qHash(key.s) ^ ::qHash(params);
629 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
630 bool rtl, bool force) const
632 PROFILE_THIS_BLOCK(breakString);
636 BreakStringKey key{s, first_wid, wid, rtl, force};
638 if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
641 PROFILE_CACHE_MISS(breakString);
642 brks = breakString_helper(s, first_wid, wid, rtl, force);
643 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
649 void GuiFontMetrics::rectText(docstring const & str,
650 int & w, int & ascent, int & descent) const
652 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
653 int const offset = 4;
655 w = width(str) + offset;
656 ascent = metrics_.ascent() + offset / 2;
657 descent = metrics_.descent() + offset / 2;
661 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
662 int & w, int & ascent, int & descent) const
664 rectText(str, w, ascent, descent);
669 Dimension const GuiFontMetrics::defaultDimension() const
671 return Dimension(0, maxAscent(), maxDescent());
675 Dimension const GuiFontMetrics::dimension(char_type c) const
677 return Dimension(width(c), ascent(c), descent(c));
681 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
686 r = metrics_.boundingRect(ucs4_to_qchar(c));
688 r = metrics_.boundingRect(toqstr(docstring(1, c)));
690 AscendDescend ad = { -r.top(), r.bottom() + 1};
691 // We could as well compute the width but this is not really
692 // needed for now as it is done directly in width() below.
693 metrics_cache_.insert(c, ad);
699 int GuiFontMetrics::width(char_type c) const
701 int value = width_cache_.value(c, outOfLimitMetric);
702 if (value != outOfLimitMetric)
705 #if QT_VERSION >= 0x050b00
707 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
709 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
712 value = metrics_.width(ucs4_to_qchar(c));
714 value = metrics_.width(toqstr(docstring(1, c)));
717 width_cache_.insert(c, value);
723 int GuiFontMetrics::ascent(char_type c) const
725 static AscendDescend const outOfLimitAD =
726 {outOfLimitMetric, outOfLimitMetric};
727 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
728 if (value.ascent != outOfLimitMetric)
731 value = fillMetricsCache(c);
736 int GuiFontMetrics::descent(char_type c) const
738 static AscendDescend const outOfLimitAD =
739 {outOfLimitMetric, outOfLimitMetric};
740 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
741 if (value.descent != outOfLimitMetric)
742 return value.descent;
744 value = fillMetricsCache(c);
745 return value.descent;
748 } // namespace frontend