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/lassert.h"
27 using namespace lyx::support;
34 * Convert a UCS4 character into a QChar.
35 * This is a hack (it does only make sense for the common part of the UCS4
36 * and UTF16 encodings) and should not be used.
37 * This does only exist because of performance reasons (a real conversion
38 * using iconv is too slow on windows).
40 * This is no real conversion but a simple cast in reality. This is the reason
41 * why this works well for symbol fonts used in mathed too, even though
42 * these are not real ucs4 characters. These are codepoints in the
43 * computer modern fonts used, nothing unicode related.
44 * See comment in GuiPainter::text() for more explanation.
46 inline QChar const ucs4_to_qchar(char_type const ucs4)
48 LATTEST(is_utf16(ucs4));
49 return QChar(static_cast<unsigned short>(ucs4));
54 // Limit strwidth_cache_ size to 512kB of string data
55 GuiFontMetrics::GuiFontMetrics(QFont const & font)
56 : font_(font), metrics_(font, 0),
57 strwidth_cache_(1 << 19),
58 tl_cache_rtl_(false), tl_cache_wordspacing_(-1.0)
63 int GuiFontMetrics::maxAscent() const
65 return metrics_.ascent();
69 int GuiFontMetrics::maxDescent() const
71 // We add 1 as the value returned by QT is different than X
72 // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
73 return metrics_.descent() + 1;
77 int GuiFontMetrics::em() const
79 return QFontInfo(font_).pixelSize();
83 int GuiFontMetrics::lineWidth() const
85 return metrics_.lineWidth();
89 int GuiFontMetrics::underlinePos() const
91 return metrics_.underlinePos();
95 int GuiFontMetrics::strikeoutPos() const
97 return metrics_.strikeOutPos();
101 int GuiFontMetrics::lbearing(char_type c) const
104 // FIXME: QFontMetrics::leftBearing does not support the
105 // full unicode range. Once it does, we could use:
106 //return metrics_.leftBearing(toqstr(docstring(1, c)));
109 return metrics_.leftBearing(ucs4_to_qchar(c));
114 int const outOfLimitMetric = -10000;
118 int GuiFontMetrics::rbearing(char_type c) const
120 int value = rbearing_cache_.value(c, outOfLimitMetric);
121 if (value != outOfLimitMetric)
124 // Qt rbearing is from the right edge of the char's width().
126 QChar sc = ucs4_to_qchar(c);
127 value = width(c) - metrics_.rightBearing(sc);
129 // FIXME: QFontMetrics::leftBearing does not support the
130 // full unicode range. Once it does, we could use:
131 // metrics_.rightBearing(toqstr(docstring(1, c)));
135 rbearing_cache_.insert(c, value);
141 int GuiFontMetrics::width(docstring const & s) const
144 QByteArray(reinterpret_cast<char const *>(s.data()),
145 s.size() * sizeof(docstring::value_type));
146 int * pw = strwidth_cache_[qba];
149 // For some reason QMetrics::width returns a wrong value with Qt5
150 // int w = metrics_.width(toqstr(s));
152 tl.setText(toqstr(s));
155 QTextLine line = tl.createLine();
157 int w = int(line.naturalTextWidth());
159 strwidth_cache_.insert(qba, new int(w), qba.size());
164 int GuiFontMetrics::width(QString const & ucs2) const
166 return width(qstring_to_ucs4(ucs2));
170 int GuiFontMetrics::signedWidth(docstring const & s) const
176 return -width(s.substr(1, s.size() - 1));
183 GuiFontMetrics::getTextLayout(docstring const & s, QFont font,
184 bool const rtl, double const wordspacing) const
186 if (s != tl_cache_s_ || font != tl_cache_font_ || rtl != tl_cache_rtl_
187 || wordspacing != tl_cache_wordspacing_) {
188 tl_cache_.setText(toqstr(s));
189 font.setWordSpacing(wordspacing);
190 tl_cache_.setFont(font);
191 // Note that both setFlags and the enums are undocumented
192 tl_cache_.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
193 tl_cache_.beginLayout();
194 tl_cache_.createLine();
195 tl_cache_.endLayout();
197 tl_cache_font_ = font;
199 tl_cache_wordspacing_ = wordspacing;
205 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
206 double const wordspacing) const
208 QTextLayout const & tl = getTextLayout(s, font_, rtl, wordspacing);
209 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
210 * not be the same when there are high-plan unicode characters
213 int const qpos = toqstr(s.substr(0, pos)).length();
214 return static_cast<int>(tl.lineForTextPosition(qpos).cursorToX(qpos));
218 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
219 double const wordspacing) const
221 QTextLayout const & tl = getTextLayout(s, font_, rtl, wordspacing);
222 int const qpos = tl.lineForTextPosition(0).xToCursor(x);
223 // correct x value to the actual cursor position.
224 x = static_cast<int>(tl.lineForTextPosition(0).cursorToX(qpos));
225 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
226 * not be the same when there are high-plan unicode characters
229 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
230 return qstring_to_ucs4(tl.text().left(qpos)).length();
232 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
233 * by QString::toUcs4 (used by qstring_to_ucs4)may have wrong
234 * length. We work around the problem by trying all docstring
235 * positions until the right one is found. This is slow only if
236 * there are many high-plane Unicode characters. It might be
237 * worthwhile to implement a dichotomy search if this shows up
240 int pos = min(qpos, static_cast<int>(s.length()));
241 while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
243 LASSERT(pos > 0 || qpos == 0, /**/);
249 int GuiFontMetrics::countExpanders(docstring const & str) const
251 // Numbers of characters that are expanded by inter-word spacing. These
252 // characters are spaces, except for characters 09-0D which are treated
253 // specially. (From a combination of testing with the notepad found in qt's
254 // examples, and reading the source code.) In addition, consecutive spaces
255 // only count as one expander.
256 bool wasspace = false;
258 for (char_type c : str)
259 if (c > 0x0d && QChar(c).isSpace()) {
270 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
275 /* Qt will not break at a leading or trailing space, and we need
276 * that sometimes, see http://www.lyx.org/trac/ticket/9921.
278 * To work around the problem, we enclose the string between
279 * zero-width characters so that the QTextLayout algorithm will
280 * agree to break the text at these extremal spaces.
282 // Unicode character ZERO WIDTH NO-BREAK SPACE
283 QChar const zerow_nbsp(0xfeff);
284 QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
286 /* Use unicode override characters to enforce drawing direction
287 * Source: http://www.iamcal.com/understanding-bidirectional-text/
290 // Right-to-left override: forces to draw text right-to-left
291 qs = QChar(0x202E) + qs;
293 // Left-to-right override: forces to draw text left-to-right
294 qs = QChar(0x202D) + qs;
295 int const offset = 2;
297 // Alternative version that breaks with Qt5 and arabic text (#10436)
298 // Note that both setFlags and the enums are undocumented
299 tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
300 int const offset = 1;
306 to.setWrapMode(force ? QTextOption::WrapAnywhere : QTextOption::WordWrap);
307 tl.setTextOption(to);
309 QTextLine line = tl.createLine();
310 line.setLineWidth(x);
313 if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
315 x = int(line.naturalTextWidth());
316 /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
317 * not be the same when there are high-plan unicode characters
320 // The variable `offset' is here to account for the extra leading characters.
321 // The ending character zerow_nbsp has to be ignored if the line is complete.
322 int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
323 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
324 s = qstring_to_ucs4(qs.mid(offset, qlen));
326 /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
327 * by QString::toUcs4 (used by qstring_to_ucs4)may have wrong
328 * length. We work around the problem by trying all docstring
329 * positions until the right one is found. This is slow only if
330 * there are many high-plane Unicode characters. It might be
331 * worthwhile to implement a dichotomy search if this shows up
334 int len = min(qlen, static_cast<int>(s.length()));
335 while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
337 LASSERT(len > 0 || qlen == 0, /**/);
338 s = s.substr(0, len);
344 void GuiFontMetrics::rectText(docstring const & str,
345 int & w, int & ascent, int & descent) const
347 static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
349 w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
350 ascent = metrics_.ascent() + d;
351 descent = metrics_.descent() + d;
356 void GuiFontMetrics::buttonText(docstring const & str,
357 int & w, int & ascent, int & descent) const
359 rectText(str, w, ascent, descent);
360 w += Inset::TEXT_TO_INSET_OFFSET;
364 Dimension const GuiFontMetrics::defaultDimension() const
366 return Dimension(0, maxAscent(), maxDescent());
370 Dimension const GuiFontMetrics::dimension(char_type c) const
372 return Dimension(width(c), ascent(c), descent(c));
376 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
381 r = metrics_.boundingRect(ucs4_to_qchar(c));
383 r = metrics_.boundingRect(toqstr(docstring(1, c)));
385 AscendDescend ad = { -r.top(), r.bottom() + 1};
386 // We could as well compute the width but this is not really
387 // needed for now as it is done directly in width() below.
388 metrics_cache_.insert(c, ad);
394 int GuiFontMetrics::width(char_type c) const
396 int value = width_cache_.value(c, outOfLimitMetric);
397 if (value != outOfLimitMetric)
401 value = metrics_.width(ucs4_to_qchar(c));
403 value = metrics_.width(toqstr(docstring(1, c)));
405 width_cache_.insert(c, value);
411 int GuiFontMetrics::ascent(char_type c) const
413 static AscendDescend const outOfLimitAD =
414 {outOfLimitMetric, outOfLimitMetric};
415 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
416 if (value.ascent != outOfLimitMetric)
419 value = fillMetricsCache(c);
424 int GuiFontMetrics::descent(char_type c) const
426 static AscendDescend const outOfLimitAD =
427 {outOfLimitMetric, outOfLimitMetric};
428 AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
429 if (value.descent != outOfLimitMetric)
430 return value.descent;
432 value = fillMetricsCache(c);
433 return value.descent;
436 } // namespace frontend