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"
24 #define DISABLE_PMPROF
25 #include "support/pmprof.h"
30 using namespace lyx::support;
35 * Argument-dependent lookup implies that this function shall be
36 * declared in the namespace of its argument. But this is std
37 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
39 uint qHash(lyx::docstring const & s)
41 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
42 s.size() * sizeof(lyx::docstring::value_type)));
52 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
53 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
54 * size of the QTextLayout objects anyway).
55 * Note that all these numbers are arbitrary.
56 * Also, setting size to 0 is tantamount to disabling the cache.
58 int cache_metrics_width_size = 1 << 19;
59 int cache_metrics_breakat_size = 1 << 19;
60 // Qt 5.x already has its own caching of QTextLayout objects
61 // but it does not seem to work well on MacOS X.
62 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
63 int cache_metrics_qtextlayout_size = 500;
65 int cache_metrics_qtextlayout_size = 0;
71 * Convert a UCS4 character into a QChar.
72 * This is a hack (it does only make sense for the common part of the UCS4
73 * and UTF16 encodings) and should not be used.
74 * This does only exist because of performance reasons (a real conversion
75 * using iconv is too slow on windows).
77 * This is no real conversion but a simple cast in reality. This is the reason
78 * why this works well for symbol fonts used in mathed too, even though
79 * these are not real ucs4 characters. These are codepoints in the
80 * computer modern fonts used, nothing unicode related.
81 * See comment in GuiPainter::text() for more explanation.
83 inline QChar const ucs4_to_qchar(char_type const ucs4)
85 LATTEST(is_utf16(ucs4));
86 return QChar(static_cast<unsigned short>(ucs4));
91 GuiFontMetrics::GuiFontMetrics(QFont const & font)
92 : font_(font), metrics_(font, 0),
93 strwidth_cache_(cache_metrics_width_size),
94 breakat_cache_(cache_metrics_breakat_size),
95 qtextlayout_cache_(cache_metrics_qtextlayout_size)
100 int GuiFontMetrics::maxAscent() const
102 return metrics_.ascent();
106 int GuiFontMetrics::maxDescent() const
108 // We add 1 as the value returned by QT is different than X
109 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
110 return metrics_.descent() + 1;
114 int GuiFontMetrics::em() const
116 return QFontInfo(font_).pixelSize();
120 int GuiFontMetrics::xHeight() const
122 // LATTEST(metrics_.xHeight() == ascent('x'));
123 return metrics_.xHeight();
127 int GuiFontMetrics::lineWidth() const
129 return metrics_.lineWidth();
133 int GuiFontMetrics::underlinePos() const
135 return metrics_.underlinePos();
139 int GuiFontMetrics::strikeoutPos() const
141 return metrics_.strikeOutPos();
145 int GuiFontMetrics::lbearing(char_type c) const
148 // FIXME: QFontMetrics::leftBearing does not support the
149 // full unicode range. Once it does, we could use:
150 //return metrics_.leftBearing(toqstr(docstring(1, c)));
153 return metrics_.leftBearing(ucs4_to_qchar(c));
158 int const outOfLimitMetric = -10000;
162 int GuiFontMetrics::rbearing(char_type c) const
164 int value = rbearing_cache_.value(c, outOfLimitMetric);
165 if (value != outOfLimitMetric)
168 // Qt rbearing is from the right edge of the char's width().
170 QChar sc = ucs4_to_qchar(c);
171 value = width(c) - metrics_.rightBearing(sc);
173 // FIXME: QFontMetrics::leftBearing does not support the
174 // full unicode range. Once it does, we could use:
175 // metrics_.rightBearing(toqstr(docstring(1, c)));
179 rbearing_cache_.insert(c, value);
185 int GuiFontMetrics::width(docstring const & s) const
187 PROFILE_THIS_BLOCK(width);
188 if (strwidth_cache_.contains(s))
189 return strwidth_cache_[s];
190 PROFILE_CACHE_MISS(width);
191 /* Several problems have to be taken into account:
192 * * QFontMetrics::width does not returns a wrong value with Qt5 with
193 * some arabic text, since the glyph-shaping operations are not
194 * done (documented in Qt5).
195 * * QTextLayout is broken for single characters with null width
196 * (like \not in mathed).
197 * * While QTextLine::horizontalAdvance is the right thing to use
198 * for text strings, it does not give a good result with some
199 * characters like the \int (gyph 4) of esint.
201 * Also, as a safety measure, always use QFontMetrics::width with
205 // is the string a single character from a math font ?
206 #if QT_VERSION >= 0x040800
207 bool const math_char = s.length() == 1 || font_.styleName() == "LyX";
209 bool const math_char = s.length() == 1;
211 // keep value 0 for math chars with width 0
212 if (!math_char || metrics_.width(toqstr(s)) != 0) {
214 tl.setText(toqstr(s));
217 QTextLine line = tl.createLine();
220 w = iround(line.naturalTextWidth());
222 w = iround(line.horizontalAdvance());
224 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
229 int GuiFontMetrics::width(QString const & ucs2) const
231 return width(qstring_to_ucs4(ucs2));
235 int GuiFontMetrics::signedWidth(docstring const & s) const
241 return -width(s.substr(1, s.size() - 1));
247 shared_ptr<QTextLayout const>
248 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
249 double const wordspacing) const
251 PROFILE_THIS_BLOCK(getTextLayout);
252 docstring const s_cache =
253 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
254 if (auto ptl = qtextlayout_cache_[s_cache])
256 PROFILE_CACHE_MISS(getTextLayout);
257 auto const ptl = make_shared<QTextLayout>();
258 ptl->setCacheEnabled(true);
259 ptl->setText(toqstr(s));
261 copy.setWordSpacing(wordspacing);
263 // FIXME: This might not work in all cases. See breakAt_helper.
264 // Note that both setFlags and the enums are undocumented
265 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
269 qtextlayout_cache_.insert(s_cache, ptl);
274 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
275 double const wordspacing) const
279 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
280 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
281 * not be the same when there are high-plan unicode characters
284 int const qpos = toqstr(s.substr(0, pos)).length();
285 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
289 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
290 double const wordspacing) const
292 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
293 QTextLine const & tline = tl->lineForTextPosition(0);
294 int qpos = tline.xToCursor(x);
295 int newx = static_cast<int>(tline.cursorToX(qpos));
296 // The value of qpos may be wrong in rtl text (see ticket #10569).
297 // To work around this, let's have a look at adjacent positions to
298 // see whether we find closer matches.
299 if (rtl && newx < x) {
301 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
302 if (abs(xm - x) < abs(newx - x)) {
308 } else if (rtl && newx > x) {
309 while (qpos < tline.textLength()) {
310 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
311 if (abs(xp - x) < abs(newx - x)) {
318 // correct x value to the actual cursor position.
321 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
322 * not be the same when there are high-plan unicode characters
325 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
326 return qstring_to_ucs4(tl->text().left(qpos)).length();
328 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
329 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
330 * length. We work around the problem by trying all docstring
331 * positions until the right one is found. This is slow only if
332 * there are many high-plane Unicode characters. It might be
333 * worthwhile to implement a dichotomy search if this shows up
336 int pos = min(qpos, static_cast<int>(s.length()));
337 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
339 LASSERT(pos > 0 || qpos == 0, /**/);
345 int GuiFontMetrics::countExpanders(docstring const & str) const
347 // Numbers of characters that are expanded by inter-word spacing. These
348 // characters are spaces, except for characters 09-0D which are treated
349 // specially. (From a combination of testing with the notepad found in qt's
350 // examples, and reading the source code.) In addition, consecutive spaces
351 // only count as one expander.
352 bool wasspace = false;
354 for (char_type c : str)
355 if (c > 0x0d && QChar(c).isSpace()) {
367 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
368 bool const rtl, bool const force) const
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 * zero-width characters so that the QTextLayout algorithm will
376 * agree to break the text at these extremal spaces.
378 // Unicode character ZERO WIDTH NO-BREAK SPACE
379 QChar const zerow_nbsp(0xfeff);
380 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
382 /* Use unicode override characters to enforce drawing direction
383 * Source: http://www.iamcal.com/understanding-bidirectional-text/
386 // Right-to-left override: forces to draw text right-to-left
387 qs = QChar(0x202E) + qs;
389 // Left-to-right override: forces to draw text left-to-right
390 qs = QChar(0x202D) + qs;
391 int const offset = 2;
393 // Alternative version that breaks with Qt5 and arabic text (#10436)
394 // Note that both setFlags and the enums are undocumented
395 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
396 int const offset = 1;
402 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
403 : QTextOption::WordWrap);
404 tl.setTextOption(to);
406 QTextLine line = tl.createLine();
407 line.setLineWidth(x);
410 int const line_wid = iround(line.horizontalAdvance());
411 if ((force && line.textLength() == offset) || line_wid > x)
413 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
414 * not be the same when there are high-plan unicode characters
417 // The variable `offset' is here to account for the extra leading characters.
418 // The ending character zerow_nbsp has to be ignored if the line is complete.
419 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
420 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
421 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
423 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
424 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
425 * length. We work around the problem by trying all docstring
426 * positions until the right one is found. This is slow only if
427 * there are many high-plane Unicode characters. It might be
428 * worthwhile to implement a dichotomy search if this shows up
431 int len = min(qlen, static_cast<int>(s.length()));
432 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
434 LASSERT(len > 0 || qlen == 0, /**/);
436 return {len, line_wid};
440 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
442 PROFILE_THIS_BLOCK(breakAt);
446 docstring const s_cache =
447 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
450 if (breakat_cache_.contains(s_cache))
451 pp = breakat_cache_[s_cache];
453 PROFILE_CACHE_MISS(breakAt);
454 pp = breakAt_helper(s, x, rtl, force);
455 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
459 s = s.substr(0, pp.first);
465 void GuiFontMetrics::rectText(docstring const & str,
466 int & w, int & ascent, int & descent) const
468 // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
469 int const offset = 4;
471 w = width(str) + offset;
472 ascent = metrics_.ascent() + offset / 2;
473 descent = metrics_.descent() + offset / 2;
477 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
478 int & w, int & ascent, int & descent) const
480 rectText(str, w, ascent, descent);
485 Dimension const GuiFontMetrics::defaultDimension() const
487 return Dimension(0, maxAscent(), maxDescent());
491 Dimension const GuiFontMetrics::dimension(char_type c) const
493 return Dimension(width(c), ascent(c), descent(c));
497 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
502 r = metrics_.boundingRect(ucs4_to_qchar(c));
504 r = metrics_.boundingRect(toqstr(docstring(1, c)));
506 AscendDescend ad = { -r.top(), r.bottom() + 1};
507 // We could as well compute the width but this is not really
508 // needed for now as it is done directly in width() below.
509 metrics_cache_.insert(c, ad);
515 int GuiFontMetrics::width(char_type c) const
517 int value = width_cache_.value(c, outOfLimitMetric);
518 if (value != outOfLimitMetric)
522 value = metrics_.width(ucs4_to_qchar(c));
524 value = metrics_.width(toqstr(docstring(1, c)));
526 width_cache_.insert(c, value);
532 int GuiFontMetrics::ascent(char_type c) const
534 static AscendDescend const outOfLimitAD =
535 {outOfLimitMetric, outOfLimitMetric};
536 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
537 if (value.ascent != outOfLimitMetric)
540 value = fillMetricsCache(c);
545 int GuiFontMetrics::descent(char_type c) const
547 static AscendDescend const outOfLimitAD =
548 {outOfLimitMetric, outOfLimitMetric};
549 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
550 if (value.descent != outOfLimitMetric)
551 return value.descent;
553 value = fillMetricsCache(c);
554 return value.descent;
557 } // namespace frontend