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"
30 #ifdef CACHE_SOME_METRICS
35 using namespace lyx::support;
37 #ifdef CACHE_SOME_METRICS
41 * Argument-dependent lookup implies that this function shall be
42 * declared in the namespace of its argument. But this is std
43 * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
45 uint qHash(lyx::docstring const & s)
47 return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
48 s.size() * sizeof(lyx::docstring::value_type)));
59 * Convert a UCS4 character into a QChar.
60 * This is a hack (it does only make sense for the common part of the UCS4
61 * and UTF16 encodings) and should not be used.
62 * This does only exist because of performance reasons (a real conversion
63 * using iconv is too slow on windows).
65 * This is no real conversion but a simple cast in reality. This is the reason
66 * why this works well for symbol fonts used in mathed too, even though
67 * these are not real ucs4 characters. These are codepoints in the
68 * computer modern fonts used, nothing unicode related.
69 * See comment in GuiPainter::text() for more explanation.
71 inline QChar const ucs4_to_qchar(char_type const ucs4)
73 LATTEST(is_utf16(ucs4));
74 return QChar(static_cast<unsigned short>(ucs4));
80 * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
81 * Limit qtextlayout_cache_ size to 500 elements (we do not know the
82 * size of the QTextLayout objects anyway).
83 * Note that all these numbers are arbitrary.
85 GuiFontMetrics::GuiFontMetrics(QFont const & font)
86 : font_(font), metrics_(font, 0)
87 #ifdef CACHE_METRICS_WIDTH
88 , strwidth_cache_(1 << 19)
90 #ifdef CACHE_METRICS_BREAKAT
91 , breakat_cache_(1 << 19)
93 #ifdef CACHE_METRICS_QTEXTLAYOUT
94 , qtextlayout_cache_(500)
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::lineWidth() const
122 return metrics_.lineWidth();
126 int GuiFontMetrics::underlinePos() const
128 return metrics_.underlinePos();
132 int GuiFontMetrics::strikeoutPos() const
134 return metrics_.strikeOutPos();
138 int GuiFontMetrics::lbearing(char_type c) const
141 // FIXME: QFontMetrics::leftBearing does not support the
142 // full unicode range. Once it does, we could use:
143 //return metrics_.leftBearing(toqstr(docstring(1, c)));
146 return metrics_.leftBearing(ucs4_to_qchar(c));
151 int const outOfLimitMetric = -10000;
155 int GuiFontMetrics::rbearing(char_type c) const
157 int value = rbearing_cache_.value(c, outOfLimitMetric);
158 if (value != outOfLimitMetric)
161 // Qt rbearing is from the right edge of the char's width().
163 QChar sc = ucs4_to_qchar(c);
164 value = width(c) - metrics_.rightBearing(sc);
166 // FIXME: QFontMetrics::leftBearing does not support the
167 // full unicode range. Once it does, we could use:
168 // metrics_.rightBearing(toqstr(docstring(1, c)));
172 rbearing_cache_.insert(c, value);
178 int GuiFontMetrics::width(docstring const & s) const
180 PROFILE_THIS_BLOCK(width)
181 #ifdef CACHE_METRICS_WIDTH
182 int * pw = strwidth_cache_[s];
185 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 #ifdef CACHE_METRICS_WIDTH
209 strwidth_cache_.insert(s, new int(w), s.size() * sizeof(char_type));
215 int GuiFontMetrics::width(QString const & ucs2) const
217 return width(qstring_to_ucs4(ucs2));
221 int GuiFontMetrics::signedWidth(docstring const & s) const
227 return -width(s.substr(1, s.size() - 1));
234 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
235 double const wordspacing) const
237 PROFILE_THIS_BLOCK(getTextLayout)
239 #ifdef CACHE_METRICS_QTEXTLAYOUT
240 docstring const s_cache = s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
241 ptl = qtextlayout_cache_[s_cache];
243 PROFILE_CACHE_MISS(getTextLayout)
245 ptl = new QTextLayout();
246 ptl->setCacheEnabled(true);
247 ptl->setText(toqstr(s));
249 copy.setWordSpacing(wordspacing);
251 // Note that both setFlags and the enums are undocumented
252 ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
256 #ifdef CACHE_METRICS_QTEXTLAYOUT
257 qtextlayout_cache_.insert(s_cache, ptl);
264 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
265 double const wordspacing) const
268 return rtl ? width(s) : 0;
269 QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
270 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
271 * not be the same when there are high-plan unicode characters
274 int const qpos = toqstr(s.substr(0, pos)).length();
275 return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
279 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
280 double const wordspacing) const
282 QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
283 int const qpos = tl->lineForTextPosition(0).xToCursor(x);
284 // correct x value to the actual cursor position.
285 x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
286 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
287 * not be the same when there are high-plan unicode characters
290 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
291 return qstring_to_ucs4(tl->text().left(qpos)).length();
293 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
294 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
295 * length. We work around the problem by trying all docstring
296 * positions until the right one is found. This is slow only if
297 * there are many high-plane Unicode characters. It might be
298 * worthwhile to implement a dichotomy search if this shows up
301 int pos = min(qpos, static_cast<int>(s.length()));
302 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
304 LASSERT(pos > 0 || qpos == 0, /**/);
310 int GuiFontMetrics::countExpanders(docstring const & str) const
312 // Numbers of characters that are expanded by inter-word spacing. These
313 // characters are spaces, except for characters 09-0D which are treated
314 // specially. (From a combination of testing with the notepad found in qt's
315 // examples, and reading the source code.) In addition, consecutive spaces
316 // only count as one expander.
317 bool wasspace = false;
319 for (char_type c : str)
320 if (c > 0x0d && QChar(c).isSpace()) {
332 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
333 bool const rtl, bool const force) const
336 /* Qt will not break at a leading or trailing space, and we need
337 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
339 * To work around the problem, we enclose the string between
340 * zero-width characters so that the QTextLayout algorithm will
341 * agree to break the text at these extremal spaces.
343 // Unicode character ZERO WIDTH NO-BREAK SPACE
344 QChar const zerow_nbsp(0xfeff);
345 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
347 /* Use unicode override characters to enforce drawing direction
348 * Source: http://www.iamcal.com/understanding-bidirectional-text/
351 // Right-to-left override: forces to draw text right-to-left
352 qs = QChar(0x202E) + qs;
354 // Left-to-right override: forces to draw text left-to-right
355 qs = QChar(0x202D) + qs;
356 int const offset = 2;
358 // Alternative version that breaks with Qt5 and arabic text (#10436)
359 // Note that both setFlags and the enums are undocumented
360 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
361 int const offset = 1;
367 to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
368 : QTextOption::WordWrap);
369 tl.setTextOption(to);
371 QTextLine line = tl.createLine();
372 line.setLineWidth(x);
375 if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
376 return new pair<int, int>(-1, -1);
377 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
378 * not be the same when there are high-plan unicode characters
381 // The variable `offset' is here to account for the extra leading characters.
382 // The ending character zerow_nbsp has to be ignored if the line is complete.
383 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
384 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
385 int len = qstring_to_ucs4(qs.mid(offset, qlen)).length();
387 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
388 * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
389 * length. We work around the problem by trying all docstring
390 * positions until the right one is found. This is slow only if
391 * there are many high-plane Unicode characters. It might be
392 * worthwhile to implement a dichotomy search if this shows up
395 int len = min(qlen, static_cast<int>(s.length()));
396 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
398 LASSERT(len > 0 || qlen == 0, /**/);
400 // The -1 is here to account for the leading zerow_nbsp.
401 return new pair<int, int>(len, int(line.naturalTextWidth()));
405 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
407 PROFILE_THIS_BLOCK(breakAt)
411 #ifdef CACHE_METRICS_BREAKAT
412 docstring const s_cache = s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
414 pp = breakat_cache_[s_cache];
416 PROFILE_CACHE_MISS(breakAt)
418 pp = breakAt_helper(s, x, rtl, force);
419 #ifdef CACHE_METRICS_BREAKAT
420 breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
425 s = s.substr(0, pp->first);
427 #ifndef CACHE_METRICS_BREAKAT
434 void GuiFontMetrics::rectText(docstring const & str,
435 int & w, int & ascent, int & descent) const
437 static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
439 w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
440 ascent = metrics_.ascent() + d;
441 descent = metrics_.descent() + d;
445 void GuiFontMetrics::buttonText(docstring const & str,
446 int & w, int & ascent, int & descent) const
448 rectText(str, w, ascent, descent);
449 w += Inset::TEXT_TO_INSET_OFFSET;
453 Dimension const GuiFontMetrics::defaultDimension() const
455 return Dimension(0, maxAscent(), maxDescent());
459 Dimension const GuiFontMetrics::dimension(char_type c) const
461 return Dimension(width(c), ascent(c), descent(c));
465 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
470 r = metrics_.boundingRect(ucs4_to_qchar(c));
472 r = metrics_.boundingRect(toqstr(docstring(1, c)));
474 AscendDescend ad = { -r.top(), r.bottom() + 1};
475 // We could as well compute the width but this is not really
476 // needed for now as it is done directly in width() below.
477 metrics_cache_.insert(c, ad);
483 int GuiFontMetrics::width(char_type c) const
485 int value = width_cache_.value(c, outOfLimitMetric);
486 if (value != outOfLimitMetric)
490 value = metrics_.width(ucs4_to_qchar(c));
492 value = metrics_.width(toqstr(docstring(1, c)));
494 width_cache_.insert(c, value);
500 int GuiFontMetrics::ascent(char_type c) const
502 static AscendDescend const outOfLimitAD =
503 {outOfLimitMetric, outOfLimitMetric};
504 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
505 if (value.ascent != outOfLimitMetric)
508 value = fillMetricsCache(c);
513 int GuiFontMetrics::descent(char_type c) const
515 static AscendDescend const outOfLimitAD =
516 {outOfLimitMetric, outOfLimitMetric};
517 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
518 if (value.descent != outOfLimitMetric)
519 return value.descent;
521 value = fillMetricsCache(c);
522 return value.descent;
525 } // namespace frontend