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"
22 #include "insets/Inset.h"
24 #include "support/convert.h"
25 #include "support/lassert.h"
27 #define DISABLE_PMPROF
28 #include "support/pmprof.h"
33 using namespace lyx::support;
38 * Argument-dependent lookup implies that this function shall be
39 * declared in the namespace of its argument. But this is std
40 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
42 uint qHash(lyx::docstring const & s)
44 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
45 s.size() * sizeof(lyx::docstring::value_type)));
54 int cache_metrics_width_size = 1 << 19;
55 int cache_metrics_breakat_size = 1 << 19;
56 // Qt 5.x already has its own caching of QTextLayout objects
57 #if (QT_VERSION < 0x050000)
58 int cache_metrics_qtextlayout_size = 500;
60 int cache_metrics_qtextlayout_size = 0;
66 * Convert a UCS4 character into a QChar.
67 * This is a hack (it does only make sense for the common part of the UCS4
68 * and UTF16 encodings) and should not be used.
69 * This does only exist because of performance reasons (a real conversion
70 * using iconv is too slow on windows).
72 * This is no real conversion but a simple cast in reality. This is the reason
73 * why this works well for symbol fonts used in mathed too, even though
74 * these are not real ucs4 characters. These are codepoints in the
75 * computer modern fonts used, nothing unicode related.
76 * See comment in GuiPainter::text() for more explanation.
78 inline QChar const ucs4_to_qchar(char_type const ucs4)
80 LATTEST(is_utf16(ucs4));
81 return QChar(static_cast<unsigned short>(ucs4));
87 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
88 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
89 * size of the QTextLayout objects anyway).
90 * Note that all these numbers are arbitrary.
92 GuiFontMetrics::GuiFontMetrics(QFont const & font)
93 : font_(font), metrics_(font, 0),
94 strwidth_cache_(cache_metrics_width_size),
95 breakat_cache_(cache_metrics_breakat_size),
96 qtextlayout_cache_(cache_metrics_qtextlayout_size)
101 int GuiFontMetrics::maxAscent() const
103 return metrics_.ascent();
107 int GuiFontMetrics::maxDescent() const
109 // We add 1 as the value returned by QT is different than X
110 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
111 return metrics_.descent() + 1;
115 int GuiFontMetrics::em() const
117 return QFontInfo(font_).pixelSize();
121 int GuiFontMetrics::lineWidth() const
123 return metrics_.lineWidth();
127 int GuiFontMetrics::underlinePos() const
129 return metrics_.underlinePos();
133 int GuiFontMetrics::strikeoutPos() const
135 return metrics_.strikeOutPos();
139 int GuiFontMetrics::lbearing(char_type c) const
142 // FIXME: QFontMetrics::leftBearing does not support the
143 // full unicode range. Once it does, we could use:
144 //return metrics_.leftBearing(toqstr(docstring(1, c)));
147 return metrics_.leftBearing(ucs4_to_qchar(c));
152 int const outOfLimitMetric = -10000;
156 int GuiFontMetrics::rbearing(char_type c) const
158 int value = rbearing_cache_.value(c, outOfLimitMetric);
159 if (value != outOfLimitMetric)
162 // Qt rbearing is from the right edge of the char's width().
164 QChar sc = ucs4_to_qchar(c);
165 value = width(c) - metrics_.rightBearing(sc);
167 // FIXME: QFontMetrics::leftBearing does not support the
168 // full unicode range. Once it does, we could use:
169 // metrics_.rightBearing(toqstr(docstring(1, c)));
173 rbearing_cache_.insert(c, value);
179 int GuiFontMetrics::width(docstring const & s) const
181 PROFILE_THIS_BLOCK(width);
182 if (strwidth_cache_.contains(s))
183 return strwidth_cache_[s];
184 PROFILE_CACHE_MISS(width);
185 /* For some reason QMetrics::width returns a wrong value with Qt5
186 * with some arabic text. OTOH, QTextLayout is broken for single
187 * characters with null width (like \not in mathed). Also, as a
188 * safety measure, always use QMetrics::width with our math fonts.
192 #if QT_VERSION >= 0x040800
193 || font_.styleName() == "LyX"
196 w = metrics_.width(toqstr(s));
199 tl.setText(toqstr(s));
202 QTextLine line = tl.createLine();
204 w = int(line.naturalTextWidth());
206 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
211 int GuiFontMetrics::width(QString const & ucs2) const
213 return width(qstring_to_ucs4(ucs2));
217 int GuiFontMetrics::signedWidth(docstring const & s) const
223 return -width(s.substr(1, s.size() - 1));
229 shared_ptr<QTextLayout const>
230 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
231 double const wordspacing) const
233 PROFILE_THIS_BLOCK(getTextLayout);
234 docstring const s_cache =
235 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
236 if (auto ptl = qtextlayout_cache_[s_cache])
238 PROFILE_CACHE_MISS(getTextLayout);
239 auto const ptl = make_shared<QTextLayout>();
240 ptl->setCacheEnabled(true);
241 ptl->setText(toqstr(s));
243 copy.setWordSpacing(wordspacing);
245 // Note that both setFlags and the enums are undocumented
246 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
250 qtextlayout_cache_.insert(s_cache, ptl);
255 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
256 double const wordspacing) const
260 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
261 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
262 * not be the same when there are high-plan unicode characters
265 int const qpos = toqstr(s.substr(0, pos)).length();
266 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
270 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
271 double const wordspacing) const
273 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
274 int const qpos = tl->lineForTextPosition(0).xToCursor(x);
275 // correct x value to the actual cursor position.
276 x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
277 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
278 * not be the same when there are high-plan unicode characters
281 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
282 return qstring_to_ucs4(tl->text().left(qpos)).length();
284 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
285 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
286 * length. We work around the problem by trying all docstring
287 * positions until the right one is found. This is slow only if
288 * there are many high-plane Unicode characters. It might be
289 * worthwhile to implement a dichotomy search if this shows up
292 int pos = min(qpos, static_cast<int>(s.length()));
293 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
295 LASSERT(pos > 0 || qpos == 0, /**/);
301 int GuiFontMetrics::countExpanders(docstring const & str) const
303 // Numbers of characters that are expanded by inter-word spacing. These
304 // characters are spaces, except for characters 09-0D which are treated
305 // specially. (From a combination of testing with the notepad found in qt's
306 // examples, and reading the source code.) In addition, consecutive spaces
307 // only count as one expander.
308 bool wasspace = false;
310 for (char_type c : str)
311 if (c > 0x0d && QChar(c).isSpace()) {
323 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
324 bool const rtl, bool const force) const
327 /* Qt will not break at a leading or trailing space, and we need
328 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
330 * To work around the problem, we enclose the string between
331 * zero-width characters so that the QTextLayout algorithm will
332 * agree to break the text at these extremal spaces.
334 // Unicode character ZERO WIDTH NO-BREAK SPACE
335 QChar const zerow_nbsp(0xfeff);
336 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
338 /* Use unicode override characters to enforce drawing direction
339 * Source: http://www.iamcal.com/understanding-bidirectional-text/
342 // Right-to-left override: forces to draw text right-to-left
343 qs = QChar(0x202E) + qs;
345 // Left-to-right override: forces to draw text left-to-right
346 qs = QChar(0x202D) + qs;
347 int const offset = 2;
349 // Alternative version that breaks with Qt5 and arabic text (#10436)
350 // Note that both setFlags and the enums are undocumented
351 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
352 int const offset = 1;
358 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
359 : QTextOption::WordWrap);
360 tl.setTextOption(to);
362 QTextLine line = tl.createLine();
363 line.setLineWidth(x);
366 if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
368 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
369 * not be the same when there are high-plan unicode characters
372 // The variable `offset' is here to account for the extra leading characters.
373 // The ending character zerow_nbsp has to be ignored if the line is complete.
374 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
375 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
376 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
378 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
379 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
380 * length. We work around the problem by trying all docstring
381 * positions until the right one is found. This is slow only if
382 * there are many high-plane Unicode characters. It might be
383 * worthwhile to implement a dichotomy search if this shows up
386 int len = min(qlen, static_cast<int>(s.length()));
387 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
389 LASSERT(len > 0 || qlen == 0, /**/);
391 // The -1 is here to account for the leading zerow_nbsp.
392 return {len, int(line.naturalTextWidth())};
396 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
398 PROFILE_THIS_BLOCK(breakAt);
402 docstring const s_cache =
403 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
406 if (breakat_cache_.contains(s_cache))
407 pp = breakat_cache_[s_cache];
409 PROFILE_CACHE_MISS(breakAt);
410 pp = breakAt_helper(s, x, rtl, force);
411 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
415 s = s.substr(0, pp.first);
421 void GuiFontMetrics::rectText(docstring const & str,
422 int & w, int & ascent, int & descent) const
424 static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
426 w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
427 ascent = metrics_.ascent() + d;
428 descent = metrics_.descent() + d;
432 void GuiFontMetrics::buttonText(docstring const & str,
433 int & w, int & ascent, int & descent) const
435 rectText(str, w, ascent, descent);
436 w += Inset::TEXT_TO_INSET_OFFSET;
440 Dimension const GuiFontMetrics::defaultDimension() const
442 return Dimension(0, maxAscent(), maxDescent());
446 Dimension const GuiFontMetrics::dimension(char_type c) const
448 return Dimension(width(c), ascent(c), descent(c));
452 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
457 r = metrics_.boundingRect(ucs4_to_qchar(c));
459 r = metrics_.boundingRect(toqstr(docstring(1, c)));
461 AscendDescend ad = { -r.top(), r.bottom() + 1};
462 // We could as well compute the width but this is not really
463 // needed for now as it is done directly in width() below.
464 metrics_cache_.insert(c, ad);
470 int GuiFontMetrics::width(char_type c) const
472 int value = width_cache_.value(c, outOfLimitMetric);
473 if (value != outOfLimitMetric)
477 value = metrics_.width(ucs4_to_qchar(c));
479 value = metrics_.width(toqstr(docstring(1, c)));
481 width_cache_.insert(c, value);
487 int GuiFontMetrics::ascent(char_type c) const
489 static AscendDescend const outOfLimitAD =
490 {outOfLimitMetric, outOfLimitMetric};
491 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
492 if (value.ascent != outOfLimitMetric)
495 value = fillMetricsCache(c);
500 int GuiFontMetrics::descent(char_type c) const
502 static AscendDescend const outOfLimitAD =
503 {outOfLimitMetric, outOfLimitMetric};
504 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
505 if (value.descent != outOfLimitMetric)
506 return value.descent;
508 value = fillMetricsCache(c);
509 return value.descent;
512 } // namespace frontend