]> git.lyx.org Git - lyx.git/blobdiff - src/frontends/qt4/GuiFontMetrics.cpp
Use <cstdint> instead of <boost/cstdint.hpp>
[lyx.git] / src / frontends / qt4 / GuiFontMetrics.cpp
index 2f598f43dc7ec73d5d257fdb1b2401f949ab92ed..10ca292cb63ef948022bf34ccbd6f1ecbfafb3ec 100644 (file)
 #include "qt_helpers.h"
 
 #include "Dimension.h"
-#include "Language.h"
-#include "LyXRC.h"
-
-#include "insets/Inset.h"
 
 #include "support/convert.h"
 #include "support/lassert.h"
+#include "support/lyxlib.h"
 
 #define DISABLE_PMPROF
 #include "support/pmprof.h"
 
-#ifdef CACHE_SOME_METRICS
 #include <QByteArray>
-#endif
 
 using namespace std;
 using namespace lyx::support;
 
-#ifdef CACHE_SOME_METRICS
 namespace std {
 
 /*
@@ -48,12 +42,30 @@ uint qHash(lyx::docstring const & s)
                                s.size() * sizeof(lyx::docstring::value_type)));
 }
 
-}
-#endif
+} // namespace std
 
 namespace lyx {
 namespace frontend {
 
+
+/*
+ * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
+ * Limit qtextlayout_cache_ size to 500 elements (we do not know the
+ * size of the QTextLayout objects anyway).
+ * Note that all these numbers are arbitrary.
+ * Also, setting size to 0 is tantamount to disabling the cache.
+ */
+int cache_metrics_width_size = 1 << 19;
+int cache_metrics_breakat_size = 1 << 19;
+// Qt 5.x already has its own caching of QTextLayout objects
+// but it does not seem to work well on MacOS X.
+#if (QT_VERSION < 0x050000) || defined(Q_OS_MAC)
+int cache_metrics_qtextlayout_size = 500;
+#else
+int cache_metrics_qtextlayout_size = 0;
+#endif
+
+
 namespace {
 /**
  * Convert a UCS4 character into a QChar.
@@ -73,26 +85,14 @@ inline QChar const ucs4_to_qchar(char_type const ucs4)
        LATTEST(is_utf16(ucs4));
        return QChar(static_cast<unsigned short>(ucs4));
 }
-} // anon namespace
+} // namespace
 
 
-/*
- * Limit (strwidth|breakat)_cache_ size to 512kB of string data.
- * Limit qtextlayout_cache_ size to 500 elements (we do not know the
- * size of the QTextLayout objects anyway).
- * Note that all these numbers are arbitrary.
- */
 GuiFontMetrics::GuiFontMetrics(QFont const & font)
-       : font_(font), metrics_(font, 0)
-#ifdef CACHE_METRICS_WIDTH
-       , strwidth_cache_(1 << 19)
-#endif
-#ifdef CACHE_METRICS_BREAKAT
-       , breakat_cache_(1 << 19)
-#endif
-#ifdef CACHE_METRICS_QTEXTLAYOUT
-       ,  qtextlayout_cache_(500)
-#endif
+       : font_(font), metrics_(font, 0),
+         strwidth_cache_(cache_metrics_width_size),
+         breakat_cache_(cache_metrics_breakat_size),
+         qtextlayout_cache_(cache_metrics_qtextlayout_size)
 {
 }
 
@@ -117,6 +117,13 @@ int GuiFontMetrics::em() const
 }
 
 
+int GuiFontMetrics::xHeight() const
+{
+//     LATTEST(metrics_.xHeight() == ascent('x'));
+       return metrics_.xHeight();
+}
+
+
 int GuiFontMetrics::lineWidth() const
 {
        return metrics_.lineWidth();
@@ -135,20 +142,29 @@ int GuiFontMetrics::strikeoutPos() const
 }
 
 
+namespace {
+int const outOfLimitMetric = -10000;
+}
+
+
 int GuiFontMetrics::lbearing(char_type c) const
 {
-       if (!is_utf16(c))
+       int value = lbearing_cache_.value(c, outOfLimitMetric);
+       if (value != outOfLimitMetric)
+               return value;
+
+       if (is_utf16(c))
+               value = metrics_.leftBearing(ucs4_to_qchar(c));
+       else {
                // FIXME: QFontMetrics::leftBearing does not support the
                //        full unicode range. Once it does, we could use:
-               //return metrics_.leftBearing(toqstr(docstring(1, c)));
-               return 0;
-
-       return metrics_.leftBearing(ucs4_to_qchar(c));
-}
+               // metrics_.leftBearing(toqstr(docstring(1, c)));
+               value = 0;
+       }
 
+       lbearing_cache_.insert(c, value);
 
-namespace {
-int const outOfLimitMetric = -10000;
+       return value;
 }
 
 
@@ -177,36 +193,44 @@ int GuiFontMetrics::rbearing(char_type c) const
 
 int GuiFontMetrics::width(docstring const & s) const
 {
-       PROFILE_THIS_BLOCK(width)
-#ifdef CACHE_METRICS_WIDTH
-       int * pw = strwidth_cache_[s];
-       if (pw)
-               return *pw;
-       PROFILE_CACHE_MISS(width)
-#endif
-       /* For some reason QMetrics::width returns a wrong value with Qt5
-        * with some arabic text. OTOH, QTextLayout is broken for single
-        * characters with null width (like \not in mathed).
+       PROFILE_THIS_BLOCK(width);
+       if (strwidth_cache_.contains(s))
+               return strwidth_cache_[s];
+       PROFILE_CACHE_MISS(width);
+       /* Several problems have to be taken into account:
+        * * QFontMetrics::width does not returns a wrong value with Qt5 with
+        *   some arabic text, since the glyph-shaping operations are not
+        *   done (documented in Qt5).
+        * * QTextLayout is broken for single characters with null width
+        *   (like \not in mathed).
+        * * While QTextLine::horizontalAdvance is the right thing to use
+     *   for text strings, it does not give a good result with some
+     *   characters like the \int (gyph 4) of esint.
+
+        * Also, as a safety measure, always use QFontMetrics::width with
+        * our math fonts.
        */
        int w = 0;
-       if (s.length() == 1
+       // is the string a single character from a math font ?
 #if QT_VERSION >= 0x040800
-           || font_.styleName() == "LyX"
+       bool const math_char = s.length() == 1 || font_.styleName() == "LyX";
+#else
+       bool const math_char = s.length() == 1;
 #endif
-           )
-               w = metrics_.width(toqstr(s));
-       else {
+       // keep value 0 for math chars with width 0
+       if (!math_char || metrics_.width(toqstr(s)) != 0) {
                QTextLayout tl;
                tl.setText(toqstr(s));
                tl.setFont(font_);
                tl.beginLayout();
                QTextLine line = tl.createLine();
                tl.endLayout();
-               w = int(line.naturalTextWidth());
+               if (math_char)
+                       w = iround(line.naturalTextWidth());
+               else
+                       w = iround(line.horizontalAdvance());
        }
-#ifdef CACHE_METRICS_WIDTH
-       strwidth_cache_.insert(s, new int(w), s.size() * sizeof(char_type));
-#endif
+       strwidth_cache_.insert(s, w, s.size() * sizeof(char_type));
        return w;
 }
 
@@ -229,48 +253,60 @@ int GuiFontMetrics::signedWidth(docstring const & s) const
 }
 
 
-QTextLayout const *
+shared_ptr<QTextLayout const>
 GuiFontMetrics::getTextLayout(docstring const & s, bool const rtl,
                               double const wordspacing) const
 {
-       PROFILE_THIS_BLOCK(getTextLayout)
-       QTextLayout * ptl;
-#ifdef CACHE_METRICS_QTEXTLAYOUT
-       docstring const s_cache = s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
-       ptl = qtextlayout_cache_[s_cache];
-       if (!ptl) {
-               PROFILE_CACHE_MISS(getTextLayout)
-#endif
-               ptl = new QTextLayout();
-               ptl->setCacheEnabled(true);
-               ptl->setText(toqstr(s));
-               QFont copy = font_;
-               copy.setWordSpacing(wordspacing);
-               ptl->setFont(copy);
-               // Note that both setFlags and the enums are undocumented
-               ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
-               ptl->beginLayout();
-               ptl->createLine();
-               ptl->endLayout();
-#ifdef CACHE_METRICS_QTEXTLAYOUT
-               qtextlayout_cache_.insert(s_cache, ptl);
-       }
+       PROFILE_THIS_BLOCK(getTextLayout);
+       docstring const s_cache =
+               s + (rtl ? "r" : "l") + convert<docstring>(wordspacing);
+       if (auto ptl = qtextlayout_cache_[s_cache])
+               return ptl;
+       PROFILE_CACHE_MISS(getTextLayout);
+       auto const ptl = make_shared<QTextLayout>();
+       ptl->setCacheEnabled(true);
+       QFont copy = font_;
+       copy.setWordSpacing(wordspacing);
+       ptl->setFont(copy);
+#if 1
+       /* Use unicode override characters to enforce drawing direction
+        * Source: http://www.iamcal.com/understanding-bidirectional-text/
+        */
+       if (rtl)
+               // Right-to-left override: forces to draw text right-to-left
+               ptl->setText(QChar(0x202E) + toqstr(s));
+       else
+               // Left-to-right override: forces to draw text left-to-right
+               ptl->setText(QChar(0x202D) + toqstr(s));
+#define TEXTLAYOUT_OFFSET 1
+#else
+       // FIXME: This does not work with Qt 5.11 (ticket #11284).
+       // Note that both setFlags and the enums are undocumented
+       ptl->setFlags(rtl ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight);
+       ptl->setText(toqstr(s));
+#define TEXTLAYOUT_OFFSET 0
 #endif
+       ptl->beginLayout();
+       ptl->createLine();
+       ptl->endLayout();
+       qtextlayout_cache_.insert(s_cache, ptl);
        return ptl;
 }
 
 
-int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
+int GuiFontMetrics::pos2x(docstring const & s, int pos, bool const rtl,
                           double const wordspacing) const
 {
        if (pos <= 0)
-               return rtl ? width(s) : 0;
-       QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
+               pos = 0;
+       shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
        /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
         * not be the same when there are high-plan unicode characters
         * (bug #10443).
         */
-       int const qpos = toqstr(s.substr(0, pos)).length();
+       // TEXTLAYOUT_OFFSET accounts for a possible direction override
+       // character in front of the string.
+       int const qpos = toqstr(s.substr(0, pos)).length() + TEXTLAYOUT_OFFSET;
        return static_cast<int>(tl->lineForTextPosition(qpos).cursorToX(qpos));
 }
 
@@ -278,16 +314,43 @@ int GuiFontMetrics::pos2x(docstring const & s, int const pos, bool const rtl,
 int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
                           double const wordspacing) const
 {
-       QTextLayout const * tl = getTextLayout(s, rtl, wordspacing);
-       int const qpos = tl->lineForTextPosition(0).xToCursor(x);
+       shared_ptr<QTextLayout const> tl = getTextLayout(s, rtl, wordspacing);
+       QTextLine const & tline = tl->lineForTextPosition(0);
+       int qpos = tline.xToCursor(x);
+       int newx = static_cast<int>(tline.cursorToX(qpos));
+       // The value of qpos may be wrong in rtl text (see ticket #10569).
+       // To work around this, let's have a look at adjacent positions to
+       // see whether we find closer matches.
+       if (rtl && newx < x) {
+               while (qpos > 0) {
+                       int const xm = static_cast<int>(tline.cursorToX(qpos - 1));
+                       if (abs(xm - x) < abs(newx - x)) {
+                               --qpos;
+                               newx = xm;
+                       } else
+                               break;
+               }
+       } else if (rtl && newx > x) {
+               while (qpos < tline.textLength()) {
+                       int const xp = static_cast<int>(tline.cursorToX(qpos + 1));
+                       if (abs(xp - x) < abs(newx - x)) {
+                               ++qpos;
+                               newx = xp;
+                       } else
+                               break;
+               }
+       }
        // correct x value to the actual cursor position.
-       x = static_cast<int>(tl->lineForTextPosition(0).cursorToX(qpos));
+       x = newx;
+
        /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
         * not be the same when there are high-plan unicode characters
         * (bug #10443).
         */
 #if QT_VERSION < 0x040801 || QT_VERSION >= 0x050100
-       return qstring_to_ucs4(tl->text().left(qpos)).length();
+       int pos = qstring_to_ucs4(tl->text().left(qpos)).length();
+       // there may be a direction override character in front of the string.
+       return max(pos - TEXTLAYOUT_OFFSET, 0);
 #else
        /* Due to QTBUG-25536 in 4.8.1 <= Qt < 5.1.0, the string returned
         * by QString::toUcs4 (used by qstring_to_ucs4) may have wrong
@@ -297,6 +360,8 @@ int GuiFontMetrics::x2pos(docstring const & s, int & x, bool const rtl,
         * worthwhile to implement a dichotomy search if this shows up
         * under a profiler.
         */
+       // there may be a direction override character in front of the string.
+       qpos = max(qpos - TEXTLAYOUT_OFFSET, 0);
        int pos = min(qpos, static_cast<int>(s.length()));
        while (pos >= 0 && toqstr(s.substr(0, pos)).length() != qpos)
                --pos;
@@ -327,7 +392,7 @@ int GuiFontMetrics::countExpanders(docstring const & str) const
 }
 
 
-pair<int, int> *
+pair<int, int>
 GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
                                bool const rtl, bool const force) const
 {
@@ -371,8 +436,9 @@ GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
        line.setLineWidth(x);
        tl.createLine();
        tl.endLayout();
-       if ((force && line.textLength() == offset) || int(line.naturalTextWidth()) > x)
-               return new pair<int, int>(-1, -1);
+       int const line_wid = iround(line.horizontalAdvance());
+       if ((force && line.textLength() == offset) || line_wid > x)
+               return {-1, -1};
        /* Since QString is UTF-16 and docstring is UCS-4, the offsets may
         * not be the same when there are high-plan unicode characters
         * (bug #10443).
@@ -396,36 +462,31 @@ GuiFontMetrics::breakAt_helper(docstring const & s, int const x,
                --len;
        LASSERT(len > 0 || qlen == 0, /**/);
 #endif
-       // The -1 is here to account for the leading zerow_nbsp.
-       return new pair<int, int>(len, int(line.naturalTextWidth()));
+       return {len, line_wid};
 }
 
 
 bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const force) const
 {
-       PROFILE_THIS_BLOCK(breakAt)
+       PROFILE_THIS_BLOCK(breakAt);
        if (s.empty())
                return false;
-       pair<int, int> * pp;
-#ifdef CACHE_METRICS_BREAKAT
-       docstring const s_cache = s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
 
-       pp = breakat_cache_[s_cache];
-       if (!pp) {
-               PROFILE_CACHE_MISS(breakAt)
-#endif
+       docstring const s_cache =
+               s + convert<docstring>(x) + (rtl ? "r" : "l") + (force ? "f" : "w");
+       pair<int, int> pp;
+
+       if (breakat_cache_.contains(s_cache))
+               pp = breakat_cache_[s_cache];
+       else {
+               PROFILE_CACHE_MISS(breakAt);
                pp = breakAt_helper(s, x, rtl, force);
-#ifdef CACHE_METRICS_BREAKAT
                breakat_cache_.insert(s_cache, pp, s_cache.size() * sizeof(char_type));
        }
-#endif
-       if (pp->first == -1)
+       if (pp.first == -1)
                return false;
-       s = s.substr(0, pp->first);
-       x = pp->second;
-#ifndef CACHE_METRICS_BREAKAT
-       delete pp;
-#endif
+       s = s.substr(0, pp.first);
+       x = pp.second;
        return true;
 }
 
@@ -433,19 +494,20 @@ bool GuiFontMetrics::breakAt(docstring & s, int & x, bool const rtl, bool const
 void GuiFontMetrics::rectText(docstring const & str,
        int & w, int & ascent, int & descent) const
 {
-       static int const d = Inset::TEXT_TO_INSET_OFFSET / 2;
+       // FIXME: let offset depend on font (this is Inset::TEXT_TO_OFFSET)
+       int const offset = 4;
 
-       w = width(str) + Inset::TEXT_TO_INSET_OFFSET;
-       ascent = metrics_.ascent() + d;
-       descent = metrics_.descent() + d;
+       w = width(str) + offset;
+       ascent = metrics_.ascent() + offset / 2;
+       descent = metrics_.descent() + offset / 2;
 }
 
 
-void GuiFontMetrics::buttonText(docstring const & str,
+void GuiFontMetrics::buttonText(docstring const & str, const int offset,
        int & w, int & ascent, int & descent) const
 {
        rectText(str, w, ascent, descent);
-       w += Inset::TEXT_TO_INSET_OFFSET;
+       w += offset;
 }