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/lyxlib.h"
24 #include "support/textutils.h"
26 #define DISABLE_PMPROF
27 #include "support/pmprof.h"
36 using namespace lyx::support;
38 /* Define what mechanisms are used to enforce text direction. There
39 * are two methods that work with different Qt versions. Here we try
40 * to use both methods together.
42 // Define to use unicode override characters to force direction
43 #define BIDI_USE_OVERRIDE
44 // Define to use QTextLayout flag to force direction
47 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
48 # error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
55 * Argument-dependent lookup implies that this function shall be
56 * declared in the namespace of its argument. But this is std
57 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
59 uint qHash(lyx::docstring const & s)
61 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
62 s.size() * sizeof(lyx::docstring::value_type)));
72 // Maximal size/cost for various caches. See QCache documentation to
73 // see what cost means.
75 // Limit strwidth_cache_ total cost to 1MB of string data.
76 int const strwidth_cache_max_cost = 1024 * 1024;
77 // Limit breakstr_cache_ total cost to 10MB of string data.
78 // This is useful for documents with very large insets.
79 int const breakstr_cache_max_cost = 10 * 1024 * 1024;
80 // Qt 5.x already has its own caching of QTextLayout objects
81 // but it does not seem to work well on MacOS X.
83 // For some reason, the built-in cache of QTextLayout does not work or
85 // Limit qtextlayout_cache_ size to 500 elements (we do not know the
86 // size of the QTextLayout objects anyway).
87 int const qtextlayout_cache_max_size = 500;
90 int const qtextlayout_cache_max_size = 0;
95 * Convert a UCS4 character into a QChar.
96 * This is a hack (it does only make sense for the common part of the UCS4
97 * and UTF16 encodings) and should not be used.
98 * This does only exist because of performance reasons (a real conversion
99 * using iconv is too slow on windows).
101 * This is no real conversion but a simple cast in reality. This is the reason
102 * why this works well for symbol fonts used in mathed too, even though
103 * these are not real ucs4 characters. These are codepoints in the
104 * computer modern fonts used, nothing unicode related.
105 * See comment in GuiPainter::text() for more explanation.
107 inline QChar const ucs4_to_qchar(char_type const ucs4)
109 LATTEST(is_utf16(ucs4));
110 return QChar(static_cast<unsigned short>(ucs4));
115 GuiFontMetrics::GuiFontMetrics(QFont const & font)
116 : font_(font), metrics_(font, 0), xheight_(metrics_.xHeight()),
117 strwidth_cache_(strwidth_cache_max_cost),
118 breakstr_cache_(breakstr_cache_max_cost),
119 qtextlayout_cache_(qtextlayout_cache_max_size)
121 // Determine italic slope
122 double const defaultSlope = tan(qDegreesToRadians(19.0));
123 QRawFont raw = QRawFont::fromFont(font);
124 QByteArray post(raw.fontTable("post"));
125 if (post.length() == 0) {
126 slope_ = defaultSlope;
127 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
129 // post table description:
130 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
131 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
132 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
133 slope_ = -tan(qDegreesToRadians(angle));
134 // Correct italic fonts with zero slope
135 if (slope_ == 0.0 && font.italic())
136 slope_ = defaultSlope;
137 LYXERR(Debug::FONT, "Italic slope: " << slope_);
142 int GuiFontMetrics::maxAscent() const
144 return metrics_.ascent();
148 int GuiFontMetrics::maxDescent() const
150 // We add 1 as the value returned by QT is different than X
151 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
153 return metrics_.descent() + 1;
157 int GuiFontMetrics::em() const
159 return QFontInfo(font_).pixelSize();
163 int GuiFontMetrics::xHeight() const
165 // LATTEST(metrics_.xHeight() == ascent('x'));
170 int GuiFontMetrics::lineWidth() const
172 return metrics_.lineWidth();
176 int GuiFontMetrics::underlinePos() const
178 return metrics_.underlinePos();
182 int GuiFontMetrics::strikeoutPos() const
184 return metrics_.strikeOutPos();
188 bool GuiFontMetrics::italic() const
190 return font_.italic();
194 double GuiFontMetrics::italicSlope() const
201 int const outOfLimitMetric = -10000;
205 int GuiFontMetrics::lbearing(char_type c) const
207 int value = lbearing_cache_.value(c, outOfLimitMetric);
208 if (value != outOfLimitMetric)
212 value = metrics_.leftBearing(ucs4_to_qchar(c));
214 // FIXME: QFontMetrics::leftBearing does not support the
215 // full unicode range. Once it does, we could use:
216 // metrics_.leftBearing(toqstr(docstring(1, c)));
220 lbearing_cache_.insert(c, value);
226 int GuiFontMetrics::rbearing(char_type c) const
228 int value = rbearing_cache_.value(c, outOfLimitMetric);
229 if (value != outOfLimitMetric)
232 // Qt rbearing is from the right edge of the char's width().
234 QChar sc = ucs4_to_qchar(c);
235 value = width(c) - metrics_.rightBearing(sc);
237 // FIXME: QFontMetrics::leftBearing does not support the
238 // full unicode range. Once it does, we could use:
239 // metrics_.rightBearing(toqstr(docstring(1, c)));
243 rbearing_cache_.insert(c, value);
249 int GuiFontMetrics::width(docstring const & s) const
251 PROFILE_THIS_BLOCK(width);
252 if (int * wid_p = strwidth_cache_.object_ptr(s))
254 PROFILE_CACHE_MISS(width);
255 /* Several problems have to be taken into account:
256 * * QFontMetrics::width returns a wrong value with Qt5 with
257 * some arabic text, since the glyph-shaping operations are not
258 * done (documented in Qt5).
259 * * QTextLayout is broken for single characters with null width
260 * (like \not in mathed).
261 * * While QTextLine::horizontalAdvance is the right thing to use
262 * for text strings, it does not give a good result with some
263 * characters like the \int (gyph 4) of esint.
265 * The metrics of some of our math fonts (eg. esint) are such that
266 * QTextLine::horizontalAdvance leads, more or less, in the middle
267 * of a symbol. This is the horizontal position where a subscript
268 * should be drawn, so that the superscript has to be moved rightward.
269 * This is done when the kerning() method of the math insets returns
270 * a positive value. The problem with this choice is that navigating
271 * a formula becomes weird. For example, a selection extends only over
272 * about half of the symbol. In order to avoid this, with our math
273 * fonts we use QTextLine::naturalTextWidth, so that a superscript can
274 * be drawn right after the symbol, and move the subscript leftward by
275 * recording a negative value for the kerning.
278 // is the string a single character from a math font ?
279 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
281 QString const qs = toqstr(s);
282 int br_width = metrics_.boundingRect(qs).width();
283 #if QT_VERSION >= 0x050b00
284 int s_width = metrics_.horizontalAdvance(qs);
286 int s_width = metrics_.width(qs);
288 // keep value 0 for math chars with width 0
290 w = max(br_width, s_width);
293 tl.setText(toqstr(s));
296 QTextLine line = tl.createLine();
298 w = iround(line.horizontalAdvance());
300 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
305 int GuiFontMetrics::width(QString const & ucs2) const
307 return width(qstring_to_ucs4(ucs2));
311 int GuiFontMetrics::signedWidth(docstring const & s) const
317 return -width(s.substr(1, s.size() - 1));
323 uint qHash(TextLayoutKey const & key)
325 double params = (2 * key.rtl - 1) * key.ws;
326 return std::qHash(key.s) ^ ::qHash(params);
330 // This holds a translation table between the original string and the
331 // QString that we can use with QTextLayout.
332 struct TextLayoutHelper
334 /// Create the helper
335 /// \c s is the original string
336 /// \c isrtl is true if the string is right-to-left
337 TextLayoutHelper(docstring const & s, bool isrtl);
339 /// translate QString index to docstring index
340 docstring::size_type qpos2pos(int qpos) const
342 return lower_bound(pos2qpos_.begin(), pos2qpos_.end(), qpos) - pos2qpos_.begin();
345 /// Translate docstring index to QString index
346 int pos2qpos(docstring::size_type pos) const { return pos2qpos_[pos]; }
348 // The original string
352 // is string right-to-left?
356 // This vector contains the QString pos for each string position
357 vector<int> pos2qpos_;
361 TextLayoutHelper::TextLayoutHelper(docstring const & s, bool isrtl)
362 : docstr(s), rtl(isrtl)
364 // Reserve memory for performance purpose
365 pos2qpos_.reserve(s.size());
366 qstr.reserve(2 * s.size());
368 /* Qt will not break at a leading or trailing space, and we need
369 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
371 * To work around the problem, we enclose the string between
372 * word joiner characters so that the QTextLayout algorithm will
373 * agree to break the text at these extremal spaces.
375 // Unicode character WORD JOINER
376 QChar const word_joiner(0x2060);
379 #ifdef BIDI_USE_OVERRIDE
380 /* Unicode override characters enforce drawing direction
381 * Source: http://www.iamcal.com/understanding-bidirectional-text/
382 * Left-to-right override is 0x202d and right-to-left override is 0x202e.
384 qstr += QChar(rtl ? 0x202e : 0x202d);
387 // Now translate the string character-by-character.
388 bool was_space = false;
389 for (char_type const c : s) {
390 // insert a word joiner character between consecutive spaces
391 bool const is_space = isSpace(c);
392 if (is_space && was_space)
394 was_space = is_space;
395 // Remember the QString index at this point
396 pos2qpos_.push_back(qstr.size());
397 // Performance: UTF-16 characters are easier
399 qstr += ucs4_to_qchar(c);
404 // Final word joiner (see above)
407 // Add virtual position at the end of the string
408 pos2qpos_.push_back(qstr.size());
410 //QString dump = qstr;
411 //LYXERR0("TLH: " << dump.replace(word_joiner, "|").toStdString());
417 shared_ptr<QTextLayout>
418 getTextLayout_helper(TextLayoutHelper const & tlh, double const wordspacing,
421 auto const ptl = make_shared<QTextLayout>();
422 ptl->setCacheEnabled(true);
423 font.setWordSpacing(wordspacing);
426 /* Use undocumented flag to enforce drawing direction
427 * FIXME: This does not work with Qt 5.11 (ticket #11284).
429 ptl->setFlags(tlh.rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
431 ptl->setText(tlh.qstr);
442 shared_ptr<QTextLayout const>
443 GuiFontMetrics::getTextLayout(TextLayoutHelper const & tlh,
444 double const wordspacing) const
446 PROFILE_THIS_BLOCK(getTextLayout_TLH);
447 TextLayoutKey key{tlh.docstr, tlh.rtl, wordspacing};
448 if (auto ptl = qtextlayout_cache_[key])
450 PROFILE_CACHE_MISS(getTextLayout_TLH);
451 auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
452 qtextlayout_cache_.insert(key, ptl);
457 shared_ptr<QTextLayout const>
458 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
459 double const wordspacing) const
461 PROFILE_THIS_BLOCK(getTextLayout);
462 TextLayoutKey key{s, rtl, wordspacing};
463 if (auto ptl = qtextlayout_cache_[key])
465 PROFILE_CACHE_MISS(getTextLayout);
466 TextLayoutHelper tlh(s, rtl);
467 auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
468 qtextlayout_cache_.insert(key, ptl);
473 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
474 double const wordspacing) const
476 TextLayoutHelper tlh(s, rtl);
477 auto ptl = getTextLayout(tlh, wordspacing);
478 // pos can be negative, see #10506.
479 int const qpos = tlh.pos2qpos(max(pos, 0));
480 return static_cast<int>(ptl->lineForTextPosition(qpos).cursorToX(qpos));
484 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
485 double const wordspacing) const
487 TextLayoutHelper tlh(s, rtl);
488 auto ptl = getTextLayout(tlh, wordspacing);
489 QTextLine const & tline = ptl->lineForTextPosition(0);
490 int qpos = tline.xToCursor(x);
491 int newx = static_cast<int>(tline.cursorToX(qpos));
492 // The value of qpos may be wrong in rtl text (see ticket #10569).
493 // To work around this, let's have a look at adjacent positions to
494 // see whether we find closer matches.
495 if (rtl && newx < x) {
497 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
498 if (abs(xm - x) < abs(newx - x)) {
504 } else if (rtl && newx > x) {
505 while (qpos < tline.textLength()) {
506 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
507 if (abs(xp - x) < abs(newx - x)) {
514 // correct x value to the actual cursor position.
517 return tlh.qpos2pos(qpos);
522 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
523 bool rtl, bool force) const
525 TextLayoutHelper const tlh(s, rtl);
529 /* Use undocumented flag to enforce drawing direction
530 * FIXME: This does not work with Qt 5.11 (ticket #11284).
532 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
534 tl.setText(tlh.qstr);
538 * Some Asian languages split lines anywhere (no notion of
539 * word). It seems that QTextLayout is not aware of this fact.
541 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
543 * FIXME: Something shall be done about characters which are
544 * not allowed at the beginning or end of line.
546 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
547 : QTextOption::WordWrap);
548 tl.setTextOption(to);
553 QTextLine line = tl.createLine();
556 line.setLineWidth(first ? first_wid : wid);
563 for (int i = 0 ; i < tl.lineCount() ; ++i) {
564 QTextLine const & line = tl.lineAt(i);
565 int const line_epos = line.textStart() + line.textLength();
566 int const epos = tlh.qpos2pos(line_epos);
567 // This does not take trailing spaces into account, except for the last line.
568 int const wid = iround(line.naturalTextWidth());
569 // If the line is not the last one, trailing space is always omitted.
571 // For the last line, compute the width without trailing space
572 if (i + 1 == tl.lineCount() && !s.empty() && isSpace(s.back())
573 && line.textStart() <= tlh.pos2qpos(s.size() - 1))
574 nspc_wid = iround(line.cursorToX(tlh.pos2qpos(s.size() - 1)));
575 breaks.emplace_back(epos - pos, wid, nspc_wid);
583 uint qHash(BreakStringKey const & key)
585 // assume widths are less than 10000. This fits in 32 bits.
586 uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
587 return std::qHash(key.s) ^ ::qHash(params);
591 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
592 bool rtl, bool force) const
594 PROFILE_THIS_BLOCK(breakString);
598 BreakStringKey key{s, first_wid, wid, rtl, force};
600 if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
603 PROFILE_CACHE_MISS(breakString);
604 brks = breakString_helper(s, first_wid, wid, rtl, force);
605 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
611 void GuiFontMetrics::rectText(docstring const & str,
612 int & w, int & ascent, int & descent) const
614 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
615 int const offset = 4;
617 w = width(str) + offset;
618 ascent = metrics_.ascent() + offset / 2;
619 descent = metrics_.descent() + offset / 2;
623 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
624 int & w, int & ascent, int & descent) const
626 rectText(str, w, ascent, descent);
631 Dimension const GuiFontMetrics::defaultDimension() const
633 return Dimension(0, maxAscent(), maxDescent());
637 Dimension const GuiFontMetrics::dimension(char_type c) const
639 return Dimension(width(c), ascent(c), descent(c));
643 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
648 r = metrics_.boundingRect(ucs4_to_qchar(c));
650 r = metrics_.boundingRect(toqstr(docstring(1, c)));
652 AscendDescend ad = { -r.top(), r.bottom() + 1};
653 // We could as well compute the width but this is not really
654 // needed for now as it is done directly in width() below.
655 metrics_cache_.insert(c, ad);
661 int GuiFontMetrics::width(char_type c) const
663 int value = width_cache_.value(c, outOfLimitMetric);
664 if (value != outOfLimitMetric)
667 #if QT_VERSION >= 0x050b00
669 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
671 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
674 value = metrics_.width(ucs4_to_qchar(c));
676 value = metrics_.width(toqstr(docstring(1, c)));
679 width_cache_.insert(c, value);
685 int GuiFontMetrics::ascent(char_type c) const
687 static AscendDescend const outOfLimitAD =
688 {outOfLimitMetric, outOfLimitMetric};
689 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
690 if (value.ascent != outOfLimitMetric)
693 value = fillMetricsCache(c);
698 int GuiFontMetrics::descent(char_type c) const
700 static AscendDescend const outOfLimitAD =
701 {outOfLimitMetric, outOfLimitMetric};
702 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
703 if (value.descent != outOfLimitMetric)
704 return value.descent;
706 value = fillMetricsCache(c);
707 return value.descent;
710 } // namespace frontend