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)));
55 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
56 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
57 * size of the QTextLayout objects anyway).
58 * Note that all these numbers are arbitrary.
59 * Also, setting size to 0 is tantamount to disabling the cache.
61 int cache_metrics_width_size = 1 << 19;
62 int cache_metrics_breakat_size = 1 << 19;
63 // Qt 5.x already has its own caching of QTextLayout objects
64 #if (QT_VERSION < 0x050000)
65 int cache_metrics_qtextlayout_size = 500;
67 int cache_metrics_qtextlayout_size = 0;
73 * Convert a UCS4 character into a QChar.
74 * This is a hack (it does only make sense for the common part of the UCS4
75 * and UTF16 encodings) and should not be used.
76 * This does only exist because of performance reasons (a real conversion
77 * using iconv is too slow on windows).
79 * This is no real conversion but a simple cast in reality. This is the reason
80 * why this works well for symbol fonts used in mathed too, even though
81 * these are not real ucs4 characters. These are codepoints in the
82 * computer modern fonts used, nothing unicode related.
83 * See comment in GuiPainter::text() for more explanation.
85 inline QChar const ucs4_to_qchar(char_type const ucs4)
87 LATTEST(is_utf16(ucs4));
88 return QChar(static_cast<unsigned short>(ucs4));
93 GuiFontMetrics::GuiFontMetrics(QFont const & font)
94 : font_(font), metrics_(font, 0),
95 strwidth_cache_(cache_metrics_width_size),
96 breakat_cache_(cache_metrics_breakat_size),
97 qtextlayout_cache_(cache_metrics_qtextlayout_size)
102 int GuiFontMetrics::maxAscent() const
104 return metrics_.ascent();
108 int GuiFontMetrics::maxDescent() const
110 // We add 1 as the value returned by QT is different than X
111 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
112 return metrics_.descent() + 1;
116 int GuiFontMetrics::em() const
118 return QFontInfo(font_).pixelSize();
122 int GuiFontMetrics::lineWidth() const
124 return metrics_.lineWidth();
128 int GuiFontMetrics::underlinePos() const
130 return metrics_.underlinePos();
134 int GuiFontMetrics::strikeoutPos() const
136 return metrics_.strikeOutPos();
140 int GuiFontMetrics::lbearing(char_type c) const
143 // FIXME: QFontMetrics::leftBearing does not support the
144 // full unicode range. Once it does, we could use:
145 //return metrics_.leftBearing(toqstr(docstring(1, c)));
148 return metrics_.leftBearing(ucs4_to_qchar(c));
153 int const outOfLimitMetric = -10000;
157 int GuiFontMetrics::rbearing(char_type c) const
159 int value = rbearing_cache_.value(c, outOfLimitMetric);
160 if (value != outOfLimitMetric)
163 // Qt rbearing is from the right edge of the char's width().
165 QChar sc = ucs4_to_qchar(c);
166 value = width(c) - metrics_.rightBearing(sc);
168 // FIXME: QFontMetrics::leftBearing does not support the
169 // full unicode range. Once it does, we could use:
170 // metrics_.rightBearing(toqstr(docstring(1, c)));
174 rbearing_cache_.insert(c, value);
180 int GuiFontMetrics::width(docstring const & s) const
182 PROFILE_THIS_BLOCK(width);
183 if (strwidth_cache_.contains(s))
184 return strwidth_cache_[s];
185 PROFILE_CACHE_MISS(width);
186 /* For some reason QMetrics::width returns a wrong value with Qt5
187 * with some arabic text. OTOH, QTextLayout is broken for single
188 * characters with null width (like \not in mathed). Also, as a
189 * safety measure, always use QMetrics::width with our math fonts.
193 #if QT_VERSION >= 0x040800
194 || font_.styleName() == "LyX"
197 w = metrics_.width(toqstr(s));
200 tl.setText(toqstr(s));
203 QTextLine line = tl.createLine();
205 w = int(line.naturalTextWidth());
207 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
212 int GuiFontMetrics::width(QString const & ucs2) const
214 return width(qstring_to_ucs4(ucs2));
218 int GuiFontMetrics::signedWidth(docstring const & s) const
224 return -width(s.substr(1, s.size() - 1));
230 shared_ptr<QTextLayout const>
231 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
232 double const wordspacing) const
234 PROFILE_THIS_BLOCK(getTextLayout);
235 docstring const s_cache =
236 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
237 if (auto ptl = qtextlayout_cache_[s_cache])
239 PROFILE_CACHE_MISS(getTextLayout);
240 auto const ptl = make_shared<QTextLayout>();
241 ptl->setCacheEnabled(true);
242 ptl->setText(toqstr(s));
244 copy.setWordSpacing(wordspacing);
246 // Note that both setFlags and the enums are undocumented
247 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
251 qtextlayout_cache_.insert(s_cache, ptl);
256 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
257 double const wordspacing) const
261 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
262 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
263 * not be the same when there are high-plan unicode characters
266 int const qpos = toqstr(s.substr(0, pos)).length();
267 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
271 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
272 double const wordspacing) const
274 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
275 QTextLine const & tline = tl->lineForTextPosition(0);
276 int qpos = tline.xToCursor(x);
277 int newx = static_cast<int>(tline.cursorToX(qpos));
278 // The value of qpos may be wrong in rtl text (see ticket #10569).
279 // To work around this, let's have a look at adjacent positions to
280 // see whether we find closer matches.
281 if (rtl && newx < x) {
283 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
284 if (abs(xm - x) < abs(newx - x)) {
290 } else if (rtl && newx > x) {
291 while (qpos < tline.textLength()) {
292 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
293 if (abs(xp - x) < abs(newx - x)) {
300 // correct x value to the actual cursor position.
303 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
304 * not be the same when there are high-plan unicode characters
307 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
308 return qstring_to_ucs4(tl->text().left(qpos)).length();
310 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
311 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
312 * length. We work around the problem by trying all docstring
313 * positions until the right one is found. This is slow only if
314 * there are many high-plane Unicode characters. It might be
315 * worthwhile to implement a dichotomy search if this shows up
318 int pos = min(qpos, static_cast<int>(s.length()));
319 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
321 LASSERT(pos > 0 || qpos == 0, /**/);
327 int GuiFontMetrics::countExpanders(docstring const & str) const
329 // Numbers of characters that are expanded by inter-word spacing. These
330 // characters are spaces, except for characters 09-0D which are treated
331 // specially. (From a combination of testing with the notepad found in qt's
332 // examples, and reading the source code.) In addition, consecutive spaces
333 // only count as one expander.
334 bool wasspace = false;
336 for (char_type c : str)
337 if (c > 0x0d && QChar(c).isSpace()) {
349 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
350 bool const rtl, bool const force) const
353 /* Qt will not break at a leading or trailing space, and we need
354 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
356 * To work around the problem, we enclose the string between
357 * zero-width characters so that the QTextLayout algorithm will
358 * agree to break the text at these extremal spaces.
360 // Unicode character ZERO WIDTH NO-BREAK SPACE
361 QChar const zerow_nbsp(0xfeff);
362 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
364 /* Use unicode override characters to enforce drawing direction
365 * Source: http://www.iamcal.com/understanding-bidirectional-text/
368 // Right-to-left override: forces to draw text right-to-left
369 qs = QChar(0x202E) + qs;
371 // Left-to-right override: forces to draw text left-to-right
372 qs = QChar(0x202D) + qs;
373 int const offset = 2;
375 // Alternative version that breaks with Qt5 and arabic text (#10436)
376 // Note that both setFlags and the enums are undocumented
377 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
378 int const offset = 1;
384 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
385 : QTextOption::WordWrap);
386 tl.setTextOption(to);
388 QTextLine line = tl.createLine();
389 line.setLineWidth(x);
392 if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
394 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
395 * not be the same when there are high-plan unicode characters
398 // The variable `offset' is here to account for the extra leading characters.
399 // The ending character zerow_nbsp has to be ignored if the line is complete.
400 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
401 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
402 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
404 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
405 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
406 * length. We work around the problem by trying all docstring
407 * positions until the right one is found. This is slow only if
408 * there are many high-plane Unicode characters. It might be
409 * worthwhile to implement a dichotomy search if this shows up
412 int len = min(qlen, static_cast<int>(s.length()));
413 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
415 LASSERT(len > 0 || qlen == 0, /**/);
417 // The -1 is here to account for the leading zerow_nbsp.
418 return {len, int(line.naturalTextWidth())};
422 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
424 PROFILE_THIS_BLOCK(breakAt);
428 docstring const s_cache =
429 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
432 if (breakat_cache_.contains(s_cache))
433 pp = breakat_cache_[s_cache];
435 PROFILE_CACHE_MISS(breakAt);
436 pp = breakAt_helper(s, x, rtl, force);
437 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
441 s = s.substr(0, pp.first);
447 void GuiFontMetrics::rectText(docstring const & str,
448 int & w, int & ascent, int & descent) const
450 static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
452 w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
453 ascent = metrics_.ascent() + d;
454 descent = metrics_.descent() + d;
458 void GuiFontMetrics::buttonText(docstring const & str,
459 int & w, int & ascent, int & descent) const
461 rectText(str, w, ascent, descent);
462 w += Inset::TEXT_TO_INSET_OFFSET;
466 Dimension const GuiFontMetrics::defaultDimension() const
468 return Dimension(0, maxAscent(), maxDescent());
472 Dimension const GuiFontMetrics::dimension(char_type c) const
474 return Dimension(width(c), ascent(c), descent(c));
478 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
483 r = metrics_.boundingRect(ucs4_to_qchar(c));
485 r = metrics_.boundingRect(toqstr(docstring(1, c)));
487 AscendDescend ad = { -r.top(), r.bottom() + 1};
488 // We could as well compute the width but this is not really
489 // needed for now as it is done directly in width() below.
490 metrics_cache_.insert(c, ad);
496 int GuiFontMetrics::width(char_type c) const
498 int value = width_cache_.value(c, outOfLimitMetric);
499 if (value != outOfLimitMetric)
503 value = metrics_.width(ucs4_to_qchar(c));
505 value = metrics_.width(toqstr(docstring(1, c)));
507 width_cache_.insert(c, value);
513 int GuiFontMetrics::ascent(char_type c) const
515 static AscendDescend const outOfLimitAD =
516 {outOfLimitMetric, outOfLimitMetric};
517 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
518 if (value.ascent != outOfLimitMetric)
521 value = fillMetricsCache(c);
526 int GuiFontMetrics::descent(char_type c) const
528 static AscendDescend const outOfLimitAD =
529 {outOfLimitMetric, outOfLimitMetric};
530 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
531 if (value.descent != outOfLimitMetric)
532 return value.descent;
534 value = fillMetricsCache(c);
535 return value.descent;
538 } // namespace frontend