Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
Introduce KoSvgText::FontMetrics and use it where we need font metrics.
Wolthera van Hövell tot Westerflier6b8298b3873d
diff --git a/libs/flake/text/KoFontRegistry.cpp b/libs/flake/text/KoFontRegistry.cppindex 3a7d52d272..7dacf0f288 100644--- a/libs/flake/text/KoFontRegistry.cpp+++ b/libs/flake/text/KoFontRegistry.cpp@@ -63,6 +63,7 @@ private:QHash<QString, FcFontSetSP> m_fontSets;QHash<QString, FT_FaceSP> m_faces;QHash<QString, QVector<QPair<QString, int>>> m_suggestedFiles;+ QHash<QString, KoSvgText::FontMetrics> m_fontMetrics;ThreadData(FT_LibrarySP lib): m_library(std::move(lib))@@ -202,6 +203,12 @@ public:return m_data.localData()->m_suggestedFiles;}+ QHash<QString, KoSvgText::FontMetrics> &fontMetrics() {+ if (!m_data.hasLocalData())+ initialize();+ return m_data.localData()->m_fontMetrics;+ }+void debugConverter() {fontFamilyConverter->debugInfo();}@@ -230,15 +237,7 @@ KoFontRegistry *KoFontRegistry::instance()return s_instance;}-std::vector<FT_FaceSP> KoFontRegistry::facesForCSSValues(QVector<int> &lengths,- KoCSSFontInfo info,- const QString &text,- quint32 xRes,- quint32 yRes, bool disableFontMatching,- const QString &language)-{- // Generate a hash for the cache.- // Because FT_faces cannot be cloned, we need to include the sizes and font variation modifications.+QString modificationsString(KoCSSFontInfo info, quint32 xRes, quint32 yRes) {QString modifications;if (info.size > -1) {modifications += QString::number(info.size) + ":" + QString::number(xRes) + "x" + QString::number(yRes);@@ -263,6 +262,17 @@ std::vector<FT_FaceSP> KoFontRegistry::facesForCSSValues(QVector<int> &lengths,modifications += "|" + key + QString::number(info.axisSettings.value(key));}}+ return modifications;+}++std::vector<FT_FaceSP> KoFontRegistry::facesForCSSValues(QVector<int> &lengths,+ KoCSSFontInfo info,+ const QString &text,+ quint32 xRes,+ quint32 yRes, bool disableFontMatching,+ const QString &language)+{+ QString modifications = modificationsString(info, xRes, yRes);QVector<QPair<QString, int>> candidates;const QString suggestedHash = info.families.join("+") + ":" + modifications;@@ -724,6 +734,219 @@ QFont::Style KoFontRegistry::slantMode(FT_FaceSP face)}}+KoSvgText::FontMetrics KoFontRegistry::fontMetricsForCSSValues(KoCSSFontInfo info, const bool isHorizontal, const QString &text, quint32 xRes, quint32 yRes, bool disableFontMatching, const QString &language)+{+ const QString suggestedHash = info.families.join(",")+":"+modificationsString(info, xRes, yRes);+ KoSvgText::FontMetrics metrics;+ auto entry = d->fontMetrics().find(suggestedHash);+ if (entry != d->fontMetrics().end()) {+ metrics = entry.value();+ } else {+ QVector<int> lengths;+ const std::vector<FT_FaceSP> faces = KoFontRegistry::instance()->facesForCSSValues(+ lengths,+ info,+ text,+ xRes,+ yRes,+ disableFontMatching,+ language);+ metrics = KoFontRegistry::generateFontMetrics(faces.front(), isHorizontal);+ d->fontMetrics().insert(suggestedHash, metrics);+ }+ return metrics;+}++KoSvgText::FontMetrics KoFontRegistry::generateFontMetrics(FT_FaceSP face, bool isHorizontal)+{+ KoSvgText::FontMetrics metrics;+ hb_direction_t dir = isHorizontal? HB_DIRECTION_LTR: HB_DIRECTION_TTB;+ hb_script_t script = HB_SCRIPT_UNKNOWN;+ hb_font_t_sp font(hb_ft_font_create_referenced(face.data()));++ FT_Int32 faceLoadFlags = loadFlagsForFace(face.data(), isHorizontal);++ metrics.isVertical = !isHorizontal;+ // Fontsize and advances.+ metrics.fontSize = isHorizontal? face.data()->size->metrics.y_ppem: face.data()->size->metrics.x_ppem;++ if(!FT_Load_Glyph(face.data(), FT_Get_Char_Index(face.data(), ' '), faceLoadFlags)) {+ metrics.spaceAdvance = isHorizontal? face.data()->glyph->advance.x: face.data()->glyph->advance.y;+ } else {+ metrics.spaceAdvance = isHorizontal? metrics.fontSize/2: metrics.fontSize;+ }++ if(!FT_Load_Glyph(face.data(), FT_Get_Char_Index(face.data(), '0'), faceLoadFlags)) {+ metrics.zeroAdvance = isHorizontal? face.data()->glyph->advance.x: face.data()->glyph->advance.y;+ } else {+ metrics.zeroAdvance = isHorizontal? metrics.fontSize/2: metrics.fontSize;+ }++ if(!FT_Load_Glyph(face.data(), FT_Get_Char_Index(face.data(), 0x6C34), faceLoadFlags)) {+ metrics.ideographicAdvance = isHorizontal? face.data()->glyph->advance.x: face.data()->glyph->advance.y;+ } else {+ metrics.ideographicAdvance = metrics.fontSize;+ }++ const bool useFallback = hb_version_atleast(4, 0, 0);++ QVector<hb_ot_metrics_tag_t> metricTags ({+ HB_OT_METRICS_TAG_X_HEIGHT,+ HB_OT_METRICS_TAG_CAP_HEIGHT,+ HB_OT_METRICS_TAG_SUPERSCRIPT_EM_X_OFFSET,+ HB_OT_METRICS_TAG_SUPERSCRIPT_EM_Y_OFFSET,+ HB_OT_METRICS_TAG_SUBSCRIPT_EM_X_OFFSET,+ HB_OT_METRICS_TAG_SUBSCRIPT_EM_Y_OFFSET+ });++ // metrics+ for (auto it = metricTags.begin(); it!= metricTags.end(); it++) {+ char c[4];+ hb_tag_to_string(*it, c);+ QLatin1String tagName(c);+ hb_position_t origin = 0;+ if (useFallback) {+ hb_ot_metrics_get_position_with_fallback(font.data(), *it, &origin);+ } else {+ hb_ot_metrics_get_position(font.data(), *it, &origin);+ }+ metrics.setMetricsValueByTag(tagName, origin);+ }++ // Baselines.++ const QVector<hb_ot_layout_baseline_tag_t> baselines ({+ HB_OT_LAYOUT_BASELINE_TAG_ROMAN,+ HB_OT_LAYOUT_BASELINE_TAG_HANGING,+ HB_OT_LAYOUT_BASELINE_TAG_IDEO_FACE_BOTTOM_OR_LEFT,+ HB_OT_LAYOUT_BASELINE_TAG_IDEO_FACE_TOP_OR_RIGHT,+ HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT,+ HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_TOP_OR_RIGHT,+ HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_CENTRAL,+ HB_OT_LAYOUT_BASELINE_TAG_MATH+ });+++ for (auto it = baselines.begin(); it!= baselines.end(); it++) {+ char c[4];+ hb_tag_to_string(*it, c);+ QLatin1String tagName(c);+ hb_position_t origin = 0;+ if (useFallback) {+ hb_ot_layout_get_baseline_with_fallback(font.data(), *it, dir, script, HB_TAG_NONE, &origin);+ } else {+ hb_ot_layout_get_baseline(font.data(), *it, dir, script, HB_TAG_NONE, &origin);+ }+ metrics.setBaselineValueByTag(tagName, origin);+ }++ // Ascender line gap, descender.++ hb_position_t ascender = 0;+ hb_position_t descender = 0;+ hb_position_t lineGap = 0;++ if (isHorizontal) {+ /**+ * There's 3 different definitions of the so-called vertical metrics, that is,+ * the ascender and descender for horizontally laid out script. WinAsc & Desc,+ * HHAE asc&desc, and OS/2... we need the last one, but harfbuzz doesn't return+ * it unless there's a flag set in the font, which is missing in a lot of fonts+ * that were from the transitional period, like Deja Vu Sans. Hence we need to get+ * the OS/2 table and calculate the values manually (and fall back in various ways).+ *+ * https://www.w3.org/TR/css-inline-3/#ascent-descent+ * https://www.w3.org/TR/CSS2/visudet.html#sTypoAscender+ * https://wiki.inkscape.org/wiki/Text_Rendering_Notes#Ascent_and_Descent+ *+ * Related HB issue: https://github.com/harfbuzz/harfbuzz/issues/1920+ */+ TT_OS2 *os2Table = nullptr;+ os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face.data(), FT_SFNT_OS2);+ if (os2Table) {+ int yscale = face.data()->size->metrics.y_scale;++ ascender = FT_MulFix(os2Table->sTypoAscender, yscale);+ descender = FT_MulFix(os2Table->sTypoDescender, yscale);+ lineGap = FT_MulFix(os2Table->sTypoLineGap, yscale);+ }++ constexpr unsigned USE_TYPO_METRICS = 1u << 7;+ if (!os2Table || os2Table->version == 0xFFFFU || !(os2Table->fsSelection & USE_TYPO_METRICS)) {+ hb_position_t altAscender = 0;+ hb_position_t altDescender = 0;+ hb_position_t altLineGap = 0;+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_ASCENDER, &altAscender)) {+ altAscender = face.data()->ascender;+ }+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_DESCENDER, &altDescender)) {+ altDescender = face.data()->descender;+ }+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_LINE_GAP, &altLineGap)) {+ altLineGap = face.data()->height - (altAscender-altDescender);+ }++ // Some fonts have sTypo metrics that are too small compared+ // to the HHEA values which make the default line height too+ // tight (e.g. Microsoft JhengHei, Source Han Sans), so we+ // compare them and take the ones that are larger.+ if (!os2Table || (altAscender - altDescender + altLineGap) > (ascender - descender + lineGap)) {+ ascender = altAscender;+ descender = altDescender;+ lineGap = altLineGap;+ }+ }+ } else {+ hb_font_extents_t fontExtends;+ hb_font_get_extents_for_direction (font.data(), HB_DIRECTION_TTB, &fontExtends);+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_ASCENDER, &ascender)) {+ ascender = fontExtends.ascender;+ }+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_DESCENDER, &descender)) {+ descender = fontExtends.descender;+ }+ if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_LINE_GAP, &lineGap)) {+ lineGap = 0;+ }+ // Default microsoft CJK fonts have the vertical ascent and descent be the same as the horizontal+ // ascent and descent, so we 'normalize' the ascender and descender to be half the total height.+ qreal height = ascender - fontExtends.descender;+ ascender = height*0.5;+ descender = -ascender;+ }+ if (ascender == 0 && descender == 0) {+ ascender = face->size->metrics.ascender;+ descender = face->size->metrics.descender;+ qreal height = ascender - descender;+ lineGap = face->size->metrics.height - height;+ if (!isHorizontal) {+ ascender = height * 0.5;+ descender = -ascender;+ }+ }+ metrics.ascender = ascender;+ metrics.descender = descender;+ metrics.lineGap = lineGap;++ return metrics;+}++int32_t KoFontRegistry::loadFlagsForFace(FT_Face face, bool isHorizontal, int32_t loadFlags)+{+ FT_Int32 faceLoadFlags = loadFlags;+ if (FT_HAS_COLOR(face)) {+ faceLoadFlags |= FT_LOAD_COLOR;+ }+ if (!isHorizontal && FT_HAS_VERTICAL(face)) {+ faceLoadFlags |= FT_LOAD_VERTICAL_LAYOUT;+ }+ if (!FT_IS_SCALABLE(face)) {+ // This is needed for the CBDT version of Noto Color Emoji+ faceLoadFlags &= ~FT_LOAD_NO_BITMAP;+ }+ return faceLoadFlags;+}+bool KoFontRegistry::addFontFilePathToRegistery(const QString &path){const QByteArray utfData = path.toUtf8();diff --git a/libs/flake/text/KoFontRegistry.h b/libs/flake/text/KoFontRegistry.hindex f467b4e223..61be80241f 100644--- a/libs/flake/text/KoFontRegistry.h+++ b/libs/flake/text/KoFontRegistry.h@@ -96,6 +96,18 @@ public:* @return the slant mode, can be normal, italic or oblique.*/static QFont::Style slantMode(FT_FaceSP face);++ KoSvgText::FontMetrics fontMetricsForCSSValues(KoCSSFontInfo info = KoCSSFontInfo(),+ const bool isHorizontal = true,+ const QString &text = "",+ quint32 xRes = 72,+ quint32 yRes = 72,+ bool disableFontMatching = false,+ const QString &language = QString());++ static KoSvgText::FontMetrics generateFontMetrics(FT_FaceSP face, bool isHorizontal = true);++ static int32_t loadFlagsForFace(FT_Face face, bool isHorizontal = true, int32_t loadFlags = 0);private Q_SLOTS:/*** Update the config and reset the FontChangeListener.diff --git a/libs/flake/text/KoSvgText.cpp b/libs/flake/text/KoSvgText.cppindex 50f1dc63d2..0da53834e3 100644--- a/libs/flake/text/KoSvgText.cpp+++ b/libs/flake/text/KoSvgText.cpp@@ -37,6 +37,7 @@ KIS_DECLARE_STATIC_INITIALIZER {qRegisterMetaType<KoSvgText::FontFeatureLigatures>("KoSvgText::FontFeatureLigatures");qRegisterMetaType<KoSvgText::FontFeatureNumeric>("KoSvgText::FontFeatureNumeric");qRegisterMetaType<KoSvgText::FontFeatureEastAsian>("KoSvgText::FontFeatureEastAsian");+ qRegisterMetaType<KoSvgText::FontMetrics>("KoSvgText::FontMetrics");#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))qRegisterMetaTypeStreamOperators<KoSvgText::FontFamilyAxis>("KoSvgText::FontFamilyAxis");@@ -91,6 +92,9 @@ KIS_DECLARE_STATIC_INITIALIZER {QMetaType::registerEqualsComparator<KoSvgText::FontFeatureEastAsian>();QMetaType::registerDebugStreamOperator<KoSvgText::FontFeatureEastAsian>();++ QMetaType::registerEqualsComparator<KoSvgText::FontMetrics>();+ QMetaType::registerDebugStreamOperator<KoSvgText::FontMetrics>();#endif}@@ -1348,4 +1352,85 @@ QStringList fontFeaturesCaps(const FontFeatureCaps &feature, const int start, coreturn list;}+void FontMetrics::setBaselineValueByTag(const QLatin1String &tag, int32_t value) {+ if (tag == "romn") {+ alphabeticBaseline = value;+ } else if (tag == "hang") {+ hangingBaseline = value;+ } else if (tag == "icfb") {+ ideographicFaceUnderBaseline = value;+ } else if (tag == "icft") {+ ideographicFaceOverBaseline = value;+ } else if (tag == "ideo") {+ ideographicUnderBaseline = value;+ } else if (tag == "idtp") {+ ideographicOverBaseline = value;+ } else if (tag == "Idce") {+ ideographicCenterBaseline = value;+ } else if (tag == "math") {+ mathematicalBaseline = value;+ }+}++void FontMetrics::setMetricsValueByTag(const QLatin1String &tag, int32_t value) {+ if (tag == "xhgt") {+ xHeight = value;+ } else if (tag == "cpht") {+ xHeight = value;+ } else if (tag == "sbxo") {+ subScriptOffset.first = value;+ } else if (tag == "sbyo") {+ subScriptOffset.second = value;+ } else if (tag == "spxo") {+ superScriptOffset.first = value;+ } else if (tag == "spyo") {+ superScriptOffset.second = value;+ }+}++void FontMetrics::scaleBaselines(const qreal multiplier)+{+ alphabeticBaseline *= multiplier;+ hangingBaseline *= multiplier;+ mathematicalBaseline *= multiplier;+ ideographicFaceUnderBaseline *= multiplier;+ ideographicFaceOverBaseline *= multiplier;+ ideographicOverBaseline *= multiplier;+ ideographicCenterBaseline *= multiplier;+ ideographicUnderBaseline *= multiplier;+}++QDebug operator<<(QDebug dbg, const FontMetrics &metrics)+{+ const double ftPixel = 1.0/64.0;+ dbg.nospace() << "FontMetrics(";+ dbg.nospace() << "Direction: " << (metrics.isVertical? "Top to bottom. ": "Left to right. ");+ dbg.nospace() << "FontSize: " << QString::number(metrics.fontSize*ftPixel) << "px. ";+ dbg.nospace() << "Number width: " << QString::number(metrics.zeroAdvance*ftPixel) << "px. ";+ dbg.nospace() << "Space width: " << QString::number(metrics.spaceAdvance*ftPixel) << "px. ";+ dbg.nospace() << "Ideographic width: " << QString::number(metrics.ideographicAdvance*ftPixel) << "px. ";++ dbg.nospace() << "xHeight: " << QString::number(metrics.xHeight*ftPixel) << "px. ";+ dbg.nospace() << "cap height: " << QString::number(metrics.capHeight*ftPixel) << "px. ";+ dbg.nospace() << "Subscripts: " << QString::number(metrics.subScriptOffset.second*ftPixel) << "px. ";+ dbg.nospace() << "Superscripts: " << QString::number(metrics.superScriptOffset.second*ftPixel) << "px. ";+ dbg.nospace() << "Ascender: " << QString::number(metrics.ascender*ftPixel) << "px. ";+ dbg.nospace() << "Descender: " << QString::number(metrics.descender*ftPixel) << "px. ";+ dbg.nospace() << "Linegap: " << QString::number(metrics.lineGap*ftPixel) << "px. ";++ dbg.nospace() << "Alphabetic: " << QString::number(metrics.alphabeticBaseline*ftPixel) << "px. ";+ dbg.nospace() << "Middle: " << QString::number((metrics.xHeight/2)*ftPixel) << "px. ";+ dbg.nospace() << "Mathematical: " << QString::number(metrics.mathematicalBaseline*ftPixel) << "px. ";++ dbg.nospace() << "Ideo Over: " << QString::number(metrics.ideographicOverBaseline*ftPixel) << "px. ";+ dbg.nospace() << "Central: " << QString::number(metrics.ideographicCenterBaseline*ftPixel) << "px. ";+ dbg.nospace() << "Ideo Under: " << QString::number(metrics.ideographicUnderBaseline*ftPixel) << "px. ";++ dbg.nospace() << "Ideo Face Over: " << QString::number(metrics.ideographicFaceOverBaseline*ftPixel) << "px. ";+ dbg.nospace() << "Ideo Face Under: " << QString::number(metrics.ideographicFaceUnderBaseline*ftPixel) << "px. ";+ dbg.nospace() << "Hanging: " << QString::number(metrics.hangingBaseline*ftPixel) << "px. ";+ dbg.nospace() << ")";+ return dbg.space();+}+} // namespace KoSvgTextdiff --git a/libs/flake/text/KoSvgText.h b/libs/flake/text/KoSvgText.hindex 8424d5a334..594f4ba5bb 100644--- a/libs/flake/text/KoSvgText.h+++ b/libs/flake/text/KoSvgText.h@@ -980,6 +980,94 @@ FontFeatureEastAsian parseFontFeatureEastAsian(const QString &value, FontFeatureQString writeFontFeatureEastAsian(const FontFeatureEastAsian &feature);QDebug KRITAFLAKE_EXPORT operator<<(QDebug dbg, const KoSvgText::FontFeatureEastAsian &feature);+/**+ * @brief The FontMetrics class+ * A class to keep track of a variety of font metrics.+ * Note that values are in Freetype pixels and coordinates! (that is 64 times bigger than a regular pixel, and Y is swapped.)+ */+struct FontMetrics : public boost::equality_comparable<FontMetrics> {+ bool isVertical = false; ///< Different fontMetrics count between vertical and horizontal.+ int32_t fontSize; ///< Currently set size, CSS unit 'em'+ int32_t zeroAdvance; ///< Advance of the character '0', CSS Unit 'ch', defaults to 0.5 em in horizontal and 1.0 em in vertical.+ int32_t spaceAdvance;///< Advance of the character ' ', used by tabs.+ int32_t ideographicAdvance; ///< Advance of the character '水' (U+6C34), CSS Unit ic, defaults to 1 em.++ int32_t xHeight; ///< height of X, defaults to 0.5 fontsize.+ int32_t capHeight; ///< Height of capital letters, defaults to ascender.+ QPair<int32_t, int32_t> subScriptOffset; ///< subscript baseline height, defaults to 1/5th em below alphabetic.+ QPair<int32_t, int32_t> superScriptOffset; ///< superscript baseline height, defaults to 2/3rd about alphabetic.++ int32_t ascender; ///< distance from origin to top.+ int32_t descender; ///< distance for origin to bottom.+ int32_t lineGap; ///< additional linegap between consequetive lines.++ int32_t alphabeticBaseline; ///< location of alphabetic baseline from origin.+ int32_t mathematicalBaseline; ///< location of mathematical baseline from origin.++ int32_t ideographicUnderBaseline; ///< location of ideographic under baseline from origin, may fall back to descender.+ int32_t ideographicCenterBaseline; ///< location of ideographic center baseline from origin,+ ///< default baseline for vertical, centered between over and under.+ int32_t ideographicOverBaseline; ///< location of ideographic over baseline from origin.++ int32_t ideographicFaceUnderBaseline; ///< location of ideographic face under baseline, that is, the bottom of the glyphs.+ int32_t ideographicFaceOverBaseline; ///< location of ideographic face over baseline, that is, the top of the glyphs.++ int32_t hangingBaseline; ///< location of the hanging baseline used in north brahmic scripts.++ bool operator==(const FontMetrics & other) const {+ return isVertical == other.isVertical+ && fontSize == other.fontSize+ && zeroAdvance == other.zeroAdvance+ && spaceAdvance == other.spaceAdvance+ && ideographicAdvance == other.ideographicAdvance+ && xHeight == other.xHeight+ && capHeight == other.capHeight+ && subScriptOffset == other.subScriptOffset+ && superScriptOffset == other.superScriptOffset+ && ascender == other.ascender+ && descender == other.descender+ && lineGap == other.lineGap+ && alphabeticBaseline == other.alphabeticBaseline+ && ideographicUnderBaseline == other.ideographicUnderBaseline+ && ideographicCenterBaseline == other.ideographicCenterBaseline+ && ideographicOverBaseline == other.ideographicOverBaseline+ && ideographicFaceUnderBaseline == other.ideographicFaceUnderBaseline+ && ideographicFaceOverBaseline == other.ideographicFaceOverBaseline+ && hangingBaseline == other.hangingBaseline;+ }++ int valueForBaselineValue(Baseline baseline) const {+ switch(baseline) {+ case BaselineIdeographic:+ return ideographicUnderBaseline;+ case BaselineAlphabetic:+ return alphabeticBaseline;+ case BaselineHanging:+ return hangingBaseline;+ case BaselineMathematical:+ return mathematicalBaseline;+ case BaselineCentral:+ return ideographicCenterBaseline;+ case BaselineMiddle:+ return xHeight/2;+ case BaselineTextBottom:+ return descender;+ case BaselineTextTop:+ return ascender;+ default:+ break;+ }+ return 0;+ }++ void setBaselineValueByTag(const QLatin1String &tag, int32_t value);++ void setMetricsValueByTag(const QLatin1String &tag, int32_t value);++ void scaleBaselines(const qreal multiplier);+};+QDebug KRITAFLAKE_EXPORT operator<<(QDebug dbg, const KoSvgText::FontMetrics &metrics);+} // namespace KoSvgTextQ_DECLARE_METATYPE(KoSvgText::CssLengthPercentage)@@ -1003,4 +1091,6 @@ Q_DECLARE_METATYPE(KoSvgText::FontFeatureLigatures)Q_DECLARE_METATYPE(KoSvgText::FontFeatureNumeric)Q_DECLARE_METATYPE(KoSvgText::FontFeatureEastAsian)+Q_DECLARE_METATYPE(KoSvgText::FontMetrics)+#endif // KOSVGTEXT_Hdiff --git a/libs/flake/text/KoSvgTextProperties.cpp b/libs/flake/text/KoSvgTextProperties.cppindex cc275afddc..5ca32c219d 100644--- a/libs/flake/text/KoSvgTextProperties.cpp+++ b/libs/flake/text/KoSvgTextProperties.cpp@@ -20,6 +20,7 @@#include <kis_global.h>#include "KoSvgText.h"+#include "KoFontRegistry.h"struct KoSvgTextProperties::Private{@@ -989,8 +990,11 @@ QFont KoSvgTextProperties::generateFont() constqreal KoSvgTextProperties::xHeight() const{- QFontMetrics metrics(this->generateFont());- return metrics.xHeight();+ const KoCSSFontInfo info = cssFontInfo();+ const qreal fontSizeVal = fontSize().value;+ const bool isHorizontal = propertyOrDefault(WritingModeId).toInt() == KoSvgText::HorizontalTB;+ const KoSvgText::FontMetrics metrics = KoFontRegistry::instance()->fontMetricsForCSSValues(info, isHorizontal);+ return double((metrics.xHeight*-1)/metrics.fontSize) * fontSizeVal;}QStringList KoSvgTextProperties::fontFeaturesForText(int start, int length) constdiff --git a/libs/flake/text/KoSvgTextShape_p.h b/libs/flake/text/KoSvgTextShape_p.hindex 9e6e8b655f..c2ff98a7f1 100644--- a/libs/flake/text/KoSvgTextShape_p.h+++ b/libs/flake/text/KoSvgTextShape_p.h@@ -385,7 +385,7 @@ public:bool isClosed);static void applyTextPath(KisForest<KoSvgTextContentElement>::child_iterator parent, QVector<CharacterResult> &result, bool isHorizontal, QPointF &startPos);void computeFontMetrics(KisForest<KoSvgTextContentElement>::child_iterator parent, const KoSvgTextProperties &parentProps,- const QMap<int, int> &parentBaselineTable,+ const KoSvgText::FontMetrics &parentBaselineTable,qreal parentFontSize,QPointF superScript,QPointF subScript,diff --git a/libs/flake/text/KoSvgTextShape_p_layout.cpp b/libs/flake/text/KoSvgTextShape_p_layout.cppindex 36e3d4e27f..09baae5581 100644--- a/libs/flake/text/KoSvgTextShape_p_layout.cpp+++ b/libs/flake/text/KoSvgTextShape_p_layout.cpp@@ -136,20 +136,6 @@ void KoSvgTextShape::Private::relayout()loadFlags |= FT_LOAD_TARGET_LIGHT;}}- const auto loadFlagsForFace = [loadFlags, isHorizontal](FT_Face face) -> FT_Int32 {- FT_Int32 faceLoadFlags = loadFlags;- if (FT_HAS_COLOR(face)) {- faceLoadFlags |= FT_LOAD_COLOR;- }- if (!isHorizontal && FT_HAS_VERTICAL(face)) {- faceLoadFlags |= FT_LOAD_VERTICAL_LAYOUT;- }- if (!FT_IS_SCALABLE(face)) {- // This is needed for the CBDT version of Noto Color Emoji- faceLoadFlags &= ~FT_LOAD_NO_BITMAP;- }- return faceLoadFlags;- };// Whenever the freetype docs talk about a 26.6 floating point unit, they// mean a 1/64 value.@@ -430,7 +416,7 @@ void KoSvgTextShape::Private::relayout()for (int i = 0; i < lengths.size(); i++) {length = lengths.at(i);const FT_FaceSP &face = faces.at(static_cast<size_t>(i));- const FT_Int32 faceLoadFlags = loadFlagsForFace(face.data());+ const FT_Int32 faceLoadFlags = KoFontRegistry::loadFlagsForFace(face.data(), isHorizontal, loadFlags);if (start == 0) {raqm_set_freetype_face(layout.data(), face.data());raqm_set_freetype_load_flags(layout.data(), faceLoadFlags);@@ -446,103 +432,21 @@ void KoSvgTextShape::Private::relayout()static_cast<size_t>(length));}- hb_font_t_sp font(hb_ft_font_create_referenced(face.data()));- hb_position_t ascender = 0;- hb_position_t descender = 0;- hb_position_t lineGap = 0;-- if (isHorizontal) {- /**- * There's 3 different definitions of the so-called vertical metrics, that is,- * the ascender and descender for horizontally laid out script. WinAsc & Desc,- * HHAE asc&desc, and OS/2... we need the last one, but harfbuzz doesn't return- * it unless there's a flag set in the font, which is missing in a lot of fonts- * that were from the transitional period, like Deja Vu Sans. Hence we need to get- * the OS/2 table and calculate the values manually (and fall back in various ways).- *- * https://www.w3.org/TR/css-inline-3/#ascent-descent- * https://www.w3.org/TR/CSS2/visudet.html#sTypoAscender- * https://wiki.inkscape.org/wiki/Text_Rendering_Notes#Ascent_and_Descent- *- * Related HB issue: https://github.com/harfbuzz/harfbuzz/issues/1920- */- TT_OS2 *os2Table = nullptr;- os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face.data(), FT_SFNT_OS2);- if (os2Table) {- int yscale = face.data()->size->metrics.y_scale;-- ascender = FT_MulFix(os2Table->sTypoAscender, yscale);- descender = FT_MulFix(os2Table->sTypoDescender, yscale);- lineGap = FT_MulFix(os2Table->sTypoLineGap, yscale);- }-- constexpr unsigned USE_TYPO_METRICS = 1u << 7;- if (!os2Table || os2Table->version == 0xFFFFU || !(os2Table->fsSelection & USE_TYPO_METRICS)) {- hb_position_t altAscender = 0;- hb_position_t altDescender = 0;- hb_position_t altLineGap = 0;- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_ASCENDER, &altAscender)) {- altAscender = face.data()->ascender;- }- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_DESCENDER, &altDescender)) {- altDescender = face.data()->descender;- }- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_HORIZONTAL_LINE_GAP, &altLineGap)) {- altLineGap = face.data()->height - (altAscender-altDescender);- }-- // Some fonts have sTypo metrics that are too small compared- // to the HHEA values which make the default line height too- // tight (e.g. Microsoft JhengHei, Source Han Sans), so we- // compare them and take the ones that are larger.- if (!os2Table || (altAscender - altDescender + altLineGap) > (ascender - descender + lineGap)) {- ascender = altAscender;- descender = altDescender;- lineGap = altLineGap;- }- }- } else {- hb_font_extents_t fontExtends;- hb_font_get_extents_for_direction (font.data(), HB_DIRECTION_TTB, &fontExtends);- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_ASCENDER, &ascender)) {- ascender = fontExtends.ascender;- }- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_DESCENDER, &descender)) {- descender = fontExtends.descender;- }- if (!hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_VERTICAL_LINE_GAP, &lineGap)) {- lineGap = 0;- }- // Default microsoft CJK fonts have the vertical ascent and descent be the same as the horizontal- // ascent and descent, so we 'normalize' the ascender and descender to be half the total height.- qreal height = ascender - fontExtends.descender;- ascender = height*0.5;- descender = -ascender;- }- if (ascender == 0 && descender == 0) {- ascender = face->size->metrics.ascender;- descender = face->size->metrics.descender;- qreal height = ascender - descender;- lineGap = face->size->metrics.height - height;- if (!isHorizontal) {- ascender = height * 0.5;- descender = -ascender;- }- }+ KoSvgText::FontMetrics metrics = KoFontRegistry::generateFontMetrics(face, isHorizontal);for (int j=start; j<start+length; j++) {- result[j].fontAscent = ascender;- result[j].fontDescent = descender;- qreal leading = lineGap;+ result[j].fontAscent = metrics.ascender;+ result[j].fontDescent = metrics.descender;+ qreal leading = metrics.lineGap;if (!lineHeight.isNormal) {if (lineHeight.isNumber) {leading = (fontSize*scaleToPixel*ftFontUnit)*lineHeight.value;- leading -= (ascender-descender);+ leading -= (metrics.ascender-metrics.descender);} else {QPointF val = ftTF.inverted().map(QPointF(lineHeight.length.value, lineHeight.length.value));leading = isHorizontal? val.x(): val.y();- leading -= (ascender-descender);+ leading -= (metrics.ascender-metrics.descender);}}result[j].fontHalfLeading = leading * 0.5;@@ -588,7 +492,7 @@ void KoSvgTextShape::Private::relayout()}CharacterResult charResult = result[cluster];- const FT_Int32 faceLoadFlags = loadFlagsForFace(currentGlyph.ftface);+ const FT_Int32 faceLoadFlags = KoFontRegistry::loadFlagsForFace(currentGlyph.ftface, isHorizontal, loadFlags);const auto getUcs4At = [](const QString &s, int i) -> char32_t {const QChar high = s.at(i);@@ -715,7 +619,7 @@ void KoSvgTextShape::Private::relayout()// Compute baseline alignment.globalIndex = 0;- this->computeFontMetrics(textData.childBegin(), KoSvgTextProperties::defaultProperties(), QMap<int, int>(), 0, QPointF(), QPointF(), result, globalIndex, finalRes, isHorizontal, disableFontMatching);+ this->computeFontMetrics(textData.childBegin(), KoSvgTextProperties::defaultProperties(), KoSvgText::FontMetrics(), 0, QPointF(), QPointF(), result, globalIndex, finalRes, isHorizontal, disableFontMatching);// Handle linebreaking.QPointF startPos = resolvedTransforms[0].absolutePos();@@ -1124,7 +1028,7 @@ void KoSvgTextShape::Private::applyTextLength(KisForest<KoSvgTextContentElement>void KoSvgTextShape::Private::computeFontMetrics( // NOLINT(readability-function-cognitive-complexity)KisForest<KoSvgTextContentElement>::child_iterator parent,const KoSvgTextProperties &parentProps,- const QMap<int, int> &parentBaselineTable,+ const KoSvgText::FontMetrics &parentBaselineTable,qreal parentFontSize,QPointF superScript,QPointF subScript,@@ -1134,8 +1038,6 @@ void KoSvgTextShape::Private::computeFontMetrics( // NOLINT(readability-functionbool isHorizontal,bool disableFontMatching){-- QMap<int, int> baselineTable;const int i = currentIndex;const int j = qMin(i + numChars(parent, true), result.size());@@ -1165,173 +1067,52 @@ void KoSvgTextShape::Private::computeFontMetrics( // NOLINT(readability-functionstatic_cast<quint32>(res),disableFontMatching);- hb_font_t_sp font(hb_ft_font_create_referenced(faces.front().data()));const qreal freetypePixelsToPt = (1.0 / 64.0) * (72. / res);- hb_direction_t dir = HB_DIRECTION_LTR;- if (!isHorizontal) {- dir = HB_DIRECTION_TTB;- }- hb_script_t script = HB_SCRIPT_UNKNOWN;KoSvgText::Baseline dominantBaseline = KoSvgText::Baseline(properties.property(KoSvgTextProperties::DominantBaselineId).toInt());hb_position_t baseline = 0;+ hb_font_t_sp font(hb_ft_font_create_referenced(faces.front().data()));KoSvgText::Baseline defaultBaseline = isHorizontal? KoSvgText::BaselineAlphabetic: KoSvgText::BaselineCentral;+ KoSvgText::FontMetrics metrics;if (dominantBaseline == KoSvgText::BaselineResetSize && parentFontSize > 0) {- baselineTable = parentBaselineTable;- qreal multiplier = 1.0 / parentFontSize * fontSize;- Q_FOREACH (int key, baselineTable.keys()) {- baselineTable.insert(key, static_cast<int>(baselineTable.value(key) * multiplier));- }+ metrics = parentBaselineTable;+ metrics.scaleBaselines(1.0 / parentFontSize * fontSize);dominantBaseline = KoSvgText::BaselineAuto;} else if (dominantBaseline == KoSvgText::BaselineNoChange) {- baselineTable = parentBaselineTable;+ metrics = parentBaselineTable;dominantBaseline = KoSvgText::BaselineAuto;} else {- QMap<hb_ot_layout_baseline_tag_t, KoSvgText::Baseline> baselineList;- baselineList.insert(HB_OT_LAYOUT_BASELINE_TAG_ROMAN, KoSvgText::BaselineAlphabetic);- baselineList.insert(HB_OT_LAYOUT_BASELINE_TAG_MATH, KoSvgText::BaselineMathematical);- baselineList.insert(HB_OT_LAYOUT_BASELINE_TAG_HANGING, KoSvgText::BaselineHanging);- baselineList.insert(HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_CENTRAL, KoSvgText::BaselineCentral);- baselineList.insert(HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT, KoSvgText::BaselineIdeographic);-- if (hb_version_atleast(4, 0, 0)) {- hb_position_t origin = 0;- hb_ot_layout_get_baseline_with_fallback(font.data(), baselineList.key(defaultBaseline), dir, script, HB_TAG_NONE, &origin);- Q_FOREACH(hb_ot_layout_baseline_tag_t tag, baselineList.keys()) {- hb_ot_layout_get_baseline_with_fallback(font.data(), tag, dir, script, HB_TAG_NONE, &baseline);- baselineTable.insert(baselineList.value(tag), baseline - origin);- }+ metrics = KoFontRegistry::generateFontMetrics(faces.front(), isHorizontal);+ }- if (isHorizontal) {- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_X_HEIGHT, &baseline);- baselineTable.insert(KoSvgText::BaselineMiddle, static_cast<int>((baseline - baselineTable.value(KoSvgText::BaselineAlphabetic)) * 0.5));- } else {- baselineTable.insert(KoSvgText::BaselineMiddle, baselineTable.value(KoSvgText::BaselineCentral));- }- } else {- hb_position_t origin = 0;- if (!isHorizontal) {- // we'll need to calculate the central baseline manually, because there's no opentype tag associated with it, and- // the harfbuzz tag is specific to HB 4.0 and up.-- hb_position_t over = 0.0;- hb_position_t under = 0.0;- bool hasOver = hb_ot_layout_get_baseline(font.data(), HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_TOP_OR_RIGHT, dir, script, HB_TAG_NONE, &over);- bool hasUnder = hb_ot_layout_get_baseline(font.data(), HB_OT_LAYOUT_BASELINE_TAG_IDEO_EMBOX_BOTTOM_OR_LEFT, dir, script, HB_TAG_NONE, &under);- if (!hasOver || !hasUnder) {- hb_font_extents_t font_extents;- hb_font_get_extents_for_direction (font.data(), dir, &font_extents);- if (!hasOver) { over = font_extents.ascender;}- if (!hasUnder) { under = font_extents.descender;}- }- origin = (over + under) / 2;- }+ // Get underline and super/subscripts.+ QPointF newSuperScript = QPointF(metrics.superScriptOffset.first * freetypePixelsToPt, metrics.superScriptOffset.second * -freetypePixelsToPt);;+ QPointF newSubScript = QPointF(metrics.subScriptOffset.first * freetypePixelsToPt, metrics.subScriptOffset.second * -freetypePixelsToPt);- Q_FOREACH(hb_ot_layout_baseline_tag_t tag, baselineList.keys()) {- if (baselineList.value(tag) == defaultBaseline) {- baselineTable.insert(defaultBaseline, 0);- } else {- baseline = 0;- hb_ot_layout_get_baseline(font.data(), tag, dir, script, HB_TAG_NONE, &baseline);- baselineTable.insert(baselineList.value(tag), baseline-origin);- }- }+ hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_UNDERLINE_SIZE, &baseline);+ qreal width = baseline;+ hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_UNDERLINE_OFFSET, &baseline);+ qreal lineOffset = baseline;+ lineOffset *= -freetypePixelsToPt;+ width *= freetypePixelsToPt;- if (isHorizontal) {- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_X_HEIGHT, &baseline);- baselineTable.insert(KoSvgText::BaselineMiddle, static_cast<int>((baseline - baselineTable.value(KoSvgText::BaselineAlphabetic)) * 0.5));- } else {- baselineTable.insert(KoSvgText::BaselineMiddle, baselineTable.value(KoSvgText::BaselineCentral));- }- }- }+ parent->textDecorationWidths.insert(KoSvgText::DecorationUnderline, width);+ parent->textDecorationOffsets.insert(KoSvgText::DecorationUnderline, lineOffset);+ parent->textDecorationWidths.insert(KoSvgText::DecorationOverline, width);- // Get underline and super/subscripts.- QPointF newSuperScript;- QPointF newSubScript;- if (hb_version_atleast(4, 0, 0)) {- hb_position_t baseline2 = 0;- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_SUPERSCRIPT_EM_X_OFFSET, &baseline);- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_SUPERSCRIPT_EM_Y_OFFSET, &baseline2);- newSuperScript = QPointF(baseline * freetypePixelsToPt, baseline2 * -freetypePixelsToPt);- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_SUBSCRIPT_EM_X_OFFSET, &baseline);- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_SUBSCRIPT_EM_Y_OFFSET, &baseline2);- newSubScript = QPointF(baseline * freetypePixelsToPt, baseline2 * freetypePixelsToPt);-- qreal width = 0;- qreal offset = 0;- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_UNDERLINE_SIZE, &baseline);- width = baseline;- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_UNDERLINE_OFFSET, &baseline);- offset = baseline;- offset *= -freetypePixelsToPt;- width *= freetypePixelsToPt;-- parent->textDecorationWidths.insert(KoSvgText::DecorationUnderline, width);- parent->textDecorationOffsets.insert(KoSvgText::DecorationUnderline, offset);- parent->textDecorationWidths.insert(KoSvgText::DecorationOverline, width);-- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_SIZE, &baseline);- width = baseline;- hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_OFFSET, &baseline);- width *= freetypePixelsToPt;- offset *= -freetypePixelsToPt;-- parent->textDecorationWidths.insert(KoSvgText::DecorationLineThrough, width);- parent->textDecorationOffsets.insert(KoSvgText::DecorationLineThrough, offset);- } else {- baseline = 0;- hb_position_t baseline2 = 0;- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_SUPERSCRIPT_EM_X_OFFSET, &baseline);- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_SUPERSCRIPT_EM_Y_OFFSET, &baseline2);- if (baseline2 == 0) {- newSuperScript = QPointF(0, 0.6 * -fontSize);- } else {- newSuperScript = QPointF(baseline * freetypePixelsToPt, baseline2 * -freetypePixelsToPt);- }- baseline = 0;- baseline2 = 0;- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_SUBSCRIPT_EM_X_OFFSET, &baseline);- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_SUBSCRIPT_EM_Y_OFFSET, &baseline2);- // Subscript should be 'added' onto the baseline'.- if (baseline2 == 0) {- newSubScript = QPointF(0, 0.2 * fontSize);- } else {- newSubScript = QPointF(baseline * freetypePixelsToPt, baseline2 * freetypePixelsToPt);- }+ hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_SIZE, &baseline);+ width = baseline;+ hb_ot_metrics_get_position_with_fallback(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_OFFSET, &baseline);+ width *= freetypePixelsToPt;+ lineOffset *= -freetypePixelsToPt;- qreal width = 0;- qreal offset = 0;- const double fallbackThickness =- faces.front()->underline_thickness * (faces.front()->size->metrics.y_scale / 65535.0);- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_UNDERLINE_SIZE, &baseline);- width = qMax<double>(baseline, fallbackThickness);-- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_UNDERLINE_OFFSET, &baseline);- offset = baseline;- offset *= -freetypePixelsToPt;- width *= freetypePixelsToPt;-- parent->textDecorationWidths.insert(KoSvgText::DecorationUnderline, width);- parent->textDecorationOffsets.insert(KoSvgText::DecorationUnderline, offset);- parent->textDecorationWidths.insert(KoSvgText::DecorationOverline, width);-- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_SIZE, &baseline);- width = qMax<double>(baseline, fallbackThickness);- hb_ot_metrics_get_position(font.data(), HB_OT_METRICS_TAG_STRIKEOUT_OFFSET, &baseline);- if (baseline == 0) {- offset = baselineTable.value(KoSvgText::BaselineCentral);- }- width *= freetypePixelsToPt;- offset *= -freetypePixelsToPt;+ parent->textDecorationWidths.insert(KoSvgText::DecorationLineThrough, width);+ parent->textDecorationOffsets.insert(KoSvgText::DecorationLineThrough, lineOffset);- parent->textDecorationWidths.insert(KoSvgText::DecorationLineThrough, width);- parent->textDecorationOffsets.insert(KoSvgText::DecorationLineThrough, offset);- }for (auto child = KisForestDetail::childBegin(parent); child != KisForestDetail::childEnd(parent); child++) {- computeFontMetrics(child, properties, baselineTable, fontSize, newSuperScript, newSubScript, result, currentIndex, res, isHorizontal, disableFontMatching);+ computeFontMetrics(child, properties, metrics, fontSize, newSuperScript, newSubScript, result, currentIndex, res, isHorizontal, disableFontMatching);}KoSvgText::Baseline baselineAdjust = KoSvgText::Baseline(properties.property(KoSvgTextProperties::AlignmentBaselineId).toInt());@@ -1353,7 +1134,7 @@ void KoSvgTextShape::Private::computeFontMetrics( // NOLINT(readability-function}}- const int offset = parentBaselineTable.value(baselineAdjust, 0) - baselineTable.value(baselineAdjust, 0);+ const int offset = parentBaselineTable.valueForBaselineValue(baselineAdjust) - metrics.valueForBaselineValue(baselineAdjust);QPointF shift = QPointF();if (baselineAdjust != KoSvgText::BaselineTextTop && baselineAdjust != KoSvgText::BaselineTextBottom) {