]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Handle negative values gracefully.
[lyx.git] / src / frontends / qt4 / GuiFontMetrics.cpp
1 /**
2  * \file GuiFontMetrics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiFontMetrics.h"
15
16 #include "qt_helpers.h"
17
18 #include "Dimension.h"
19 #include "Language.h"
20 #include "LyXRC.h"
21
22 #include "insets/Inset.h"
23
24 #include "support/lassert.h"
25
26 using namespace std;
27 using namespace lyx::support;
28
29 namespace lyx {
30 namespace frontend {
31
32 namespace {
33 /**
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).
39  *
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.
45  **/
46 inline QChar const ucs4_to_qchar(char_type const ucs4)
47 {
48         LATTEST(is_utf16(ucs4));
49         return QChar(static_cast<unsigned short>(ucs4));
50 }
51 } // anon namespace
52
53
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)
59 {
60 }
61
62
63 int GuiFontMetrics::maxAscent() const
64 {
65         return metrics_.ascent();
66 }
67
68
69 int GuiFontMetrics::maxDescent() const
70 {
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;
74 }
75
76
77 int GuiFontMetrics::em() const
78 {
79         return QFontInfo(font_).pixelSize();
80 }
81
82
83 int GuiFontMetrics::lineWidth() const
84 {
85         return metrics_.lineWidth();
86 }
87
88
89 int GuiFontMetrics::underlinePos() const
90 {
91         return metrics_.underlinePos();
92 }
93
94
95 int GuiFontMetrics::strikeoutPos() const
96 {
97         return metrics_.strikeOutPos();
98 }
99
100
101 int GuiFontMetrics::lbearing(char_type c) const
102 {
103         if (!is_utf16(c))
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)));
107                 return 0;
108
109         return metrics_.leftBearing(ucs4_to_qchar(c));
110 }
111
112
113 namespace {
114 int const outOfLimitMetric = -10000;
115 }
116
117
118 int GuiFontMetrics::rbearing(char_type c) const
119 {
120         int value = rbearing_cache_.value(c, outOfLimitMetric);
121         if (value != outOfLimitMetric)
122                 return value;
123
124         // Qt rbearing is from the right edge of the char's width().
125         if (is_utf16(c)) {
126                 QChar sc = ucs4_to_qchar(c);
127                 value = width(c) - metrics_.rightBearing(sc);
128         } else {
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)));
132                 value = width(c);
133         }
134
135         rbearing_cache_.insert(c, value);
136
137         return value;
138 }
139
140
141 int GuiFontMetrics::width(docstring const & s) const
142 {
143         QByteArray qba =
144                 QByteArray(reinterpret_cast<char const *>(s.data()),
145                            s.size() * sizeof(docstring::value_type));
146         int * pw = strwidth_cache_[qba];
147         if (pw)
148                 return *pw;
149         // For some reason QMetrics::width returns a wrong value with Qt5
150         // int w = metrics_.width(toqstr(s));
151         QTextLayout tl;
152         tl.setText(toqstr(s));
153         tl.setFont(font_);
154         tl.beginLayout();
155         QTextLine line = tl.createLine();
156         tl.endLayout();
157         int w = int(line.naturalTextWidth());
158
159         strwidth_cache_.insert(qba, new int(w), qba.size());
160         return w;
161 }
162
163
164 int GuiFontMetrics::width(QString const & ucs2) const
165 {
166         return width(qstring_to_ucs4(ucs2));
167 }
168
169
170 int GuiFontMetrics::signedWidth(docstring const & s) const
171 {
172         if (s.empty())
173                 return 0;
174
175         if (s[0] == '-')
176                 return -width(s.substr(1, s.size() - 1));
177         else
178                 return width(s);
179 }
180
181
182 QTextLayout const &
183 GuiFontMetrics::getTextLayout(docstring const & s, QFont font,
184                               bool const rtl, double const wordspacing) const
185 {
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();
196                 tl_cache_s_ = s;
197                 tl_cache_font_ = font;
198                 tl_cache_rtl_ = rtl;
199                 tl_cache_wordspacing_ = wordspacing;
200         }
201         return tl_cache_;
202 }
203
204
205 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
206                           double const wordspacing) const
207 {
208         if (pos <= 0)
209                 return rtl ? width(s) : 0;
210         QTextLayout const & tl = getTextLayout(s, font_, rtl, wordspacing);
211         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
212          * not be the same when there are high-plan unicode characters
213          * (bug #10443).
214          */
215         int const qpos = toqstr(s.substr(0, pos)).length();
216         return static_cast<int>(tl.lineForTextPosition(qpos).cursorToX(qpos));
217 }
218
219
220 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
221                           double const wordspacing) const
222 {
223         QTextLayout const & tl = getTextLayout(s, font_, rtl, wordspacing);
224         int const qpos = tl.lineForTextPosition(0).xToCursor(x);
225         // correct x value to the actual cursor position.
226         x = static_cast<int>(tl.lineForTextPosition(0).cursorToX(qpos));
227         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
228          * not be the same when there are high-plan unicode characters
229          * (bug #10443).
230          */
231 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
232         return qstring_to_ucs4(tl.text().left(qpos)).length();
233 #else
234         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
235          * by QString::toUcs4 (used by qstring_to_ucs4)may have wrong
236          * length. We work around the problem by trying all docstring
237          * positions until the right one is found. This is slow only if
238          * there are many high-plane Unicode characters. It might be
239          * worthwhile to implement a dichotomy search if this shows up
240          * under a profiler.
241          */
242         int pos = min(qpos, static_cast<int>(s.length()));
243         while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
244                 --pos;
245         LASSERT(pos > 0 || qpos == 0, /**/);
246         return pos;
247 #endif
248 }
249
250
251 int GuiFontMetrics::countExpanders(docstring const & str) const
252 {
253         // Numbers of characters that are expanded by inter-word spacing.  These
254         // characters are spaces, except for characters 09-0D which are treated
255         // specially.  (From a combination of testing with the notepad found in qt's
256         // examples, and reading the source code.)  In addition, consecutive spaces
257         // only count as one expander.
258         bool wasspace = false;
259         int nexp = 0;
260         for (char_type c : str)
261                 if (c > 0x0d && QChar(c).isSpace()) {
262                         if (!wasspace) {
263                                 ++nexp;
264                                 wasspace = true;
265                         }
266                 } else
267                         wasspace = false;
268         return nexp;
269 }
270
271
272 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
273 {
274         if (s.empty())
275                 return false;
276         QTextLayout tl;
277         /* Qt will not break at a leading or trailing space, and we need
278          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
279          *
280          * To work around the problem, we enclose the string between
281          * zero-width characters so that the QTextLayout algorithm will
282          * agree to break the text at these extremal spaces.
283         */
284         // Unicode character ZERO WIDTH NO-BREAK SPACE
285         QChar const zerow_nbsp(0xfeff);
286         QString qs = zerow_nbsp + toqstr(s) + zerow_nbsp;
287 #if 1
288         /* Use unicode override characters to enforce drawing direction
289          * Source: http://www.iamcal.com/understanding-bidirectional-text/
290          */
291         if (rtl)
292                 // Right-to-left override: forces to draw text right-to-left
293                 qs = QChar(0x202E) + qs;
294         else
295                 // Left-to-right override: forces to draw text left-to-right
296                 qs =  QChar(0x202D) + qs;
297         int const offset = 2;
298 #else
299         // Alternative version that breaks with Qt5 and arabic text (#10436)
300         // Note that both setFlags and the enums are undocumented
301         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
302         int const offset = 1;
303 #endif
304
305         tl.setText(qs);
306         tl.setFont(font_);
307         QTextOption to;
308         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
309                              : QTextOption::WordWrap);
310         tl.setTextOption(to);
311         tl.beginLayout();
312         QTextLine line = tl.createLine();
313         line.setLineWidth(x);
314         tl.createLine();
315         tl.endLayout();
316         if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
317                 return false;
318         x = int(line.naturalTextWidth());
319         /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
320          * not be the same when there are high-plan unicode characters
321          * (bug #10443).
322          */
323         // The variable `offset' is here to account for the extra leading characters.
324         // The ending character zerow_nbsp has to be ignored if the line is complete.
325         int const qlen = line.textLength() - offset - (line.textLength() == qs.length());
326 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
327         s = qstring_to_ucs4(qs.mid(offset, qlen));
328 #else
329         /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
330          * by QString::toUcs4 (used by qstring_to_ucs4)may have wrong
331          * length. We work around the problem by trying all docstring
332          * positions until the right one is found. This is slow only if
333          * there are many high-plane Unicode characters. It might be
334          * worthwhile to implement a dichotomy search if this shows up
335          * under a profiler.
336          */
337         int len = min(qlen, static_cast<int>(s.length()));
338         while (len >= 0 && toqstr(s.substr(0, len)).length() != qlen)
339                 --len;
340         LASSERT(len > 0 || qlen == 0, /**/);
341         s = s.substr(0, len);
342 #endif
343         return true;
344 }
345
346
347 void GuiFontMetrics::rectText(docstring const & str,
348         int & w, int & ascent, int & descent) const
349 {
350         static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
351
352         w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
353         ascent = metrics_.ascent() + d;
354         descent = metrics_.descent() + d;
355 }
356
357
358
359 void GuiFontMetrics::buttonText(docstring const & str,
360         int & w, int & ascent, int & descent) const
361 {
362         rectText(str, w, ascent, descent);
363         w += Inset::TEXT_TO_INSET_OFFSET;
364 }
365
366
367 Dimension const GuiFontMetrics::defaultDimension() const
368 {
369         return Dimension(0, maxAscent(), maxDescent());
370 }
371
372
373 Dimension const GuiFontMetrics::dimension(char_type c) const
374 {
375         return Dimension(width(c), ascent(c), descent(c));
376 }
377
378
379 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
380                 char_type c) const
381 {
382         QRect r;
383         if (is_utf16(c))
384                 r = metrics_.boundingRect(ucs4_to_qchar(c));
385         else
386                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
387
388         AscendDescend ad = { -r.top(), r.bottom() + 1};
389         // We could as well compute the width but this is not really
390         // needed for now as it is done directly in width() below.
391         metrics_cache_.insert(c, ad);
392
393         return ad;
394 }
395
396
397 int GuiFontMetrics::width(char_type c) const
398 {
399         int value = width_cache_.value(c, outOfLimitMetric);
400         if (value != outOfLimitMetric)
401                 return value;
402
403         if (is_utf16(c))
404                 value = metrics_.width(ucs4_to_qchar(c));
405         else
406                 value = metrics_.width(toqstr(docstring(1, c)));
407
408         width_cache_.insert(c, value);
409
410         return value;
411 }
412
413
414 int GuiFontMetrics::ascent(char_type c) const
415 {
416         static AscendDescend const outOfLimitAD =
417                 {outOfLimitMetric, outOfLimitMetric};
418         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
419         if (value.ascent != outOfLimitMetric)
420                 return value.ascent;
421
422         value = fillMetricsCache(c);
423         return value.ascent;
424 }
425
426
427 int GuiFontMetrics::descent(char_type c) const
428 {
429         static AscendDescend const outOfLimitAD =
430                 {outOfLimitMetric, outOfLimitMetric};
431         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
432         if (value.descent != outOfLimitMetric)
433                 return value.descent;
434
435         value = fillMetricsCache(c);
436         return value.descent;
437 }
438
439 } // namespace frontend
440 } // namespace lyx