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 // but it does not seem to work well on MacOS X.
65 #if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
66 int cache_metrics_qtextlayout_size = 500;
68 int cache_metrics_qtextlayout_size = 0;
74 * Convert a UCS4 character into a QChar.
75 * This is a hack (it does only make sense for the common part of the UCS4
76 * and UTF16 encodings) and should not be used.
77 * This does only exist because of performance reasons (a real conversion
78 * using iconv is too slow on windows).
80 * This is no real conversion but a simple cast in reality. This is the reason
81 * why this works well for symbol fonts used in mathed too, even though
82 * these are not real ucs4 characters. These are codepoints in the
83 * computer modern fonts used, nothing unicode related.
84 * See comment in GuiPainter::text() for more explanation.
86 inline QChar const ucs4_to_qchar(char_type const ucs4)
88 LATTEST(is_utf16(ucs4));
89 return QChar(static_cast<unsigned short>(ucs4));
94 GuiFontMetrics::GuiFontMetrics(QFont const & font)
95 : font_(font), metrics_(font, 0),
96 strwidth_cache_(cache_metrics_width_size),
97 breakat_cache_(cache_metrics_breakat_size),
98 qtextlayout_cache_(cache_metrics_qtextlayout_size)
103 int GuiFontMetrics::maxAscent() const
105 return metrics_.ascent();
109 int GuiFontMetrics::maxDescent() const
111 // We add 1 as the value returned by QT is different than X
112 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
113 return metrics_.descent() + 1;
117 int GuiFontMetrics::em() const
119 return QFontInfo(font_).pixelSize();
123 int GuiFontMetrics::lineWidth() const
125 return metrics_.lineWidth();
129 int GuiFontMetrics::underlinePos() const
131 return metrics_.underlinePos();
135 int GuiFontMetrics::strikeoutPos() const
137 return metrics_.strikeOutPos();
141 int GuiFontMetrics::lbearing(char_type c) const
144 // FIXME: QFontMetrics::leftBearing does not support the
145 // full unicode range. Once it does, we could use:
146 //return metrics_.leftBearing(toqstr(docstring(1, c)));
149 return metrics_.leftBearing(ucs4_to_qchar(c));
154 int const outOfLimitMetric = -10000;
158 int GuiFontMetrics::rbearing(char_type c) const
160 int value = rbearing_cache_.value(c, outOfLimitMetric);
161 if (value != outOfLimitMetric)
164 // Qt rbearing is from the right edge of the char's width().
166 QChar sc = ucs4_to_qchar(c);
167 value = width(c) - metrics_.rightBearing(sc);
169 // FIXME: QFontMetrics::leftBearing does not support the
170 // full unicode range. Once it does, we could use:
171 // metrics_.rightBearing(toqstr(docstring(1, c)));
175 rbearing_cache_.insert(c, value);
181 int GuiFontMetrics::width(docstring const & s) const
183 PROFILE_THIS_BLOCK(width);
184 if (strwidth_cache_.contains(s))
185 return strwidth_cache_[s];
186 PROFILE_CACHE_MISS(width);
187 /* For some reason QMetrics::width returns a wrong value with Qt5
188 * with some arabic text. OTOH, QTextLayout is broken for single
189 * characters with null width (like \not in mathed). Also, as a
190 * safety measure, always use QMetrics::width with our math fonts.
194 #if QT_VERSION >= 0x040800
195 || font_.styleName() == "LyX"
198 w = metrics_.width(toqstr(s));
201 tl.setText(toqstr(s));
204 QTextLine line = tl.createLine();
206 w = int(line.naturalTextWidth());
208 strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
213 int GuiFontMetrics::width(QString const & ucs2) const
215 return width(qstring_to_ucs4(ucs2));
219 int GuiFontMetrics::signedWidth(docstring const & s) const
225 return -width(s.substr(1, s.size() - 1));
231 shared_ptr<QTextLayout const>
232 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
233 double const wordspacing) const
235 PROFILE_THIS_BLOCK(getTextLayout);
236 docstring const s_cache =
237 s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
238 if (auto ptl = qtextlayout_cache_[s_cache])
240 PROFILE_CACHE_MISS(getTextLayout);
241 auto const ptl = make_shared<QTextLayout>();
242 ptl->setCacheEnabled(true);
243 ptl->setText(toqstr(s));
245 copy.setWordSpacing(wordspacing);
247 // Note that both setFlags and the enums are undocumented
248 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
252 qtextlayout_cache_.insert(s_cache, ptl);
257 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
258 double const wordspacing) const
262 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
263 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
264 * not be the same when there are high-plan unicode characters
267 int const qpos = toqstr(s.substr(0, pos)).length();
268 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
272 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
273 double const wordspacing) const
275 shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
276 QTextLine const & tline = tl->lineForTextPosition(0);
277 int qpos = tline.xToCursor(x);
278 int newx = static_cast<int>(tline.cursorToX(qpos));
279 // The value of qpos may be wrong in rtl text (see ticket #10569).
280 // To work around this, let's have a look at adjacent positions to
281 // see whether we find closer matches.
282 if (rtl && newx < x) {
284 int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
285 if (abs(xm - x) < abs(newx - x)) {
291 } else if (rtl && newx > x) {
292 while (qpos < tline.textLength()) {
293 int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
294 if (abs(xp - x) < abs(newx - x)) {
301 // correct x value to the actual cursor position.
304 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
305 * not be the same when there are high-plan unicode characters
308 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
309 return qstring_to_ucs4(tl->text().left(qpos)).length();
311 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
312 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
313 * length. We work around the problem by trying all docstring
314 * positions until the right one is found. This is slow only if
315 * there are many high-plane Unicode characters. It might be
316 * worthwhile to implement a dichotomy search if this shows up
319 int pos = min(qpos, static_cast<int>(s.length()));
320 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
322 LASSERT(pos > 0 || qpos == 0, /**/);
328 int GuiFontMetrics::countExpanders(docstring const & str) const
330 // Numbers of characters that are expanded by inter-word spacing. These
331 // characters are spaces, except for characters 09-0D which are treated
332 // specially. (From a combination of testing with the notepad found in qt's
333 // examples, and reading the source code.) In addition, consecutive spaces
334 // only count as one expander.
335 bool wasspace = false;
337 for (char_type c : str)
338 if (c > 0x0d && QChar(c).isSpace()) {
350 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
351 bool const rtl, bool const force) const
354 /* Qt will not break at a leading or trailing space, and we need
355 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
357 * To work around the problem, we enclose the string between
358 * zero-width characters so that the QTextLayout algorithm will
359 * agree to break the text at these extremal spaces.
361 // Unicode character ZERO WIDTH NO-BREAK SPACE
362 QChar const zerow_nbsp(0xfeff);
363 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
365 /* Use unicode override characters to enforce drawing direction
366 * Source: http://www.iamcal.com/understanding-bidirectional-text/
369 // Right-to-left override: forces to draw text right-to-left
370 qs = QChar(0x202E) + qs;
372 // Left-to-right override: forces to draw text left-to-right
373 qs = QChar(0x202D) + qs;
374 int const offset = 2;
376 // Alternative version that breaks with Qt5 and arabic text (#10436)
377 // Note that both setFlags and the enums are undocumented
378 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
379 int const offset = 1;
385 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
386 : QTextOption::WordWrap);
387 tl.setTextOption(to);
389 QTextLine line = tl.createLine();
390 line.setLineWidth(x);
393 if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
395 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
396 * not be the same when there are high-plan unicode characters
399 // The variable `offset' is here to account for the extra leading characters.
400 // The ending character zerow_nbsp has to be ignored if the line is complete.
401 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
402 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
403 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
405 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
406 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
407 * length. We work around the problem by trying all docstring
408 * positions until the right one is found. This is slow only if
409 * there are many high-plane Unicode characters. It might be
410 * worthwhile to implement a dichotomy search if this shows up
413 int len = min(qlen, static_cast<int>(s.length()));
414 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
416 LASSERT(len > 0 || qlen == 0, /**/);
418 // The -1 is here to account for the leading zerow_nbsp.
419 return {len, int(line.naturalTextWidth())};
423 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
425 PROFILE_THIS_BLOCK(breakAt);
429 docstring const s_cache =
430 s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
433 if (breakat_cache_.contains(s_cache))
434 pp = breakat_cache_[s_cache];
436 PROFILE_CACHE_MISS(breakAt);
437 pp = breakAt_helper(s, x, rtl, force);
438 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
442 s = s.substr(0, pp.first);
448 void GuiFontMetrics::rectText(docstring const & str,
449 int & w, int & ascent, int & descent) const
451 static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
453 w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
454 ascent = metrics_.ascent() + d;
455 descent = metrics_.descent() + d;
459 void GuiFontMetrics::buttonText(docstring const & str,
460 int & w, int & ascent, int & descent) const
462 rectText(str, w, ascent, descent);
463 w += Inset::TEXT_TO_INSET_OFFSET;
467 Dimension const GuiFontMetrics::defaultDimension() const
469 return Dimension(0, maxAscent(), maxDescent());
473 Dimension const GuiFontMetrics::dimension(char_type c) const
475 return Dimension(width(c), ascent(c), descent(c));
479 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
484 r = metrics_.boundingRect(ucs4_to_qchar(c));
486 r = metrics_.boundingRect(toqstr(docstring(1, c)));
488 AscendDescend ad = { -r.top(), r.bottom() + 1};
489 // We could as well compute the width but this is not really
490 // needed for now as it is done directly in width() below.
491 metrics_cache_.insert(c, ad);
497 int GuiFontMetrics::width(char_type c) const
499 int value = width_cache_.value(c, outOfLimitMetric);
500 if (value != outOfLimitMetric)
504 value = metrics_.width(ucs4_to_qchar(c));
506 value = metrics_.width(toqstr(docstring(1, c)));
508 width_cache_.insert(c, value);
514 int GuiFontMetrics::ascent(char_type c) const
516 static AscendDescend const outOfLimitAD =
517 {outOfLimitMetric, outOfLimitMetric};
518 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
519 if (value.ascent != outOfLimitMetric)
522 value = fillMetricsCache(c);
527 int GuiFontMetrics::descent(char_type c) const
529 static AscendDescend const outOfLimitAD =
530 {outOfLimitMetric, outOfLimitMetric};
531 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
532 if (value.descent != outOfLimitMetric)
533 return value.descent;
535 value = fillMetricsCache(c);
536 return value.descent;
539 } // namespace frontend