]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiFontMetrics.cpp
Few string fixes from Dan.
[lyx.git] / src / frontends / qt / 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
20 #include "support/convert.h"
21 #include "support/debug.h"
22 #include "support/lassert.h"
23 #include "support/lyxlib.h"
24 #include "support/textutils.h"
25
26 #define DISABLE_PMPROF
27 #include "support/pmprof.h"
28
29 #include <QByteArray>
30 #include <QRawFont>
31 #include <QtEndian>
32
33 #include <QtMath>
34
35 using namespace std;
36 using namespace lyx::support;
37
38 /* Define what mechanisms are used to enforce text direction. There
39  * are two methods that work with different Qt versions. Here we try
40  * to use both methods together.
41  */
42 // Define to use unicode override characters to force direction
43 #define BIDI_USE_OVERRIDE
44 // Define to use QTextLayout flag to force direction
45 #define BIDI_USE_FLAG
46
47 #if !defined(BIDI_USE_OVERRIDE) && !defined(BIDI_USE_FLAG)
48 #  error "Define at least one of BIDI_USE_OVERRIDE or BIDI_USE_FLAG"
49 #endif
50
51
52 namespace std {
53
54 /*
55  * Argument-dependent lookup implies that this function shall be
56  * declared in the namespace of its argument. But this is std
57  * namespace, since lyx::docstring is just std::basic_string<wchar_t>.
58  */
59 uint qHash(lyx::docstring const & s)
60 {
61         return qHash(QByteArray(reinterpret_cast<char const *>(s.data()),
62                                 s.size() * sizeof(lyx::docstring::value_type)));
63 }
64
65 } // namespace std
66
67 namespace lyx {
68 namespace frontend {
69
70
71 namespace {
72 // Maximal size/cost for various caches. See QCache documentation to
73 // see what cost means.
74
75 // Limit strwidth_cache_ total cost to 1MB of string data.
76 int const strwidth_cache_max_cost = 1024 * 1024;
77 // Limit breakstr_cache_ total cost to 10MB of string data.
78 // This is useful for documents with very large insets.
79 int const breakstr_cache_max_cost = 10 * 1024 * 1024;
80 // Qt 5.x already has its own caching of QTextLayout objects
81 // but it does not seem to work well on MacOS X.
82 #if defined(Q_OS_MAC)
83 // For some reason, the built-in cache of QTextLayout does not work or
84 // exist on macOS.
85 // Limit qtextlayout_cache_ size to 500 elements (we do not know the
86 // size of the QTextLayout objects anyway).
87 int const qtextlayout_cache_max_size = 500;
88 #else
89 // Disable the cache
90 int const qtextlayout_cache_max_size = 0;
91 #endif
92
93
94 /**
95  * Convert a UCS4 character into a QChar.
96  * This is a hack (it does only make sense for the common part of the UCS4
97  * and UTF16 encodings) and should not be used.
98  * This does only exist because of performance reasons (a real conversion
99  * using iconv is too slow on windows).
100  *
101  * This is no real conversion but a simple cast in reality. This is the reason
102  * why this works well for symbol fonts used in mathed too, even though
103  * these are not real ucs4 characters. These are codepoints in the
104  * computer modern fonts used, nothing unicode related.
105  * See comment in GuiPainter::text() for more explanation.
106  **/
107 inline QChar const ucs4_to_qchar(char_type const ucs4)
108 {
109         LATTEST(is_utf16(ucs4));
110         return QChar(static_cast<unsigned short>(ucs4));
111 }
112 } // namespace
113
114
115 GuiFontMetrics::GuiFontMetrics(QFont const & font)
116         : font_(font), metrics_(font, 0), xheight_(metrics_.xHeight()),
117           strwidth_cache_(strwidth_cache_max_cost),
118           breakstr_cache_(breakstr_cache_max_cost),
119           qtextlayout_cache_(qtextlayout_cache_max_size)
120 {
121         // Determine italic slope
122         double const defaultSlope = tan(qDegreesToRadians(19.0));
123         QRawFont raw = QRawFont::fromFont(font);
124         QByteArray post(raw.fontTable("post"));
125         if (post.length() == 0) {
126                 slope_ = defaultSlope;
127                 LYXERR(Debug::FONT, "Screen font doesn't have 'post' table.");
128         } else {
129                 // post table description:
130                 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
131                 int32_t italicAngle = qFromBigEndian(*reinterpret_cast<int32_t *>(post.data() + 4));
132                 double angle = italicAngle / 65536.0; // Fixed-point 16.16 to floating-point
133                 slope_ = -tan(qDegreesToRadians(angle));
134                 // Correct italic fonts with zero slope
135                 if (slope_ == 0.0 && font.italic())
136                         slope_ = defaultSlope;
137                 LYXERR(Debug::FONT, "Italic slope: " << slope_);
138         }
139 }
140
141
142 int GuiFontMetrics::maxAscent() const
143 {
144         return metrics_.ascent();
145 }
146
147
148 int GuiFontMetrics::maxDescent() const
149 {
150         // We add 1 as the value returned by QT is different than X
151         // See http://doc.trolltech.com/2.3/qfontmetrics.html#200b74
152         // FIXME: check this
153         return metrics_.descent() + 1;
154 }
155
156
157 int GuiFontMetrics::em() const
158 {
159         return QFontInfo(font_).pixelSize();
160 }
161
162
163 int GuiFontMetrics::xHeight() const
164 {
165 //      LATTEST(metrics_.xHeight() == ascent('x'));
166         return xheight_;
167 }
168
169
170 int GuiFontMetrics::lineWidth() const
171 {
172         return metrics_.lineWidth();
173 }
174
175
176 int GuiFontMetrics::underlinePos() const
177 {
178         return metrics_.underlinePos();
179 }
180
181
182 int GuiFontMetrics::strikeoutPos() const
183 {
184         return metrics_.strikeOutPos();
185 }
186
187
188 bool GuiFontMetrics::italic() const
189 {
190         return font_.italic();
191 }
192
193
194 double GuiFontMetrics::italicSlope() const
195 {
196         return slope_;
197 }
198
199
200 namespace {
201 int const outOfLimitMetric = -10000;
202 }
203
204
205 int GuiFontMetrics::lbearing(char_type c) const
206 {
207         int value = lbearing_cache_.value(c, outOfLimitMetric);
208         if (value != outOfLimitMetric)
209                 return value;
210
211         if (is_utf16(c))
212                 value = metrics_.leftBearing(ucs4_to_qchar(c));
213         else {
214                 // FIXME: QFontMetrics::leftBearing does not support the
215                 //        full unicode range. Once it does, we could use:
216                 // metrics_.leftBearing(toqstr(docstring(1, c)));
217                 value = 0;
218         }
219
220         lbearing_cache_.insert(c, value);
221
222         return value;
223 }
224
225
226 int GuiFontMetrics::rbearing(char_type c) const
227 {
228         int value = rbearing_cache_.value(c, outOfLimitMetric);
229         if (value != outOfLimitMetric)
230                 return value;
231
232         // Qt rbearing is from the right edge of the char's width().
233         if (is_utf16(c)) {
234                 QChar sc = ucs4_to_qchar(c);
235                 value = width(c) - metrics_.rightBearing(sc);
236         } else {
237                 // FIXME: QFontMetrics::leftBearing does not support the
238                 //        full unicode range. Once it does, we could use:
239                 // metrics_.rightBearing(toqstr(docstring(1, c)));
240                 value = width(c);
241         }
242
243         rbearing_cache_.insert(c, value);
244
245         return value;
246 }
247
248
249 int GuiFontMetrics::width(docstring const & s) const
250 {
251         PROFILE_THIS_BLOCK(width);
252         if (int * wid_p = strwidth_cache_.object_ptr(s))
253                 return *wid_p;
254         PROFILE_CACHE_MISS(width);
255         /* Several problems have to be taken into account:
256          * * QFontMetrics::width returns a wrong value with Qt5 with
257          *   some arabic text, since the glyph-shaping operations are not
258          *   done (documented in Qt5).
259          * * QTextLayout is broken for single characters with null width
260          *   (like \not in mathed).
261          * * While QTextLine::horizontalAdvance is the right thing to use
262      *   for text strings, it does not give a good result with some
263      *   characters like the \int (gyph 4) of esint.
264
265          * The metrics of some of our math fonts (eg. esint) are such that
266          * QTextLine::horizontalAdvance leads, more or less, in the middle
267          * of a symbol. This is the horizontal position where a subscript
268          * should be drawn, so that the superscript has to be moved rightward.
269          * This is done when the kerning() method of the math insets returns
270          * a positive value. The problem with this choice is that navigating
271          * a formula becomes weird. For example, a selection extends only over
272          * about half of the symbol. In order to avoid this, with our math
273          * fonts we use QTextLine::naturalTextWidth, so that a superscript can
274          * be drawn right after the symbol, and move the subscript leftward by
275          * recording a negative value for the kerning.
276         */
277         int w = 0;
278         // is the string a single character from a math font ?
279         bool const math_char = s.length() == 1 && font_.styleName() == "LyX";
280         if (math_char) {
281                 QString const qs = toqstr(s);
282                 int br_width = metrics_.boundingRect(qs).width();
283 #if QT_VERSION >= 0x050b00
284                 int s_width = metrics_.horizontalAdvance(qs);
285 #else
286                 int s_width = metrics_.width(qs);
287 #endif
288                 // keep value 0 for math chars with width 0
289                 if (s_width != 0)
290                         w = max(br_width, s_width);
291         } else {
292                 QTextLayout tl;
293                 tl.setText(toqstr(s));
294                 tl.setFont(font_);
295                 tl.beginLayout();
296                 QTextLine line = tl.createLine();
297                 tl.endLayout();
298                 w = iround(line.horizontalAdvance());
299         }
300         strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
301         return w;
302 }
303
304
305 int GuiFontMetrics::width(QString const & ucs2) const
306 {
307         return width(qstring_to_ucs4(ucs2));
308 }
309
310
311 int GuiFontMetrics::signedWidth(docstring const & s) const
312 {
313         if (s.empty())
314                 return 0;
315
316         if (s[0] == '-')
317                 return -width(s.substr(1, s.size() - 1));
318         else
319                 return width(s);
320 }
321
322
323 uint qHash(TextLayoutKey const & key)
324 {
325         double params = (2 * key.rtl - 1) * key.ws;
326         return std::qHash(key.s) ^ ::qHash(params);
327 }
328
329
330 // This holds a translation table between the original string and the
331 // QString that we can use with QTextLayout.
332 struct TextLayoutHelper
333 {
334         /// Create the helper
335         /// \c s is the original string
336         /// \c isrtl is true if the string is right-to-left
337         TextLayoutHelper(docstring const & s, bool isrtl);
338
339         /// translate QString index to docstring index
340         docstring::size_type qpos2pos(int qpos) const
341         {
342                 return lower_bound(pos2qpos_.begin(), pos2qpos_.end(), qpos) - pos2qpos_.begin();
343         }
344
345         /// Translate docstring index to QString index
346         int pos2qpos(docstring::size_type pos) const { return pos2qpos_[pos]; }
347
348         // The original string
349         docstring docstr;
350         // The mirror string
351         QString qstr;
352         // is string right-to-left?
353         bool rtl;
354
355 private:
356         // This vector contains the QString pos for each string position
357         vector<int> pos2qpos_;
358 };
359
360
361 TextLayoutHelper::TextLayoutHelper(docstring const & s, bool isrtl)
362         : docstr(s), rtl(isrtl)
363 {
364         // Reserve memory for performance purpose
365         pos2qpos_.reserve(s.size());
366         qstr.reserve(2 * s.size());
367
368         /* Qt will not break at a leading or trailing space, and we need
369          * that sometimes, see http://www.lyx.org/trac/ticket/9921.
370          *
371          * To work around the problem, we enclose the string between
372          * word joiner characters so that the QTextLayout algorithm will
373          * agree to break the text at these extremal spaces.
374          */
375         // Unicode character WORD JOINER
376         QChar const word_joiner(0x2060);
377         qstr += word_joiner;
378
379 #ifdef BIDI_USE_OVERRIDE
380         /* Unicode override characters enforce drawing direction
381          * Source: http://www.iamcal.com/understanding-bidirectional-text/
382          * Left-to-right override is 0x202d and right-to-left override is 0x202e.
383          */
384         qstr += QChar(rtl ? 0x202e : 0x202d);
385 #endif
386
387         // Now translate the string character-by-character.
388         bool was_space = false;
389         for (char_type const c : s) {
390                 // insert a word joiner character between consecutive spaces
391                 bool const is_space = isSpace(c);
392                 if (is_space && was_space)
393                         qstr += word_joiner;
394                 was_space = is_space;
395                 // Remember the QString index at this point
396                 pos2qpos_.push_back(qstr.size());
397                 // Performance: UTF-16 characters are easier
398                 if (is_utf16(c))
399                         qstr += ucs4_to_qchar(c);
400                 else
401                         qstr += toqstr(c);
402         }
403
404         // Final word joiner (see above)
405         qstr += word_joiner;
406
407         // Add virtual position at the end of the string
408         pos2qpos_.push_back(qstr.size());
409
410         //QString dump = qstr;
411         //LYXERR0("TLH: " << dump.replace(word_joiner, "|").toStdString());
412 }
413
414
415 namespace {
416
417 shared_ptr<QTextLayout>
418 getTextLayout_helper(TextLayoutHelper const & tlh, double const wordspacing,
419                      QFont font)
420 {
421         auto const ptl = make_shared<QTextLayout>();
422         ptl->setCacheEnabled(true);
423         font.setWordSpacing(wordspacing);
424         ptl->setFont(font);
425 #ifdef BIDI_USE_FLAG
426         /* Use undocumented flag to enforce drawing direction
427          * FIXME: This does not work with Qt 5.11 (ticket #11284).
428          */
429         ptl->setFlags(tlh.rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
430 #endif
431         ptl->setText(tlh.qstr);
432
433         ptl->beginLayout();
434         ptl->createLine();
435         ptl->endLayout();
436
437         return ptl;
438 }
439
440 }
441
442 shared_ptr<QTextLayout const>
443 GuiFontMetrics::getTextLayout(TextLayoutHelper const & tlh,
444                               double const wordspacing) const
445 {
446         PROFILE_THIS_BLOCK(getTextLayout_TLH);
447         TextLayoutKey key{tlh.docstr, tlh.rtl, wordspacing};
448         if (auto ptl = qtextlayout_cache_[key])
449                 return ptl;
450         PROFILE_CACHE_MISS(getTextLayout_TLH);
451         auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
452         qtextlayout_cache_.insert(key, ptl);
453         return ptl;
454 }
455
456
457 shared_ptr<QTextLayout const>
458 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
459                               double const wordspacing) const
460 {
461         PROFILE_THIS_BLOCK(getTextLayout);
462         TextLayoutKey key{s, rtl, wordspacing};
463         if (auto ptl = qtextlayout_cache_[key])
464                 return ptl;
465         PROFILE_CACHE_MISS(getTextLayout);
466         TextLayoutHelper tlh(s, rtl);
467         auto const ptl = getTextLayout_helper(tlh, wordspacing, font_);
468         qtextlayout_cache_.insert(key, ptl);
469         return ptl;
470 }
471
472
473 int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
474                           double const wordspacing) const
475 {
476         TextLayoutHelper tlh(s, rtl);
477         auto ptl = getTextLayout(tlh, wordspacing);
478         // pos can be negative, see #10506.
479         int const qpos = tlh.pos2qpos(max(pos, 0));
480         return static_cast<int>(ptl->lineForTextPosition(qpos).cursorToX(qpos));
481 }
482
483
484 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
485                           double const wordspacing) const
486 {
487         TextLayoutHelper tlh(s, rtl);
488         auto ptl = getTextLayout(tlh, wordspacing);
489         QTextLine const & tline = ptl->lineForTextPosition(0);
490         int qpos = tline.xToCursor(x);
491         int newx = static_cast<int>(tline.cursorToX(qpos));
492         // The value of qpos may be wrong in rtl text (see ticket #10569).
493         // To work around this, let's have a look at adjacent positions to
494         // see whether we find closer matches.
495         if (rtl && newx < x) {
496                 while (qpos > 0) {
497                         int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
498                         if (abs(xm - x) < abs(newx - x)) {
499                                 --qpos;
500                                 newx = xm;
501                         } else
502                                 break;
503                 }
504         } else if (rtl && newx > x) {
505                 while (qpos < tline.textLength()) {
506                         int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
507                         if (abs(xp - x) < abs(newx - x)) {
508                                 ++qpos;
509                                 newx = xp;
510                         } else
511                                 break;
512                 }
513         }
514         // correct x value to the actual cursor position.
515         x = newx;
516
517         return tlh.qpos2pos(qpos);
518 }
519
520
521 FontMetrics::Breaks
522 GuiFontMetrics::breakString_helper(docstring const & s, int first_wid, int wid,
523                                    bool rtl, bool force) const
524 {
525         TextLayoutHelper const tlh(s, rtl);
526
527         QTextLayout tl;
528 #ifdef BIDI_USE_FLAG
529         /* Use undocumented flag to enforce drawing direction
530          * FIXME: This does not work with Qt 5.11 (ticket #11284).
531          */
532         tl.setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
533 #endif
534         tl.setText(tlh.qstr);
535         tl.setFont(font_);
536         QTextOption to;
537         /*
538          * Some Asian languages split lines anywhere (no notion of
539          * word). It seems that QTextLayout is not aware of this fact.
540          * See for reference:
541          *    https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
542          *
543          * FIXME: Something shall be done about characters which are
544          * not allowed at the beginning or end of line.
545          */
546         to.setWrapMode(force ? QTextOption::WrapAtWordBoundaryOrAnywhere
547                              : QTextOption::WordWrap);
548         tl.setTextOption(to);
549
550         bool first = true;
551         tl.beginLayout();
552         while(true) {
553                 QTextLine line = tl.createLine();
554                 if (!line.isValid())
555                         break;
556                 line.setLineWidth(first ? first_wid : wid);
557                 first = false;
558         }
559         tl.endLayout();
560
561         Breaks breaks;
562         int pos = 0;
563         for (int i = 0 ; i < tl.lineCount() ; ++i) {
564                 QTextLine const & line = tl.lineAt(i);
565                 int const line_epos = line.textStart() + line.textLength();
566                 int const epos = tlh.qpos2pos(line_epos);
567                 // This does not take trailing spaces into account, except for the last line.
568                 int const wid = iround(line.naturalTextWidth());
569                 // If the line is not the last one, trailing space is always omitted.
570                 int nspc_wid = wid;
571                 // For the last line, compute the width without trailing space
572                 if (i + 1 == tl.lineCount() && !s.empty() && isSpace(s.back())
573                     && line.textStart() <= tlh.pos2qpos(s.size() - 1))
574                         nspc_wid = iround(line.cursorToX(tlh.pos2qpos(s.size() - 1)));
575                 breaks.emplace_back(epos - pos, wid, nspc_wid);
576                 pos = epos;
577         }
578
579         return breaks;
580 }
581
582
583 uint qHash(BreakStringKey const & key)
584 {
585         // assume widths are less than 10000. This fits in 32 bits.
586         uint params = key.force + 2 * key.rtl + 4 * key.first_wid + 10000 * key.wid;
587         return std::qHash(key.s) ^ ::qHash(params);
588 }
589
590
591 FontMetrics::Breaks GuiFontMetrics::breakString(docstring const & s, int first_wid, int wid,
592                                                 bool rtl, bool force) const
593 {
594         PROFILE_THIS_BLOCK(breakString);
595         if (s.empty())
596                 return Breaks();
597
598         BreakStringKey key{s, first_wid, wid, rtl, force};
599         Breaks brks;
600         if (auto * brks_ptr = breakstr_cache_.object_ptr(key))
601                 brks = *brks_ptr;
602         else {
603                 PROFILE_CACHE_MISS(breakString);
604                 brks = breakString_helper(s, first_wid, wid, rtl, force);
605                 breakstr_cache_.insert(key, brks, sizeof(key) + s.size() * sizeof(char_type));
606         }
607         return brks;
608 }
609
610
611 void GuiFontMetrics::rectText(docstring const & str,
612         int & w, int & ascent, int & descent) const
613 {
614         // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
615         int const offset = 4;
616
617         w = width(str) + offset;
618         ascent = metrics_.ascent() + offset / 2;
619         descent = metrics_.descent() + offset / 2;
620 }
621
622
623 void GuiFontMetrics::buttonText(docstring const & str, const int offset,
624         int & w, int & ascent, int & descent) const
625 {
626         rectText(str, w, ascent, descent);
627         w += offset;
628 }
629
630
631 Dimension const GuiFontMetrics::defaultDimension() const
632 {
633         return Dimension(0, maxAscent(), maxDescent());
634 }
635
636
637 Dimension const GuiFontMetrics::dimension(char_type c) const
638 {
639         return Dimension(width(c), ascent(c), descent(c));
640 }
641
642
643 GuiFontMetrics::AscendDescend const GuiFontMetrics::fillMetricsCache(
644                 char_type c) const
645 {
646         QRect r;
647         if (is_utf16(c))
648                 r = metrics_.boundingRect(ucs4_to_qchar(c));
649         else
650                 r = metrics_.boundingRect(toqstr(docstring(1, c)));
651
652         AscendDescend ad = { -r.top(), r.bottom() + 1};
653         // We could as well compute the width but this is not really
654         // needed for now as it is done directly in width() below.
655         metrics_cache_.insert(c, ad);
656
657         return ad;
658 }
659
660
661 int GuiFontMetrics::width(char_type c) const
662 {
663         int value = width_cache_.value(c, outOfLimitMetric);
664         if (value != outOfLimitMetric)
665                 return value;
666
667 #if QT_VERSION >= 0x050b00
668         if (is_utf16(c))
669                 value = metrics_.horizontalAdvance(ucs4_to_qchar(c));
670         else
671                 value = metrics_.horizontalAdvance(toqstr(docstring(1, c)));
672 #else
673         if (is_utf16(c))
674                 value = metrics_.width(ucs4_to_qchar(c));
675         else
676                 value = metrics_.width(toqstr(docstring(1, c)));
677 #endif
678
679         width_cache_.insert(c, value);
680
681         return value;
682 }
683
684
685 int GuiFontMetrics::ascent(char_type c) const
686 {
687         static AscendDescend const outOfLimitAD =
688                 {outOfLimitMetric, outOfLimitMetric};
689         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
690         if (value.ascent != outOfLimitMetric)
691                 return value.ascent;
692
693         value = fillMetricsCache(c);
694         return value.ascent;
695 }
696
697
698 int GuiFontMetrics::descent(char_type c) const
699 {
700         static AscendDescend const outOfLimitAD =
701                 {outOfLimitMetric, outOfLimitMetric};
702         AscendDescend value = metrics_cache_.value(c, outOfLimitAD);
703         if (value.descent != outOfLimitMetric)
704                 return value.descent;
705
706         value = fillMetricsCache(c);
707         return value.descent;
708 }
709
710 } // namespace frontend
711 } // namespace lyx