]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiFontMetrics.cpp
Use a QCache for string metrics
[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 #include <QTextLayout>
27
28 using namespace std;
29 using namespace lyx::support;
30
31 namespace lyx {
32 namespace frontend {
33
34 namespace {
35 /**
36  * Convert a UCS4 character into a QChar.
37  * This is a hack (it does only make sense for the common part of the UCS4
38  * and UTF16 encodings) and should not be used.
39  * This does only exist because of performance reasons (a real conversion
40  * using iconv is too slow on windows).
41  *
42  * This is no real conversion but a simple cast in reality. This is the reason
43  * why this works well for symbol fonts used in mathed too, even though
44  * these are not real ucs4 characters. These are codepoints in the
45  * computer modern fonts used, nothing unicode related.
46  * See comment in GuiPainter::text() for more explanation.
47  **/
48 inline QChar const ucs4_to_qchar(char_type const ucs4)
49 {
50         LATTEST(is_utf16(ucs4));
51         return QChar(static_cast<unsigned short>(ucs4));
52 }
53 } // anon namespace
54
55
56 // Limit strwidth_cache_ size to 512kB of string data
57 GuiFontMetrics::GuiFontMetrics(QFont const & font)
58         : font_(font), metrics_(font, 0),
59           strwidth_cache_(1 << 19)
60 {
61 }
62
63
64 int GuiFontMetrics::maxAscent() const
65 {
66         return metrics_.ascent();
67 }
68
69
70 int GuiFontMetrics::maxDescent() const
71 {
72         // We add 1 as the value returned by QT is different than X
73         // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
74         return metrics_.descent() + 1;
75 }
76
77
78 int GuiFontMetrics::em() const
79 {
80         return QFontInfo(font_).pixelSize();
81 }
82
83
84 int GuiFontMetrics::lineWidth() const
85 {
86         return metrics_.lineWidth();
87 }
88
89
90 int GuiFontMetrics::underlinePos() const
91 {
92         return metrics_.underlinePos();
93 }
94
95
96 int GuiFontMetrics::strikeoutPos() const
97 {
98         return metrics_.strikeOutPos();
99 }
100
101
102 int GuiFontMetrics::lbearing(char_type c) const
103 {
104         if (!is_utf16(c))
105                 // FIXME: QFontMetrics::leftBearing does not support the
106                 //        full unicode range. Once it does, we could use:
107                 //return metrics_.leftBearing(toqstr(docstring(1, c)));
108                 return 0;
109
110         return metrics_.leftBearing(ucs4_to_qchar(c));
111 }
112
113
114 namespace {
115 int const outOfLimitMetric = -10000;
116 }
117
118
119 int GuiFontMetrics::rbearing(char_type c) const
120 {
121         int value = rbearing_cache_.value(c, outOfLimitMetric);
122         if (value != outOfLimitMetric)
123                 return value;
124
125         // Qt rbearing is from the right edge of the char's width().
126         if (is_utf16(c)) {
127                 QChar sc = ucs4_to_qchar(c);
128                 value = width(c) - metrics_.rightBearing(sc);
129         } else {
130                 // FIXME: QFontMetrics::leftBearing does not support the
131                 //        full unicode range. Once it does, we could use:
132                 // metrics_.rightBearing(toqstr(docstring(1, c)));
133                 value = width(c);
134         }
135
136         rbearing_cache_.insert(c, value);
137
138         return value;
139 }
140
141
142 int GuiFontMetrics::width(docstring const & s) const
143 {
144         QByteArray qba =
145                 QByteArray(reinterpret_cast<char const *>(s.data()),
146                            s.size() * sizeof(docstring::value_type));
147         int * pw = strwidth_cache_[qba];
148         if (pw)
149                 return *pw;
150         int w = metrics_.width(toqstr(s));
151         strwidth_cache_.insert(qba, new int(w), qba.size());
152         return w;
153 }
154
155
156 int GuiFontMetrics::width(QString const & ucs2) const
157 {
158         return width(qstring_to_ucs4(ucs2));
159 }
160
161
162 int GuiFontMetrics::signedWidth(docstring const & s) const
163 {
164         if (s.empty())
165                 return 0;
166
167         if (s[0] == '-')
168                 return -width(s.substr(1, s.size() - 1));
169         else
170                 return width(s);
171 }
172
173 namespace {
174 void setTextLayout(QTextLayout & tl, docstring const & s, QFont font,
175                    bool const rtl, double const wordspacing)
176 {
177         tl.setText(toqstr(s));
178         font.setWordSpacing(wordspacing);
179         tl.setFont(font);
180         // Note that both setFlags and the enums are undocumented
181         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
182         tl.beginLayout();
183         tl.createLine();
184         tl.endLayout();
185 }
186 }
187
188
189 int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
190                           double const wordspacing) const
191 {
192         QTextLayout tl;
193         QFont copy = font_;
194         copy.setWordSpacing(wordspacing);
195         setTextLayout(tl, s, font_, rtl, wordspacing);
196         return static_cast<int>(tl.lineForTextPosition(pos).cursorToX(pos));
197 }
198
199
200 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
201                           double const wordspacing) const
202 {
203         QTextLayout tl;
204         setTextLayout(tl, s, font_, rtl, wordspacing);
205         int pos = tl.lineForTextPosition(0).xToCursor(x);
206         // correct x value to the actual cursor position.
207         x = static_cast<int>(tl.lineForTextPosition(0).cursorToX(pos));
208         return pos;
209 }
210
211
212 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
213 {
214         if (s.empty())
215                 return false;
216         QTextLayout tl;
217         tl.setText(toqstr(s));
218         tl.setFont(font_);
219         // Note that both setFlags and the enums are undocumented
220         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
221         QTextOption to;
222         to.setWrapMode(force ? QTextOption::WrapAnywhere : QTextOption::WordWrap);
223         tl.setTextOption(to);
224         tl.beginLayout();
225         QTextLine line = tl.createLine();
226         line.setLineWidth(x);
227         tl.createLine();
228         tl.endLayout();
229         if (int(line.naturalTextWidth()) > x)
230                 return false;
231         x = int(line.naturalTextWidth());
232         s = s.substr(0, line.textLength());
233         return true;
234 }
235
236
237 void GuiFontMetrics::rectText(docstring const & str,
238         int & w, int & ascent, int & descent) const
239 {
240         static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
241
242         w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
243         ascent = metrics_.ascent() + d;
244         descent = metrics_.descent() + d;
245 }
246
247
248
249 void GuiFontMetrics::buttonText(docstring const & str,
250         int & w, int & ascent, int & descent) const
251 {
252         rectText(str, w, ascent, descent);
253         w += Inset::TEXT_TO_INSET_OFFSET;
254 }
255
256
257 Dimension const GuiFontMetrics::defaultDimension() const
258 {
259         return Dimension(0, maxAscent(), maxDescent());
260 }
261
262
263 Dimension const GuiFontMetrics::dimension(char_type c) const
264 {
265         return Dimension(width(c), ascent(c), descent(c));
266 }
267
268
269 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
270                 char_type c) const
271 {
272         QRect r;
273         if (is_utf16(c))
274                 r = metrics_.boundingRect(ucs4_to_qchar(c));
275         else
276                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
277
278         AscendDescend ad = { -r.top(), r.bottom() + 1};
279         // We could as well compute the width but this is not really
280         // needed for now as it is done directly in width() below.
281         metrics_cache_.insert(c, ad);
282
283         return ad;
284 }
285
286
287 int GuiFontMetrics::width(char_type c) const
288 {
289         int value = width_cache_.value(c, outOfLimitMetric);
290         if (value != outOfLimitMetric)
291                 return value;
292
293         if (is_utf16(c))
294                 value = metrics_.width(ucs4_to_qchar(c));
295         else
296                 value = metrics_.width(toqstr(docstring(1, c)));
297
298         width_cache_.insert(c, value);
299
300         return value;
301 }
302
303
304 int GuiFontMetrics::ascent(char_type c) const
305 {
306         static AscendDescend const outOfLimitAD =
307                 {outOfLimitMetric, outOfLimitMetric};
308         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
309         if (value.ascent != outOfLimitMetric)
310                 return value.ascent;
311
312         value = fillMetricsCache(c);
313         return value.ascent;
314 }
315
316
317 int GuiFontMetrics::descent(char_type c) const
318 {
319         static AscendDescend const outOfLimitAD =
320                 {outOfLimitMetric, outOfLimitMetric};
321         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
322         if (value.descent != outOfLimitMetric)
323                 return value.descent;
324
325         value = fillMetricsCache(c);
326         return value.descent;
327 }
328
329 } // namespace frontend
330 } // namespace lyx