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"
63 * Argument-dependent lookup implies that this function shall be
64 * declared in the namespace of its argument. But this is std
65 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
67 uint qHash(lyx::docstring const & s)
69 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
70 s.size() * sizeof(lyx::docstring::value_type)));
80 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
81 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
82 * size of the QTextLayout objects anyway).
83 * Note that all these numbers are arbitrary.
84 * Also, setting size to 0 is tantamount to disabling the cache.
86 int cache_metrics_width_size = 1 << 19;
87 int cache_metrics_breakat_size = 1 << 19;
88 // Qt 5.x already has its own caching of QTextLayout objects
89 // but it does not seem to work well on MacOS X.
90 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
91 int cache_metrics_qtextlayout_size = 500;
93 int cache_metrics_qtextlayout_size = 0;
99 * Convert a UCS4 character into a QChar.
100 * This is a hack (it does only make sense for the common part of the UCS4
101 * and UTF16 encodings) and should not be used.
102 * This does only exist because of performance reasons (a real conversion
103 * using iconv is too slow on windows).
105 * This is no real conversion but a simple cast in reality. This is the reason
106 * why this works well for symbol fonts used in mathed too, even though
107 * these are not real ucs4 characters. These are codepoints in the
108 * computer modern fonts used, nothing unicode related.
109 * See comment in GuiPainter::text() for more explanation.
111 inline QChar const ucs4_to_qchar(char_type const ucs4)
113 LATTEST(is_utf16(ucs4));
114 return QChar(static_cast<unsigned short>(ucs4));
119 GuiFontMetrics::GuiFontMetrics(QFont const & font)
120 : font_(font), metrics_(font, 0),
121 strwidth_cache_(cache_metrics_width_size),
122 breakat_cache_(cache_metrics_breakat_size),
123 qtextlayout_cache_(cache_metrics_qtextlayout_size)
125 // Determine italic slope
126 double const defaultSlope = tan(qDegreesToRadians(19.0));
127 QRawFont raw = QRawFont::fromFont(font);
128 QByteArray post(raw.fontTable("post"));
129 if (post.length() == 0) {
130 slope_ = defaultSlope;
131 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
133 // post table description:
134 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
135 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
136 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
137 slope_ = -tan(qDegreesToRadians(angle));
138 // Correct italic fonts with zero slope
139 if (slope_ == 0.0 && font.italic())
140 slope_ = defaultSlope;
141 LYXERR(Debug::FONT, "Italic slope: " << slope_);
146 int GuiFontMetrics::maxAscent() const
148 return metrics_.ascent();
152 int GuiFontMetrics::maxDescent() const
154 // We add 1 as the value returned by QT is different than X
155 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
156 return metrics_.descent() + 1;
160 int GuiFontMetrics::em() const
162 return QFontInfo(font_).pixelSize();
166 int GuiFontMetrics::xHeight() const
168 // LATTEST(metrics_.xHeight() == ascent('x'));
169 return metrics_.xHeight();
173 int GuiFontMetrics::lineWidth() const
175 return metrics_.lineWidth();
179 int GuiFontMetrics::underlinePos() const
181 return metrics_.underlinePos();
185 int GuiFontMetrics::strikeoutPos() const
187 return metrics_.strikeOutPos();
191 bool GuiFontMetrics::italic() const
193 return font_.italic();
197 double GuiFontMetrics::italicSlope() const
204 int const outOfLimitMetric = -10000;
208 int GuiFontMetrics::lbearing(char_type c) const
210 int value = lbearing_cache_.value(c, outOfLimitMetric);
211 if (value != outOfLimitMetric)
215 value = metrics_.leftBearing(ucs4_to_qchar(c));
217 // FIXME: QFontMetrics::leftBearing does not support the
218 // full unicode range. Once it does, we could use:
219 // metrics_.leftBearing(toqstr(docstring(1, c)));
223 lbearing_cache_.insert(c, value);
229 int GuiFontMetrics::rbearing(char_type c) const
231 int value = rbearing_cache_.value(c, outOfLimitMetric);
232 if (value != outOfLimitMetric)
235 // Qt rbearing is from the right edge of the char's width().
237 QChar sc = ucs4_to_qchar(c);
238 value = width(c) - metrics_.rightBearing(sc);
240 // FIXME: QFontMetrics::leftBearing does not support the
241 // full unicode range. Once it does, we could use:
242 // metrics_.rightBearing(toqstr(docstring(1, c)));
246 rbearing_cache_.insert(c, value);
252 int GuiFontMetrics::width(docstring const & s) const
254 PROFILE_THIS_BLOCK(width);
255 if (strwidth_cache_.contains(s))
256 return strwidth_cache_[s];
257 PROFILE_CACHE_MISS(width);
258 /* Several problems have to be taken into account:
259 * * QFontMetrics::width does not returns a wrong value with Qt5 with
260 * some arabic text, since the glyph-shaping operations are not
261 * done (documented in Qt5).
262 * * QTextLayout is broken for single characters with null width
263 * (like \not in mathed).
264 * * While QTextLine::horizontalAdvance is the right thing to use
265 * for text strings, it does not give a good result with some
266 * characters like the \int (gyph 4) of esint.
268 * The metrics of some of our math fonts (eg. esint) are such that
269 * QTextLine::horizontalAdvance leads, more or less, in the middle
270 * of a symbol. This is the horizontal position where a subscript
271 * should be drawn, so that the superscript has to be moved rightward.
272 * This is done when the kerning() method of the math insets returns
273 * a positive value. The problem with this choice is that navigating
274 * a formula becomes weird. For example, a selection extends only over
275 * about half of the symbol. In order to avoid this, with our math
276 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
277 * be drawn right after the symbol, and move the subscript leftward by
278 * recording a negative value for the kerning.
281 // is the string a single character from a math font ?
282 #if QT_VERSION >= 0x040800
283 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
285 bool const math_char = s.length() == 1;
288 QString const qs = toqstr(s);
289 int br_width = metrics_.boundingRect(qs).width();
290 #if QT_VERSION >= 0x050b00
291 int s_width = metrics_.horizontalAdvance(qs);
293 int s_width = metrics_.width(qs);
295 // keep value 0 for math chars with width 0
297 w = max(br_width, s_width);
300 tl.setText(toqstr(s));
303 QTextLine line = tl.createLine();
305 w = iround(line.horizontalAdvance());
307 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
312 int GuiFontMetrics::width(QString const & ucs2) const
314 return width(qstring_to_ucs4(ucs2));
318 int GuiFontMetrics::signedWidth(docstring const & s) const
324 return -width(s.substr(1, s.size() - 1));
330 shared_ptr<QTextLayout const>
331 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
332 double const wordspacing) const
334 PROFILE_THIS_BLOCK(getTextLayout);
335 docstring const s_cache =
336 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
337 if (auto ptl = qtextlayout_cache_[s_cache])
339 PROFILE_CACHE_MISS(getTextLayout);
340 auto const ptl = make_shared<QTextLayout>();
341 ptl->setCacheEnabled(true);
343 copy.setWordSpacing(wordspacing);
347 /* Use undocumented flag to enforce drawing direction
348 * FIXME: This does not work with Qt 5.11 (ticket #11284).
350 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
353 #ifdef BIDI_USE_OVERRIDE
354 /* Use unicode override characters to enforce drawing direction
355 * Source: http://www.iamcal.com/understanding-bidirectional-text/
358 // Right-to-left override: forces to draw text right-to-left
359 ptl->setText(QChar(0x202E) + toqstr(s));
361 // Left-to-right override: forces to draw text left-to-right
362 ptl->setText(QChar(0x202D) + toqstr(s));
364 ptl->setText(toqstr(s));
370 qtextlayout_cache_.insert(s_cache, ptl);
375 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
376 double const wordspacing) const
380 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
381 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
382 * not be the same when there are high-plan unicode characters
385 // BIDI_OFFSET accounts for a possible direction override
386 // character in front of the string.
387 int const qpos = toqstr(s.substr(0, pos)).length() + BIDI_OFFSET;
388 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
392 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
393 double const wordspacing) const
395 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
396 QTextLine const & tline = tl->lineForTextPosition(0);
397 int qpos = tline.xToCursor(x);
398 int newx = static_cast<int>(tline.cursorToX(qpos));
399 // The value of qpos may be wrong in rtl text (see ticket #10569).
400 // To work around this, let's have a look at adjacent positions to
401 // see whether we find closer matches.
402 if (rtl && newx < x) {
404 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
405 if (abs(xm - x) < abs(newx - x)) {
411 } else if (rtl && newx > x) {
412 while (qpos < tline.textLength()) {
413 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
414 if (abs(xp - x) < abs(newx - x)) {
421 // correct x value to the actual cursor position.
424 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
425 * not be the same when there are high-plan unicode characters
428 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
429 int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
430 // there may be a direction override character in front of the string.
431 return max(pos - BIDI_OFFSET, 0);
433 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
434 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
435 * length. We work around the problem by trying all docstring
436 * positions until the right one is found. This is slow only if
437 * there are many high-plane Unicode characters. It might be
438 * worthwhile to implement a dichotomy search if this shows up
441 // there may be a direction override character in front of the string.
442 qpos = max(qpos - BIDI_OFFSET, 0);
443 int pos = min(qpos, static_cast<int>(s.length()));
444 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
446 LASSERT(pos > 0 || qpos == 0, /**/);
452 int GuiFontMetrics::countExpanders(docstring const & str) const
454 // Numbers of characters that are expanded by inter-word spacing. These
455 // characters are spaces, except for characters 09-0D which are treated
456 // specially. (From a combination of testing with the notepad found in qt's
457 // examples, and reading the source code.) In addition, consecutive spaces
458 // only count as one expander.
459 bool wasspace = false;
461 for (char_type c : str)
462 if (c > 0x0d && QChar(c).isSpace()) {
474 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
475 bool const rtl, bool const force) const
478 /* Qt will not break at a leading or trailing space, and we need
479 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
481 * To work around the problem, we enclose the string between
482 * zero-width characters so that the QTextLayout algorithm will
483 * agree to break the text at these extremal spaces.
485 // Unicode character ZERO WIDTH NO-BREAK SPACE
486 QChar const zerow_nbsp(0xfeff);
487 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
489 /* Use undocumented flag to enforce drawing direction
490 * FIXME: This does not work with Qt 5.11 (ticket #11284).
492 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
495 #ifdef BIDI_USE_OVERRIDE
496 /* Use unicode override characters to enforce drawing direction
497 * Source: http://www.iamcal.com/understanding-bidirectional-text/
500 // Right-to-left override: forces to draw text right-to-left
501 qs = QChar(0x202E) + qs;
503 // Left-to-right override: forces to draw text left-to-right
504 qs = QChar(0x202D) + qs;
506 int const offset = 1 + BIDI_OFFSET;
511 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
512 : QTextOption::WordWrap);
513 tl.setTextOption(to);
515 QTextLine line = tl.createLine();
516 line.setLineWidth(x);
519 int const line_wid = iround(line.horizontalAdvance());
520 if ((force && line.textLength() == offset) || line_wid > x)
522 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
523 * not be the same when there are high-plan unicode characters
526 // The variable `offset' is here to account for the extra leading characters.
527 // The ending character zerow_nbsp has to be ignored if the line is complete.
528 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
529 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
530 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
532 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
533 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
534 * length. We work around the problem by trying all docstring
535 * positions until the right one is found. This is slow only if
536 * there are many high-plane Unicode characters. It might be
537 * worthwhile to implement a dichotomy search if this shows up
540 int len = min(qlen, static_cast<int>(s.length()));
541 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
543 LASSERT(len > 0 || qlen == 0, /**/);
545 return {len, line_wid};
549 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
551 PROFILE_THIS_BLOCK(breakAt);
555 docstring const s_cache =
556 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
559 if (breakat_cache_.contains(s_cache))
560 pp = breakat_cache_[s_cache];
562 PROFILE_CACHE_MISS(breakAt);
563 pp = breakAt_helper(s, x, rtl, force);
564 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
568 s = s.substr(0, pp.first);
574 void GuiFontMetrics::rectText(docstring const & str,
575 int & w, int & ascent, int & descent) const
577 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
578 int const offset = 4;
580 w = width(str) + offset;
581 ascent = metrics_.ascent() + offset / 2;
582 descent = metrics_.descent() + offset / 2;
586 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
587 int & w, int & ascent, int & descent) const
589 rectText(str, w, ascent, descent);
594 Dimension const GuiFontMetrics::defaultDimension() const
596 return Dimension(0, maxAscent(), maxDescent());
600 Dimension const GuiFontMetrics::dimension(char_type c) const
602 return Dimension(width(c), ascent(c), descent(c));
606 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
611 r = metrics_.boundingRect(ucs4_to_qchar(c));
613 r = metrics_.boundingRect(toqstr(docstring(1, c)));
615 AscendDescend ad = { -r.top(), r.bottom() + 1};
616 // We could as well compute the width but this is not really
617 // needed for now as it is done directly in width() below.
618 metrics_cache_.insert(c, ad);
624 int GuiFontMetrics::width(char_type c) const
626 int value = width_cache_.value(c, outOfLimitMetric);
627 if (value != outOfLimitMetric)
631 value = metrics_.width(ucs4_to_qchar(c));
633 value = metrics_.width(toqstr(docstring(1, c)));
635 width_cache_.insert(c, value);
641 int GuiFontMetrics::ascent(char_type c) const
643 static AscendDescend const outOfLimitAD =
644 {outOfLimitMetric, outOfLimitMetric};
645 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
646 if (value.ascent != outOfLimitMetric)
649 value = fillMetricsCache(c);
654 int GuiFontMetrics::descent(char_type c) const
656 static AscendDescend const outOfLimitAD =
657 {outOfLimitMetric, outOfLimitMetric};
658 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
659 if (value.descent != outOfLimitMetric)
660 return value.descent;
662 value = fillMetricsCache(c);
663 return value.descent;
666 } // namespace frontend