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"
33 #if QT_VERSION >= 0x050100
36 #define qDegreesToRadians(degree) (degree * (M_PI / 180))
40 using namespace lyx::support;
42 /* Define what mechanisms are used to enforce text direction. There
43 * are two methods that work with different Qt versions. Here we try
44 * to use both methods together.
46 // Define to use unicode override characters to force direction
47 #define BIDI_USE_OVERRIDE
48 // Define to use QTextLayout flag to force direction
51 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
52 # error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
59 * Argument-dependent lookup implies that this function shall be
60 * declared in the namespace of its argument. But this is std
61 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
63 uint qHash(lyx::docstring const & s)
65 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
66 s.size() * sizeof(lyx::docstring::value_type)));
76 // Maximal size/cost for various caches. See QCache documentation to
77 // see what cost means.
79 // Limit strwidth_cache_ total cost to 1MB of string data.
80 int const strwidth_cache_max_cost = 1024 * 1024;
81 // Limit breakstr_cache_ total cost to 10MB of string data.
82 // This is useful for documents with very large insets.
83 int const breakstr_cache_max_cost = 10 * 1024 * 1024;
84 // Qt 5.x already has its own caching of QTextLayout objects
85 // but it does not seem to work well on MacOS X.
87 //FIXME KILLQT4: check wether setting the cache to 0 hurts on macOS
88 // Limit qtextlayout_cache_ size to 500 elements (we do not know the
89 // size of the QTextLayout objects anyway).
90 int const qtextlayout_cache_max_size = 500;
93 int const qtextlayout_cache_max_size = 0;
98 * Convert a UCS4 character into a QChar.
99 * This is a hack (it does only make sense for the common part of the UCS4
100 * and UTF16 encodings) and should not be used.
101 * This does only exist because of performance reasons (a real conversion
102 * using iconv is too slow on windows).
104 * This is no real conversion but a simple cast in reality. This is the reason
105 * why this works well for symbol fonts used in mathed too, even though
106 * these are not real ucs4 characters. These are codepoints in the
107 * computer modern fonts used, nothing unicode related.
108 * See comment in GuiPainter::text() for more explanation.
110 inline QChar const ucs4_to_qchar(char_type const ucs4)
112 LATTEST(is_utf16(ucs4));
113 return QChar(static_cast<unsigned short>(ucs4));
118 GuiFontMetrics::GuiFontMetrics(QFont const & font)
119 : font_(font), metrics_(font, 0),
120 strwidth_cache_(strwidth_cache_max_cost),
121 breakstr_cache_(breakstr_cache_max_cost),
122 qtextlayout_cache_(qtextlayout_cache_max_size)
124 // Determine italic slope
125 double const defaultSlope = tan(qDegreesToRadians(19.0));
126 QRawFont raw = QRawFont::fromFont(font);
127 QByteArray post(raw.fontTable("post"));
128 if (post.length() == 0) {
129 slope_ = defaultSlope;
130 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
132 // post table description:
133 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
134 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
135 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
136 slope_ = -tan(qDegreesToRadians(angle));
137 // Correct italic fonts with zero slope
138 if (slope_ == 0.0 && font.italic())
139 slope_ = defaultSlope;
140 LYXERR(Debug::FONT, "Italic slope: " << slope_);
145 int GuiFontMetrics::maxAscent() const
147 return metrics_.ascent();
151 int GuiFontMetrics::maxDescent() const
153 // We add 1 as the value returned by QT is different than X
154 // 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 (int * wid_p = strwidth_cache_.object_ptr(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 bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
284 QString const qs = toqstr(s);
285 int br_width = metrics_.boundingRect(qs).width();
286 #if QT_VERSION >= 0x050b00
287 int s_width = metrics_.horizontalAdvance(qs);
289 int s_width = metrics_.width(qs);
291 // keep value 0 for math chars with width 0
293 w = max(br_width, s_width);
296 tl.setText(toqstr(s));
299 QTextLine line = tl.createLine();
301 w = iround(line.horizontalAdvance());
303 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
308 int GuiFontMetrics::width(QString const & ucs2) const
310 return width(qstring_to_ucs4(ucs2));
314 int GuiFontMetrics::signedWidth(docstring const & s) const
320 return -width(s.substr(1, s.size() - 1));
326 uint qHash(TextLayoutKey const & key)
328 double params = (2 * key.rtl - 1) * key.ws;
329 return std::qHash(key.s) ^ ::qHash(params);
333 // This holds a translation table between the original string and the
334 // QString that we can use with QTextLayout.
335 struct TextLayoutHelper
337 /// Create the helper
338 /// \c s is the original string
339 /// \c isrtl is true if the string is right-to-left
340 TextLayoutHelper(docstring const & s, bool isrtl);
342 /// translate QString index to docstring index
343 docstring::size_type qpos2pos(int qpos) const
345 return lower_bound(pos2qpos_.begin(), pos2qpos_.end(), qpos) - pos2qpos_.begin();
348 /// Translate docstring index to QString index
349 int pos2qpos(docstring::size_type pos) const { return pos2qpos_[pos]; }
351 // The original string
355 // is string right-to-left?
359 // This vector contains the QString pos for each string position
360 vector<int> pos2qpos_;
364 TextLayoutHelper::TextLayoutHelper(docstring const & s, bool isrtl)
365 : docstr(s), rtl(isrtl)
367 // Reserve memory for performance purpose
368 pos2qpos_.reserve(s.size());
369 qstr.reserve(2 * s.size());
371 /* Qt will not break at a leading or trailing space, and we need
372 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
374 * To work around the problem, we enclose the string between
375 * word joiner characters so that the QTextLayout algorithm will
376 * agree to break the text at these extremal spaces.
378 // Unicode character WORD JOINER
379 QChar const word_joiner(0x2060);
382 #ifdef BIDI_USE_OVERRIDE
383 /* Unicode override characters enforce drawing direction
384 * Source: http://www.iamcal.com/understanding-bidirectional-text/
385 * Left-to-right override is 0x202d and right-to-left override is 0x202e.
387 qstr += QChar(rtl ? 0x202e : 0x202d);
390 // Now translate the string character-by-character.
391 bool was_space = false;
392 for (char_type const c : s) {
393 // insert a word joiner character between consecutive spaces
394 bool const is_space = isSpace(c);
395 if (is_space && was_space)
397 was_space = is_space;
398 // Remember the QString index at this point
399 pos2qpos_.push_back(qstr.size());
400 // Performance: UTF-16 characters are easier
402 qstr += ucs4_to_qchar(c);
407 // Final word joiner (see above)
410 // Add virtual position at the end of the string
411 pos2qpos_.push_back(qstr.size());
413 //QString dump = qstr;
414 //LYXERR0("TLH: " << dump.replace(word_joiner, "|").toStdString());
420 shared_ptr<QTextLayout>
421 getTextLayout_helper(TextLayoutHelper const & tlh, double const wordspacing,
424 auto const ptl = make_shared<QTextLayout>();
425 ptl->setCacheEnabled(true);
426 font.setWordSpacing(wordspacing);
429 /* Use undocumented flag to enforce drawing direction
430 * FIXME: This does not work with Qt 5.11 (ticket #11284).
432 ptl->setFlags(tlh.rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
434 ptl->setText(tlh.qstr);
445 shared_ptr<QTextLayout const>
446 GuiFontMetrics::getTextLayout(TextLayoutHelper const & tlh,
447 double const wordspacing) const
449 PROFILE_THIS_BLOCK(getTextLayout_TLH);
450 TextLayoutKey key{tlh.docstr, tlh.rtl, wordspacing};
451 if (auto ptl = qtextlayout_cache_[key])
453 PROFILE_CACHE_MISS(getTextLayout_TLH);
454 auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
455 qtextlayout_cache_.insert(key, ptl);
460 shared_ptr<QTextLayout const>
461 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
462 double const wordspacing) const
464 PROFILE_THIS_BLOCK(getTextLayout);
465 TextLayoutKey key{s, rtl, wordspacing};
466 if (auto ptl = qtextlayout_cache_[key])
468 PROFILE_CACHE_MISS(getTextLayout);
469 TextLayoutHelper tlh(s, rtl);
470 auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
471 qtextlayout_cache_.insert(key, ptl);
476 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
477 double const wordspacing) const
479 TextLayoutHelper tlh(s, rtl);
480 auto ptl = getTextLayout(tlh, wordspacing);
481 // pos can be negative, see #10506.
482 int const qpos = tlh.pos2qpos(max(pos, 0));
483 return static_cast<int>(ptl->lineForTextPosition(qpos).cursorToX(qpos));
487 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
488 double const wordspacing) const
490 TextLayoutHelper tlh(s, rtl);
491 auto ptl = getTextLayout(tlh, wordspacing);
492 QTextLine const & tline = ptl->lineForTextPosition(0);
493 int qpos = tline.xToCursor(x);
494 int newx = static_cast<int>(tline.cursorToX(qpos));
495 // The value of qpos may be wrong in rtl text (see ticket #10569).
496 // To work around this, let's have a look at adjacent positions to
497 // see whether we find closer matches.
498 if (rtl && newx < x) {
500 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
501 if (abs(xm - x) < abs(newx - x)) {
507 } else if (rtl && newx > x) {
508 while (qpos < tline.textLength()) {
509 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
510 if (abs(xp - x) < abs(newx - x)) {
517 // correct x value to the actual cursor position.
520 return tlh.qpos2pos(qpos);
525 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
526 bool rtl, bool force) const
528 TextLayoutHelper const tlh(s, rtl);
532 /* Use undocumented flag to enforce drawing direction
533 * FIXME: This does not work with Qt 5.11 (ticket #11284).
535 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
537 tl.setText(tlh.qstr);
541 * Some Asian languages split lines anywhere (no notion of
542 * word). It seems that QTextLayout is not aware of this fact.
544 * https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
546 * FIXME: Something shall be done about characters which are
547 * not allowed at the beginning or end of line.
549 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
550 : QTextOption::WordWrap);
551 tl.setTextOption(to);
556 QTextLine line = tl.createLine();
559 line.setLineWidth(first ? first_wid : wid);
566 for (int i = 0 ; i < tl.lineCount() ; ++i) {
567 QTextLine const & line = tl.lineAt(i);
568 int const line_epos = line.textStart() + line.textLength();
569 int const epos = tlh.qpos2pos(line_epos);
570 // This does not take trailing spaces into account, except for the last line.
571 int const wid = iround(line.naturalTextWidth());
572 // If the line is not the last one, trailing space is always omitted.
574 // For the last line, compute the width without trailing space
575 if (i + 1 == tl.lineCount() && !s.empty() && isSpace(s.back())
576 && line.textStart() <= tlh.pos2qpos(s.size() - 1))
577 nspc_wid = iround(line.cursorToX(tlh.pos2qpos(s.size() - 1)));
578 breaks.emplace_back(epos - pos, wid, nspc_wid);
586 uint qHash(BreakStringKey const & key)
588 // assume widths are less than 10000. This fits in 32 bits.
589 uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
590 return std::qHash(key.s) ^ ::qHash(params);
594 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
595 bool rtl, bool force) const
597 PROFILE_THIS_BLOCK(breakString);
601 BreakStringKey key{s, first_wid, wid, rtl, force};
603 if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
606 PROFILE_CACHE_MISS(breakString);
607 brks = breakString_helper(s, first_wid, wid, rtl, force);
608 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
614 void GuiFontMetrics::rectText(docstring const & str,
615 int & w, int & ascent, int & descent) const
617 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
618 int const offset = 4;
620 w = width(str) + offset;
621 ascent = metrics_.ascent() + offset / 2;
622 descent = metrics_.descent() + offset / 2;
626 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
627 int & w, int & ascent, int & descent) const
629 rectText(str, w, ascent, descent);
634 Dimension const GuiFontMetrics::defaultDimension() const
636 return Dimension(0, maxAscent(), maxDescent());
640 Dimension const GuiFontMetrics::dimension(char_type c) const
642 return Dimension(width(c), ascent(c), descent(c));
646 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
651 r = metrics_.boundingRect(ucs4_to_qchar(c));
653 r = metrics_.boundingRect(toqstr(docstring(1, c)));
655 AscendDescend ad = { -r.top(), r.bottom() + 1};
656 // We could as well compute the width but this is not really
657 // needed for now as it is done directly in width() below.
658 metrics_cache_.insert(c, ad);
664 int GuiFontMetrics::width(char_type c) const
666 int value = width_cache_.value(c, outOfLimitMetric);
667 if (value != outOfLimitMetric)
670 #if QT_VERSION >= 0x050b00
672 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
674 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
677 value = metrics_.width(ucs4_to_qchar(c));
679 value = metrics_.width(toqstr(docstring(1, c)));
682 width_cache_.insert(c, value);
688 int GuiFontMetrics::ascent(char_type c) const
690 static AscendDescend const outOfLimitAD =
691 {outOfLimitMetric, outOfLimitMetric};
692 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
693 if (value.ascent != outOfLimitMetric)
696 value = fillMetricsCache(c);
701 int GuiFontMetrics::descent(char_type c) const
703 static AscendDescend const outOfLimitAD =
704 {outOfLimitMetric, outOfLimitMetric};
705 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
706 if (value.descent != outOfLimitMetric)
707 return value.descent;
709 value = fillMetricsCache(c);
710 return value.descent;
713 } // namespace frontend