summaryrefslogtreecommitdiffstats
path: root/vcl/source/font
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--vcl/source/font/DirectFontSubstitution.cxx71
-rw-r--r--vcl/source/font/EmphasisMark.cxx174
-rw-r--r--vcl/source/font/Feature.cxx162
-rw-r--r--vcl/source/font/FeatureCollector.cxx206
-rw-r--r--vcl/source/font/FeatureParser.cxx67
-rw-r--r--vcl/source/font/FontSelectPattern.cxx156
-rw-r--r--vcl/source/font/LogicalFontInstance.cxx348
-rw-r--r--vcl/source/font/OpenTypeFeatureDefinitionList.cxx159
-rw-r--r--vcl/source/font/PhysicalFontCollection.cxx1279
-rw-r--r--vcl/source/font/PhysicalFontFace.cxx510
-rw-r--r--vcl/source/font/PhysicalFontFamily.cxx269
-rw-r--r--vcl/source/font/font.cxx1185
-rw-r--r--vcl/source/font/fontattributes.cxx61
-rw-r--r--vcl/source/font/fontcache.cxx283
-rw-r--r--vcl/source/font/fontcharmap.cxx251
-rw-r--r--vcl/source/font/fontmetric.cxx563
-rw-r--r--vcl/source/fontsubset/cff.cxx2625
-rw-r--r--vcl/source/fontsubset/fontsubset.cxx94
-rw-r--r--vcl/source/fontsubset/sft.cxx1847
-rw-r--r--vcl/source/fontsubset/ttcr.cxx1136
-rw-r--r--vcl/source/fontsubset/ttcr.hxx288
-rw-r--r--vcl/source/fontsubset/xlat.cxx144
-rw-r--r--vcl/source/fontsubset/xlat.hxx37
23 files changed, 11915 insertions, 0 deletions
diff --git a/vcl/source/font/DirectFontSubstitution.cxx b/vcl/source/font/DirectFontSubstitution.cxx
new file mode 100644
index 0000000000..e494fb7ce7
--- /dev/null
+++ b/vcl/source/font/DirectFontSubstitution.cxx
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <unotools/fontdefs.hxx>
+
+#include <font/DirectFontSubstitution.hxx>
+
+#include <svdata.hxx>
+
+#include <string>
+#include <vector>
+
+namespace vcl::font
+{
+void DirectFontSubstitution::AddFontSubstitute(const OUString& rFontName,
+ const OUString& rSubstFontName,
+ AddFontSubstituteFlags nFlags)
+{
+ maFontSubstList.emplace_back(rFontName, rSubstFontName, nFlags);
+}
+
+void DirectFontSubstitution::RemoveFontsSubstitute() { maFontSubstList.clear(); }
+
+bool DirectFontSubstitution::FindFontSubstitute(OUString& rSubstName,
+ std::u16string_view rSearchName) const
+{
+ // TODO: get rid of O(N) searches
+ std::vector<FontSubstEntry>::const_iterator it = std::find_if(
+ maFontSubstList.begin(), maFontSubstList.end(), [&](const FontSubstEntry& s) {
+ return (s.mnFlags & AddFontSubstituteFlags::ALWAYS) && (s.maSearchName == rSearchName);
+ });
+ if (it != maFontSubstList.end())
+ {
+ rSubstName = it->maSearchReplaceName;
+ return true;
+ }
+ return false;
+}
+
+void ImplFontSubstitute(OUString& rFontName)
+{
+ // must be canonicalised
+ assert(GetEnglishSearchFontName(rFontName) == rFontName);
+ OUString aSubstFontName;
+ // apply user-configurable font replacement (eg, from the list in Tools->Options)
+ const DirectFontSubstitution* pSubst = ImplGetSVData()->maGDIData.mpDirectFontSubst;
+ if (pSubst && pSubst->FindFontSubstitute(aSubstFontName, rFontName))
+ {
+ rFontName = aSubstFontName;
+ return;
+ }
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
diff --git a/vcl/source/font/EmphasisMark.cxx b/vcl/source/font/EmphasisMark.cxx
new file mode 100644
index 0000000000..be1a20223e
--- /dev/null
+++ b/vcl/source/font/EmphasisMark.cxx
@@ -0,0 +1,174 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#include <sal/config.h>
+
+#include <font/EmphasisMark.hxx>
+
+namespace vcl::font
+{
+EmphasisMark::EmphasisMark(FontEmphasisMark eEmphasis, tools::Long nHeight, sal_Int32 nDPIY)
+{
+ static const PolyFlags aAccentPolyFlags[24] =
+ {
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Normal, PolyFlags::Control,
+ PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control
+ };
+
+ static const Point aAccentPos[24] =
+ {
+ { 78, 0 },
+ { 348, 79 },
+ { 599, 235 },
+ { 843, 469 },
+ { 938, 574 },
+ { 990, 669 },
+ { 990, 773 },
+ { 990, 843 },
+ { 964, 895 },
+ { 921, 947 },
+ { 886, 982 },
+ { 860, 999 },
+ { 825, 999 },
+ { 764, 999 },
+ { 721, 964 },
+ { 686, 895 },
+ { 625, 791 },
+ { 556, 660 },
+ { 469, 504 },
+ { 400, 400 },
+ { 261, 252 },
+ { 61, 61 },
+ { 0, 27 },
+ { 9, 0 }
+ };
+
+ mnWidth = 0;
+ mnYOff = 0;
+ mbIsPolyLine = false;
+
+ if ( !nHeight )
+ return;
+
+ FontEmphasisMark nEmphasisStyle = eEmphasis & FontEmphasisMark::Style;
+ tools::Long nDotSize = 0;
+ switch ( nEmphasisStyle )
+ {
+ case FontEmphasisMark::Dot:
+ // Dot has 55% of the height
+ nDotSize = (nHeight*550)/1000;
+ if ( !nDotSize )
+ nDotSize = 1;
+ if ( nDotSize <= 2 )
+ maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) );
+ else
+ {
+ tools::Long nRad = nDotSize/2;
+ tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad );
+ maPolyPoly.Insert( aPoly );
+ }
+ mnYOff = ((nHeight*250)/1000)/2; // Center to the another EmphasisMarks
+ mnWidth = nDotSize;
+ break;
+
+ case FontEmphasisMark::Circle:
+ // Dot has 80% of the height
+ nDotSize = (nHeight*800)/1000;
+ if ( !nDotSize )
+ nDotSize = 1;
+ if ( nDotSize <= 2 )
+ maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) );
+ else
+ {
+ tools::Long nRad = nDotSize/2;
+ tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad );
+ maPolyPoly.Insert( aPoly );
+ // Border mnWidth is 15%
+ tools::Long nBorder = (nDotSize*150)/1000;
+ if ( nBorder <= 1 )
+ mbIsPolyLine = true;
+ else
+ {
+ tools::Polygon aPoly2( Point( nRad, nRad ),
+ nRad-nBorder, nRad-nBorder );
+ maPolyPoly.Insert( aPoly2 );
+ }
+ }
+ mnWidth = nDotSize;
+ break;
+
+ case FontEmphasisMark::Disc:
+ // Dot has 80% of the height
+ nDotSize = (nHeight*800)/1000;
+ if ( !nDotSize )
+ nDotSize = 1;
+ if ( nDotSize <= 2 )
+ maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) );
+ else
+ {
+ tools::Long nRad = nDotSize/2;
+ tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad );
+ maPolyPoly.Insert( aPoly );
+ }
+ mnWidth = nDotSize;
+ break;
+
+ case FontEmphasisMark::Accent:
+ // Dot has 80% of the height
+ nDotSize = (nHeight*800)/1000;
+ if ( !nDotSize )
+ nDotSize = 1;
+ if ( nDotSize <= 2 )
+ {
+ if ( nDotSize == 1 )
+ {
+ maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) );
+ mnWidth = nDotSize;
+ }
+ else
+ {
+ maRect1 = tools::Rectangle( Point(), Size( 1, 1 ) );
+ maRect2 = tools::Rectangle( Point( 1, 1 ), Size( 1, 1 ) );
+ }
+ }
+ else
+ {
+ tools::Polygon aPoly( SAL_N_ELEMENTS(aAccentPos), aAccentPos,
+ aAccentPolyFlags );
+ double dScale = static_cast<double>(nDotSize)/1000.0;
+ aPoly.Scale( dScale, dScale );
+ tools::Polygon aTemp;
+ aPoly.AdaptiveSubdivide( aTemp );
+ tools::Rectangle aBoundRect = aTemp.GetBoundRect();
+ mnWidth = aBoundRect.GetWidth();
+ nDotSize = aBoundRect.GetHeight();
+ maPolyPoly.Insert( aTemp );
+ }
+ break;
+ default: break;
+ }
+
+ // calculate position
+ tools::Long nOffY = 1+(nDPIY/300); // one visible pixel space
+ tools::Long nSpaceY = nHeight-nDotSize;
+ if ( nSpaceY >= nOffY*2 )
+ mnYOff += nOffY;
+
+ if ( !(eEmphasis & FontEmphasisMark::PosBelow) )
+ mnYOff += nDotSize;
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
diff --git a/vcl/source/font/Feature.cxx b/vcl/source/font/Feature.cxx
new file mode 100644
index 0000000000..ece71df8ed
--- /dev/null
+++ b/vcl/source/font/Feature.cxx
@@ -0,0 +1,162 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ */
+
+#include <utility>
+#include <vcl/font/Feature.hxx>
+#include <svdata.hxx>
+
+#include <hb.h>
+
+namespace vcl::font
+{
+OUString featureCodeAsString(uint32_t nFeature)
+{
+ std::vector<char> aString(5, 0);
+ aString[0] = char(nFeature >> 24 & 0xff);
+ aString[1] = char(nFeature >> 16 & 0xff);
+ aString[2] = char(nFeature >> 8 & 0xff);
+ aString[3] = char(nFeature >> 0 & 0xff);
+
+ return OStringToOUString(aString.data(), RTL_TEXTENCODING_ASCII_US);
+}
+
+// Feature
+Feature::Feature()
+ : m_nCode(0)
+ , m_eType(FeatureType::OpenType)
+{
+}
+
+Feature::Feature(uint32_t nCode, FeatureType eType)
+ : m_nCode(nCode)
+ , m_eType(eType)
+{
+}
+
+// FeatureSetting
+FeatureSetting::FeatureSetting(OString feature)
+ : m_nTag(0)
+ , m_nValue(0)
+ , m_nStart(0)
+ , m_nEnd(0)
+{
+ hb_feature_t aFeat;
+ if (hb_feature_from_string(feature.getStr(), feature.getLength(), &aFeat))
+ {
+ m_nTag = aFeat.tag;
+ m_nValue = aFeat.value;
+ m_nStart = aFeat.start;
+ m_nEnd = aFeat.end;
+ }
+}
+
+// FeatureParameter
+
+FeatureParameter::FeatureParameter(uint32_t nCode, OUString aDescription)
+ : m_nCode(nCode)
+ , m_sDescription(std::move(aDescription))
+{
+}
+
+FeatureParameter::FeatureParameter(uint32_t nCode, TranslateId pDescriptionID)
+ : m_nCode(nCode)
+ , m_pDescriptionID(pDescriptionID)
+{
+}
+
+OUString FeatureParameter::getDescription() const
+{
+ OUString aReturnString;
+
+ if (m_pDescriptionID)
+ aReturnString = VclResId(m_pDescriptionID);
+ else if (!m_sDescription.isEmpty())
+ aReturnString = m_sDescription;
+
+ return aReturnString;
+}
+
+uint32_t FeatureParameter::getCode() const { return m_nCode; }
+
+// FeatureDefinition
+
+FeatureDefinition::FeatureDefinition()
+ : m_nCode(0)
+ , m_nDefault(-1)
+ , m_eType(FeatureParameterType::BOOL)
+{
+}
+
+FeatureDefinition::FeatureDefinition(uint32_t nCode, OUString aDescription,
+ FeatureParameterType eType,
+ std::vector<FeatureParameter>&& rEnumParameters,
+ int32_t nDefault)
+ : m_sDescription(std::move(aDescription))
+ , m_nCode(nCode)
+ , m_nDefault(nDefault)
+ , m_eType(eType)
+ , m_aEnumParameters(std::move(rEnumParameters))
+{
+}
+
+FeatureDefinition::FeatureDefinition(uint32_t nCode, TranslateId pDescriptionID,
+ OUString aNumericPart)
+ : m_pDescriptionID(pDescriptionID)
+ , m_sNumericPart(std::move(aNumericPart))
+ , m_nCode(nCode)
+ , m_nDefault(-1)
+ , m_eType(FeatureParameterType::BOOL)
+{
+}
+
+FeatureDefinition::FeatureDefinition(uint32_t nCode, TranslateId pDescriptionID,
+ std::vector<FeatureParameter> aEnumParameters)
+ : m_pDescriptionID(pDescriptionID)
+ , m_nCode(nCode)
+ , m_nDefault(-1)
+ , m_eType(FeatureParameterType::ENUM)
+ , m_aEnumParameters(std::move(aEnumParameters))
+{
+}
+
+const std::vector<FeatureParameter>& FeatureDefinition::getEnumParameters() const
+{
+ return m_aEnumParameters;
+}
+
+OUString FeatureDefinition::getDescription() const
+{
+ if (m_pDescriptionID)
+ {
+ OUString sTranslatedDescription = VclResId(m_pDescriptionID);
+ if (!m_sNumericPart.isEmpty())
+ return sTranslatedDescription.replaceFirst("%1", m_sNumericPart);
+ return sTranslatedDescription;
+ }
+ else if (!m_sDescription.isEmpty())
+ {
+ return m_sDescription;
+ }
+ else
+ {
+ return vcl::font::featureCodeAsString(m_nCode);
+ }
+}
+
+uint32_t FeatureDefinition::getCode() const { return m_nCode; }
+
+FeatureParameterType FeatureDefinition::getType() const { return m_eType; }
+
+FeatureDefinition::operator bool() const { return m_nCode != 0; }
+
+int32_t FeatureDefinition::getDefault() const { return m_nDefault; }
+} // end vcl::font namespace
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/FeatureCollector.cxx b/vcl/source/font/FeatureCollector.cxx
new file mode 100644
index 0000000000..fd175eade0
--- /dev/null
+++ b/vcl/source/font/FeatureCollector.cxx
@@ -0,0 +1,206 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#include <font/FeatureCollector.hxx>
+#include <font/OpenTypeFeatureDefinitionList.hxx>
+#include <i18nlangtag/languagetag.hxx>
+
+#include <font/OpenTypeFeatureStrings.hrc>
+#include <svdata.hxx>
+
+#include <hb-ot.h>
+#include <hb-graphite2.h>
+
+namespace vcl::font
+{
+bool FeatureCollector::collectGraphite()
+{
+ gr_face* grFace = hb_graphite2_face_get_gr_face(m_pHbFace);
+
+ if (grFace == nullptr)
+ return false;
+
+ gr_uint16 nUILanguage = gr_uint16(m_rLanguageTag.getLanguageType());
+
+ gr_uint16 nNumberOfFeatures = gr_face_n_fref(grFace);
+ gr_feature_val* pfeatureValues
+ = gr_face_featureval_for_lang(grFace, 0); // shame we don't know which lang
+
+ for (gr_uint16 i = 0; i < nNumberOfFeatures; ++i)
+ {
+ const gr_feature_ref* pFeatureRef = gr_face_fref(grFace, i);
+ gr_uint32 nFeatureCode = gr_fref_id(pFeatureRef);
+
+ if (nFeatureCode == 0) // illegal feature code - skip
+ continue;
+
+ gr_uint16 nValue = gr_fref_feature_value(pFeatureRef, pfeatureValues);
+ gr_uint32 nLabelLength = 0;
+ void* pLabel = gr_fref_label(pFeatureRef, &nUILanguage, gr_utf8, &nLabelLength);
+ OUString sLabel(OUString::createFromAscii(static_cast<char*>(pLabel)));
+ gr_label_destroy(pLabel);
+
+ std::vector<vcl::font::FeatureParameter> aParameters;
+ gr_uint16 nNumberOfValues = gr_fref_n_values(pFeatureRef);
+
+ if (nNumberOfValues > 0)
+ {
+ for (gr_uint16 j = 0; j < nNumberOfValues; ++j)
+ {
+ gr_uint32 nValueLabelLength = 0;
+ void* pValueLabel = gr_fref_value_label(pFeatureRef, j, &nUILanguage, gr_utf8,
+ &nValueLabelLength);
+ OUString sValueLabel(OUString::createFromAscii(static_cast<char*>(pValueLabel)));
+ gr_uint16 nParamValue = gr_fref_value(pFeatureRef, j);
+ aParameters.emplace_back(sal_uInt32(nParamValue), sValueLabel);
+ gr_label_destroy(pValueLabel);
+ }
+
+ auto eFeatureParameterType = vcl::font::FeatureParameterType::ENUM;
+
+ // Check if the parameters are boolean
+ if (aParameters.size() == 2
+ && (aParameters[0].getDescription() == "True"
+ || aParameters[0].getDescription() == "False"))
+ {
+ eFeatureParameterType = vcl::font::FeatureParameterType::BOOL;
+ aParameters.clear();
+ }
+
+ m_rFontFeatures.emplace_back(nFeatureCode, vcl::font::FeatureType::Graphite);
+ vcl::font::Feature& rFeature = m_rFontFeatures.back();
+ rFeature.m_aDefinition
+ = vcl::font::FeatureDefinition(nFeatureCode, sLabel, eFeatureParameterType,
+ std::move(aParameters), int32_t(nValue));
+ }
+ }
+ gr_featureval_destroy(pfeatureValues);
+ return true;
+}
+
+void FeatureCollector::collectForTable(hb_tag_t aTableTag)
+{
+ unsigned int nFeatureCount
+ = hb_ot_layout_table_get_feature_tags(m_pHbFace, aTableTag, 0, nullptr, nullptr);
+ std::vector<hb_tag_t> aFeatureTags(nFeatureCount);
+ hb_ot_layout_table_get_feature_tags(m_pHbFace, aTableTag, 0, &nFeatureCount,
+ aFeatureTags.data());
+ aFeatureTags.resize(nFeatureCount);
+
+ for (hb_tag_t aFeatureTag : aFeatureTags)
+ {
+ if (OpenTypeFeatureDefinitionList().isRequired(aFeatureTag))
+ continue;
+
+ m_rFontFeatures.emplace_back();
+ vcl::font::Feature& rFeature = m_rFontFeatures.back();
+ rFeature.m_nCode = aFeatureTag;
+
+ FeatureDefinition aDefinition = OpenTypeFeatureDefinitionList().getDefinition(rFeature);
+ std::vector<vcl::font::FeatureParameter> aParameters{
+ { 0, VclResId(STR_FONT_FEATURE_PARAM_NONE) }
+ };
+
+ unsigned int nFeatureIdx;
+ if (hb_ot_layout_language_find_feature(m_pHbFace, aTableTag, 0,
+ HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX, aFeatureTag,
+ &nFeatureIdx))
+ {
+ // ssXX and cvXX can have name ID defined for them, check for
+ // them and use as appropriate.
+ hb_ot_name_id_t aLabelID;
+ hb_ot_name_id_t aFirstParameterID;
+ unsigned nNamedParameters;
+ if (hb_ot_layout_feature_get_name_ids(m_pHbFace, aTableTag, nFeatureIdx, &aLabelID,
+ nullptr, nullptr, &nNamedParameters,
+ &aFirstParameterID))
+ {
+ OUString sLabel = m_pFace->GetName(NameID(aLabelID), m_rLanguageTag);
+ if (!sLabel.isEmpty())
+ aDefinition = vcl::font::FeatureDefinition(aFeatureTag, sLabel);
+
+ // cvXX features can have parameters name IDs, check for
+ // them and populate feature parameters as appropriate.
+ for (unsigned i = 0; i < nNamedParameters; i++)
+ {
+ hb_ot_name_id_t aNameID = aFirstParameterID + i;
+ OUString sName = m_pFace->GetName(NameID(aNameID), m_rLanguageTag);
+ if (!sName.isEmpty())
+ aParameters.emplace_back(uint32_t(i + 1), sName);
+ else
+ aParameters.emplace_back(uint32_t(i + 1), OUString::number(i + 1));
+ }
+ }
+
+ unsigned int nAlternates = 0;
+ if (aTableTag == HB_OT_TAG_GSUB)
+ {
+ // Collect lookups in this feature, and input glyphs for each
+ // lookup, and calculate the max number of alternates they have.
+ unsigned int nLookups = hb_ot_layout_feature_get_lookups(
+ m_pHbFace, aTableTag, nFeatureIdx, 0, nullptr, nullptr);
+ std::vector<unsigned int> aLookups(nLookups);
+ hb_ot_layout_feature_get_lookups(m_pHbFace, aTableTag, nFeatureIdx, 0, &nLookups,
+ aLookups.data());
+
+ hb_set_t* pGlyphs = hb_set_create();
+ for (unsigned int nLookupIdx : aLookups)
+ {
+ hb_set_clear(pGlyphs);
+ hb_ot_layout_lookup_collect_glyphs(m_pHbFace, aTableTag, nLookupIdx, nullptr,
+ pGlyphs, nullptr, nullptr);
+ hb_codepoint_t nGlyphIdx = HB_SET_VALUE_INVALID;
+ while (hb_set_next(pGlyphs, &nGlyphIdx))
+ {
+ nAlternates
+ = std::max(nAlternates,
+ hb_ot_layout_lookup_get_glyph_alternates(
+ m_pHbFace, nLookupIdx, nGlyphIdx, 0, nullptr, nullptr));
+ }
+ }
+ hb_set_destroy(pGlyphs);
+ }
+
+ // Append the alternates to the feature parameters, keeping any
+ // existing ones calculated from cvXX features above.
+ for (unsigned int i = aParameters.size() - 1; i < nAlternates; i++)
+ aParameters.emplace_back(uint32_t(i + 1), OUString::number(i + 1));
+
+ if (aParameters.size() > 1)
+ {
+ aDefinition = vcl::font::FeatureDefinition(
+ aFeatureTag, aDefinition.getDescription(),
+ vcl::font::FeatureParameterType::ENUM, std::move(aParameters), 0);
+ }
+ }
+
+ if (aDefinition)
+ rFeature.m_aDefinition = aDefinition;
+ }
+}
+
+bool FeatureCollector::collect()
+{
+ gr_face* grFace = hb_graphite2_face_get_gr_face(m_pHbFace);
+
+ if (grFace)
+ {
+ return collectGraphite();
+ }
+ else
+ {
+ collectForTable(HB_OT_TAG_GSUB); // substitution
+ collectForTable(HB_OT_TAG_GPOS); // positioning
+ return true;
+ }
+}
+
+} // end namespace vcl::font
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/FeatureParser.cxx b/vcl/source/font/FeatureParser.cxx
new file mode 100644
index 0000000000..697662032f
--- /dev/null
+++ b/vcl/source/font/FeatureParser.cxx
@@ -0,0 +1,67 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ */
+
+#include <vcl/font/FeatureParser.hxx>
+#include <vcl/font/Feature.hxx>
+#include <o3tl/string_view.hxx>
+
+namespace vcl::font
+{
+OUString trimFontNameFeatures(OUString const& rFontName)
+{
+ const sal_Int32 nPrefixIdx{ rFontName.indexOf(vcl::font::FeaturePrefix) };
+
+ if (nPrefixIdx < 0)
+ return rFontName;
+
+ return rFontName.copy(0, nPrefixIdx);
+}
+
+FeatureParser::FeatureParser(std::u16string_view rFontName)
+{
+ size_t nPrefixIdx{ rFontName.find(vcl::font::FeaturePrefix) };
+
+ if (nPrefixIdx == std::u16string_view::npos)
+ return;
+
+ std::u16string_view sName(rFontName.substr(++nPrefixIdx));
+ sal_Int32 nIndex = 0;
+ do
+ {
+ std::u16string_view sToken = o3tl::getToken(sName, 0, vcl::font::FeatureSeparator, nIndex);
+
+ sal_Int32 nInnerIdx{ 0 };
+ std::u16string_view sID = o3tl::getToken(sToken, 0, '=', nInnerIdx);
+
+ if (sID == u"lang")
+ {
+ m_sLanguage = o3tl::getToken(sToken, 0, '=', nInnerIdx);
+ }
+ else
+ {
+ OString sFeature = OUStringToOString(sToken, RTL_TEXTENCODING_ASCII_US);
+ FeatureSetting aFeature(sFeature);
+ if (aFeature.m_nTag != 0)
+ m_aFeatures.push_back(aFeature);
+ }
+ } while (nIndex >= 0);
+}
+
+std::unordered_map<uint32_t, int32_t> FeatureParser::getFeaturesMap() const
+{
+ std::unordered_map<uint32_t, int32_t> aResultMap;
+ for (auto const& rFeat : m_aFeatures)
+ aResultMap.emplace(rFeat.m_nTag, rFeat.m_nValue);
+ return aResultMap;
+}
+
+} // end vcl::font namespace
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/FontSelectPattern.cxx b/vcl/source/font/FontSelectPattern.cxx
new file mode 100644
index 0000000000..30c2c9aaa5
--- /dev/null
+++ b/vcl/source/font/FontSelectPattern.cxx
@@ -0,0 +1,156 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+#include <o3tl/safeint.hxx>
+#include <tools/gen.hxx>
+
+#include <utility>
+#include <vcl/font.hxx>
+
+#include <font/FontSelectPattern.hxx>
+#include <font/PhysicalFontFace.hxx>
+
+namespace vcl::font
+{
+
+// These mustn't conflict with font name lists which use ; and ,
+const char FontSelectPattern::FEAT_PREFIX = ':';
+const char FontSelectPattern::FEAT_SEPARATOR = '&';
+
+FontSelectPattern::FontSelectPattern( const vcl::Font& rFont,
+ OUString aSearchName, const Size& rSize, float fExactHeight, bool bNonAntialias)
+ : maSearchName(std::move( aSearchName ))
+ , mnWidth( rSize.Width() )
+ , mnHeight( rSize.Height() )
+ , mfExactHeight( fExactHeight)
+ , mnOrientation( rFont.GetOrientation() )
+ , meLanguage( rFont.GetLanguage() )
+ , mbVertical( rFont.IsVertical() )
+ , mbNonAntialiased(bNonAntialias)
+ , mbEmbolden( false )
+{
+ maTargetName = GetFamilyName();
+
+ rFont.GetFontAttributes( *this );
+
+ // normalize orientation between 0 and 3600
+ if( mnOrientation < 0_deg10 || mnOrientation >= 3600_deg10 )
+ {
+ if( mnOrientation >= 0_deg10 )
+ mnOrientation %= 3600_deg10;
+ else
+ mnOrientation = 3600_deg10 - (-mnOrientation % 3600_deg10);
+ }
+
+ // normalize width and height
+ if( mnHeight < 0 )
+ mnHeight = o3tl::saturating_toggle_sign(mnHeight);
+ if( mnWidth < 0 )
+ mnWidth = o3tl::saturating_toggle_sign(mnWidth);
+}
+
+
+// NOTE: this ctor is still used on Windows. Do not remove.
+#ifdef _WIN32
+FontSelectPattern::FontSelectPattern( const PhysicalFontFace& rFontData,
+ const Size& rSize, float fExactHeight, int nOrientation, bool bVertical )
+ : FontAttributes( rFontData )
+ , mnWidth( rSize.Width() )
+ , mnHeight( rSize.Height() )
+ , mfExactHeight( fExactHeight )
+ , mnOrientation( nOrientation )
+ , meLanguage( 0 )
+ , mbVertical( bVertical )
+ , mbNonAntialiased( false )
+ , mbEmbolden( false )
+{
+ maTargetName = maSearchName = GetFamilyName();
+ // NOTE: no normalization for width/height/orientation
+}
+
+#endif
+
+size_t FontSelectPattern::hashCode() const
+{
+ // TODO: does it pay off to improve this hash function?
+ size_t nHash;
+ // check for features and generate a unique hash if necessary
+ if (maTargetName.indexOf(FontSelectPattern::FEAT_PREFIX)
+ != -1)
+ {
+ nHash = maTargetName.hashCode();
+ }
+ else
+ {
+ nHash = maSearchName.hashCode();
+ }
+ nHash += 11U * mnHeight;
+ nHash += 19 * GetWeight();
+ nHash += 29 * GetItalic();
+ nHash += 37 * mnOrientation.get();
+ nHash += 41 * static_cast<sal_uInt16>(meLanguage);
+ if( mbVertical )
+ nHash += 53;
+ return nHash;
+}
+
+bool FontSelectPattern::operator==(const FontSelectPattern& rOther) const
+{
+ if (!CompareDeviceIndependentFontAttributes(rOther))
+ return false;
+
+ if (maTargetName != rOther.maTargetName)
+ return false;
+
+ if (maSearchName != rOther.maSearchName)
+ return false;
+
+ if (mnWidth != rOther.mnWidth)
+ return false;
+
+ if (mnHeight != rOther.mnHeight)
+ return false;
+
+ if (mfExactHeight != rOther.mfExactHeight)
+ return false;
+
+ if (mnOrientation != rOther.mnOrientation)
+ return false;
+
+ if (meLanguage != rOther.meLanguage)
+ return false;
+
+ if (mbVertical != rOther.mbVertical)
+ return false;
+
+ if (mbNonAntialiased != rOther.mbNonAntialiased)
+ return false;
+
+ if (mbEmbolden != rOther.mbEmbolden)
+ return false;
+
+ if (maItalicMatrix != rOther.maItalicMatrix)
+ return false;
+
+ return true;
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/LogicalFontInstance.cxx b/vcl/source/font/LogicalFontInstance.cxx
new file mode 100644
index 0000000000..0c21cba475
--- /dev/null
+++ b/vcl/source/font/LogicalFontInstance.cxx
@@ -0,0 +1,348 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <hb-ot.h>
+#include <hb-graphite2.h>
+
+#include <font/PhysicalFontFace.hxx>
+#include <font/LogicalFontInstance.hxx>
+#include <impfontcache.hxx>
+
+LogicalFontInstance::LogicalFontInstance(const vcl::font::PhysicalFontFace& rFontFace,
+ const vcl::font::FontSelectPattern& rFontSelData)
+ : mxFontMetric(new FontMetricData(rFontSelData))
+ , mpConversion(nullptr)
+ , mnLineHeight(0)
+ , mnOwnOrientation(0)
+ , mnOrientation(0)
+ , mbInit(false)
+ , mpFontCache(nullptr)
+ , m_aFontSelData(rFontSelData)
+ , m_pHbFont(nullptr)
+ , m_nAveWidthFactor(1.0f)
+ , m_pFontFace(&const_cast<vcl::font::PhysicalFontFace&>(rFontFace))
+{
+}
+
+LogicalFontInstance::~LogicalFontInstance()
+{
+ maUnicodeFallbackList.clear();
+ mpFontCache = nullptr;
+ mxFontMetric = nullptr;
+
+ if (m_pHbFont)
+ hb_font_destroy(m_pHbFont);
+
+ if (m_pHbFontUntransformed)
+ hb_font_destroy(m_pHbFontUntransformed);
+
+ if (m_pHbDrawFuncs)
+ hb_draw_funcs_destroy(m_pHbDrawFuncs);
+}
+
+hb_font_t* LogicalFontInstance::InitHbFont()
+{
+ auto pFace = GetFontFace();
+ hb_face_t* pHbFace = pFace->GetHbFace();
+ assert(pHbFace);
+ auto nUPEM = pFace->UnitsPerEm();
+
+ hb_font_t* pHbFont = hb_font_create(pHbFace);
+ hb_font_set_scale(pHbFont, nUPEM, nUPEM);
+ hb_ot_font_set_funcs(pHbFont);
+
+ auto aVariations = pFace->GetVariations(*this);
+ if (!aVariations.empty())
+ hb_font_set_variations(pHbFont, aVariations.data(), aVariations.size());
+
+ // If we are applying artificial italic, instruct HarfBuzz to do the same
+ // so that mark positioning is also transformed.
+ if (NeedsArtificialItalic())
+ hb_font_set_synthetic_slant(pHbFont, ARTIFICIAL_ITALIC_SKEW);
+
+ ImplInitHbFont(pHbFont);
+
+ return pHbFont;
+}
+
+hb_font_t* LogicalFontInstance::GetHbFontUntransformed() const
+{
+ auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont();
+
+ if (NeedsArtificialItalic()) // || NeedsArtificialBold()
+ {
+ if (!m_pHbFontUntransformed)
+ {
+ m_pHbFontUntransformed = hb_font_create_sub_font(pHbFont);
+ // Unset slant set on parent font.
+ // Does not actually work: https://github.com/harfbuzz/harfbuzz/issues/3890
+ hb_font_set_synthetic_slant(m_pHbFontUntransformed, 0);
+ }
+ return m_pHbFontUntransformed;
+ }
+
+ return pHbFont;
+}
+
+double LogicalFontInstance::GetKashidaWidth() const
+{
+ sal_GlyphId nGlyph = GetGlyphIndex(0x0640);
+ if (nGlyph)
+ return GetGlyphWidth(nGlyph);
+ return 0;
+}
+
+void LogicalFontInstance::GetScale(double* nXScale, double* nYScale) const
+{
+ double nUPEM = GetFontFace()->UnitsPerEm();
+ double nHeight(m_aFontSelData.mnHeight);
+
+ // On Windows, mnWidth is relative to average char width not font height,
+ // and we need to keep it that way for GDI to correctly scale the glyphs.
+ // Here we compensate for this so that HarfBuzz gives us the correct glyph
+ // positions.
+ double nWidth(m_aFontSelData.mnWidth ? m_aFontSelData.mnWidth * m_nAveWidthFactor : nHeight);
+
+ if (nYScale)
+ *nYScale = nHeight / nUPEM;
+
+ if (nXScale)
+ *nXScale = nWidth / nUPEM;
+}
+
+void LogicalFontInstance::AddFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight,
+ const OUString& rFontName, bool bEmbolden,
+ const ItalicMatrix& rMatrix)
+{
+ MapEntry& rEntry = maUnicodeFallbackList[std::pair<sal_UCS4, FontWeight>(cChar, eWeight)];
+ rEntry.sFontName = rFontName;
+ rEntry.bEmbolden = bEmbolden;
+ rEntry.aItalicMatrix = rMatrix;
+}
+
+bool LogicalFontInstance::GetFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight,
+ OUString* pFontName, bool* pEmbolden,
+ ItalicMatrix* pMatrix) const
+{
+ UnicodeFallbackList::const_iterator it
+ = maUnicodeFallbackList.find(std::pair<sal_UCS4, FontWeight>(cChar, eWeight));
+ if (it == maUnicodeFallbackList.end())
+ return false;
+
+ const MapEntry& rEntry = (*it).second;
+ *pFontName = rEntry.sFontName;
+ *pEmbolden = rEntry.bEmbolden;
+ *pMatrix = rEntry.aItalicMatrix;
+ return true;
+}
+
+void LogicalFontInstance::IgnoreFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight,
+ std::u16string_view rFontName)
+{
+ UnicodeFallbackList::iterator it
+ = maUnicodeFallbackList.find(std::pair<sal_UCS4, FontWeight>(cChar, eWeight));
+ if (it == maUnicodeFallbackList.end())
+ return;
+ const MapEntry& rEntry = (*it).second;
+ if (rEntry.sFontName == rFontName)
+ maUnicodeFallbackList.erase(it);
+}
+
+bool LogicalFontInstance::GetGlyphBoundRect(sal_GlyphId nID, tools::Rectangle& rRect,
+ bool bVertical) const
+{
+ if (mpFontCache && mpFontCache->GetCachedGlyphBoundRect(this, nID, rRect))
+ return true;
+
+ auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont();
+ hb_glyph_extents_t aExtents;
+ bool res = hb_font_get_glyph_extents(pHbFont, nID, &aExtents);
+
+ if (res)
+ {
+ double nXScale = 0, nYScale = 0;
+ GetScale(&nXScale, &nYScale);
+
+ double fMinX = aExtents.x_bearing;
+ double fMinY = aExtents.y_bearing;
+ double fMaxX = aExtents.x_bearing + aExtents.width;
+ double fMaxY = aExtents.y_bearing + aExtents.height;
+
+ tools::Rectangle aRect(std::floor(fMinX * nXScale), -std::ceil(fMinY * nYScale),
+ std::ceil(fMaxX * nXScale), -std::floor(fMaxY * nYScale));
+ if (mnOrientation && !bVertical)
+ {
+ // Apply font rotation.
+ const double fRad = toRadians(mnOrientation);
+ const double fCos = cos(fRad);
+ const double fSin = sin(fRad);
+
+ rRect.SetLeft(fCos * aRect.Left() + fSin * aRect.Top());
+ rRect.SetTop(-fSin * aRect.Left() - fCos * aRect.Top());
+ rRect.SetRight(fCos * aRect.Right() + fSin * aRect.Bottom());
+ rRect.SetBottom(-fSin * aRect.Right() - fCos * aRect.Bottom());
+ }
+ else
+ rRect = aRect;
+ }
+
+ if (mpFontCache && res)
+ mpFontCache->CacheGlyphBoundRect(this, nID, rRect);
+ return res;
+}
+
+sal_GlyphId LogicalFontInstance::GetGlyphIndex(uint32_t nUnicode, uint32_t nVariationSelector) const
+{
+ auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont();
+ sal_GlyphId nGlyph = 0;
+ if (hb_font_get_glyph(pHbFont, nUnicode, nVariationSelector, &nGlyph))
+ return nGlyph;
+ return 0;
+}
+
+double LogicalFontInstance::GetGlyphWidth(sal_GlyphId nGlyph, bool bVertical, bool bScale) const
+{
+ auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont();
+ int nWidth;
+ if (bVertical)
+ nWidth = hb_font_get_glyph_v_advance(pHbFont, nGlyph);
+ else
+ nWidth = hb_font_get_glyph_h_advance(pHbFont, nGlyph);
+
+ if (!bScale)
+ return nWidth;
+
+ double nScale = 0;
+ GetScale(&nScale, nullptr);
+ return double(nWidth * nScale);
+}
+
+bool LogicalFontInstance::IsGraphiteFont()
+{
+ if (!m_xbIsGraphiteFont.has_value())
+ {
+ m_xbIsGraphiteFont
+ = hb_graphite2_face_get_gr_face(hb_font_get_face(GetHbFont())) != nullptr;
+ }
+ return *m_xbIsGraphiteFont;
+}
+
+bool LogicalFontInstance::NeedOffsetCorrection(sal_Int32 nYOffset)
+{
+ if (!m_xeFontFamilyEnum)
+ {
+ m_xeFontFamilyEnum = FontFamilyEnum::Unclassified;
+
+ // DFKai-SB (ukai.ttf) is a built-in font under traditional Chinese
+ // Windows. It has wrong extent values in glyf table. The problem results
+ // in wrong positioning of glyphs in vertical writing.
+ // Check https://github.com/harfbuzz/harfbuzz/issues/3521 for reference.
+ if (GetFontFace()->GetName(vcl::font::NAME_ID_FONT_FAMILY) == "DFKai-SB")
+ m_xeFontFamilyEnum = FontFamilyEnum::DFKaiSB;
+ }
+
+ bool bRet = true;
+
+ switch (*m_xeFontFamilyEnum)
+ {
+ case FontFamilyEnum::DFKaiSB:
+ // -839: optimization for one third of ukai.ttf
+ if (nYOffset == -839)
+ bRet = false;
+ break;
+ default:
+ bRet = false;
+ }
+
+ return bRet;
+}
+
+bool LogicalFontInstance::NeedsArtificialBold() const
+{
+ return m_aFontSelData.GetWeight() > WEIGHT_MEDIUM && m_pFontFace->GetWeight() <= WEIGHT_MEDIUM;
+}
+
+bool LogicalFontInstance::NeedsArtificialItalic() const
+{
+ return m_aFontSelData.GetItalic() != ITALIC_NONE && m_pFontFace->GetItalic() == ITALIC_NONE;
+}
+
+namespace
+{
+void move_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float to_x, float to_y,
+ void* pUserData)
+{
+ auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData);
+ pPoly->append(basegfx::B2DPoint(to_x, -to_y));
+}
+
+void line_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float to_x, float to_y,
+ void* pUserData)
+{
+ auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData);
+ pPoly->append(basegfx::B2DPoint(to_x, -to_y));
+}
+
+void cubic_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float control1_x,
+ float control1_y, float control2_x, float control2_y, float to_x, float to_y,
+ void* pUserData)
+{
+ auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData);
+ pPoly->appendBezierSegment(basegfx::B2DPoint(control1_x, -control1_y),
+ basegfx::B2DPoint(control2_x, -control2_y),
+ basegfx::B2DPoint(to_x, -to_y));
+}
+
+void close_path_func(hb_draw_funcs_t*, void* pDrawData, hb_draw_state_t*, void* pUserData)
+{
+ auto pPolyPoly = static_cast<basegfx::B2DPolyPolygon*>(pDrawData);
+ auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData);
+ pPolyPoly->append(*pPoly);
+ pPoly->clear();
+}
+}
+
+basegfx::B2DPolyPolygon LogicalFontInstance::GetGlyphOutlineUntransformed(sal_GlyphId nGlyph) const
+{
+ if (!m_pHbDrawFuncs)
+ {
+ m_pHbDrawFuncs = hb_draw_funcs_create();
+ auto pUserData = const_cast<basegfx::B2DPolygon*>(&m_aDrawPolygon);
+ hb_draw_funcs_set_move_to_func(m_pHbDrawFuncs, move_to_func, pUserData, nullptr);
+ hb_draw_funcs_set_line_to_func(m_pHbDrawFuncs, line_to_func, pUserData, nullptr);
+ hb_draw_funcs_set_cubic_to_func(m_pHbDrawFuncs, cubic_to_func, pUserData, nullptr);
+ // B2DPolyPolygon does not support quadratic curves, HarfBuzz will
+ // convert them to cubic curves for us if we don’t set a callback
+ // function.
+ //hb_draw_funcs_set_quadratic_to_func(m_pHbDrawFuncs, quadratic_to_func, pUserData, nullptr);
+ hb_draw_funcs_set_close_path_func(m_pHbDrawFuncs, close_path_func, pUserData, nullptr);
+ }
+
+ basegfx::B2DPolyPolygon aPolyPoly;
+#if HB_VERSION_ATLEAST(7, 0, 0)
+ hb_font_draw_glyph(GetHbFontUntransformed(), nGlyph, m_pHbDrawFuncs, &aPolyPoly);
+#else
+ hb_font_get_glyph_shape(GetHbFontUntransformed(), nGlyph, m_pHbDrawFuncs, &aPolyPoly);
+#endif
+ return aPolyPoly;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/OpenTypeFeatureDefinitionList.cxx b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx
new file mode 100644
index 0000000000..0400833937
--- /dev/null
+++ b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx
@@ -0,0 +1,159 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ */
+
+#include <font/OpenTypeFeatureDefinitionList.hxx>
+#include <font/OpenTypeFeatureStrings.hrc>
+
+#include <rtl/character.hxx>
+
+#include <algorithm>
+
+namespace vcl::font
+{
+OpenTypeFeatureDefinitionListPrivate& OpenTypeFeatureDefinitionList()
+{
+ static OpenTypeFeatureDefinitionListPrivate SINGLETON;
+ return SINGLETON;
+};
+
+OpenTypeFeatureDefinitionListPrivate::OpenTypeFeatureDefinitionListPrivate() { init(); }
+
+void OpenTypeFeatureDefinitionListPrivate::init()
+{
+ m_aFeatureDefinition.assign({
+ { featureCode("aalt"), STR_FONT_FEATURE_ID_AALT },
+ { featureCode("afrc"), STR_FONT_FEATURE_ID_AFRC },
+ { featureCode("alig"), STR_FONT_FEATURE_ID_ALIG },
+ { featureCode("c2pc"), STR_FONT_FEATURE_ID_C2PC },
+ { featureCode("c2sc"), STR_FONT_FEATURE_ID_C2SC },
+ { featureCode("calt"), STR_FONT_FEATURE_ID_CALT },
+ { featureCode("case"), STR_FONT_FEATURE_ID_CASE },
+ { featureCode("clig"), STR_FONT_FEATURE_ID_CLIG },
+ { featureCode("cpct"), STR_FONT_FEATURE_ID_CPCT },
+ { featureCode("cpsp"), STR_FONT_FEATURE_ID_CPSP },
+ { featureCode("cswh"), STR_FONT_FEATURE_ID_CSWH },
+ { featureCode("dcap"), STR_FONT_FEATURE_ID_DCAP },
+ { featureCode("dlig"), STR_FONT_FEATURE_ID_DLIG },
+ { featureCode("dnom"), STR_FONT_FEATURE_ID_DNOM },
+ { featureCode("dpng"), STR_FONT_FEATURE_ID_DPNG },
+ { featureCode("expt"), STR_FONT_FEATURE_ID_EXPT },
+ { featureCode("falt"), STR_FONT_FEATURE_ID_FALT },
+ { featureCode("frac"), STR_FONT_FEATURE_ID_FRAC },
+ { featureCode("fwid"), STR_FONT_FEATURE_ID_FWID },
+ { featureCode("halt"), STR_FONT_FEATURE_ID_HALT },
+ { featureCode("hist"), STR_FONT_FEATURE_ID_HIST },
+ { featureCode("hkna"), STR_FONT_FEATURE_ID_HKNA },
+ { featureCode("hlig"), STR_FONT_FEATURE_ID_HLIG },
+ { featureCode("hngl"), STR_FONT_FEATURE_ID_HNGL },
+ { featureCode("hojo"), STR_FONT_FEATURE_ID_HOJO },
+ { featureCode("hwid"), STR_FONT_FEATURE_ID_HWID },
+ { featureCode("ital"), STR_FONT_FEATURE_ID_ITAL },
+ { featureCode("jalt"), STR_FONT_FEATURE_ID_JALT },
+ { featureCode("jp78"), STR_FONT_FEATURE_ID_JP78 },
+ { featureCode("jp83"), STR_FONT_FEATURE_ID_JP83 },
+ { featureCode("jp90"), STR_FONT_FEATURE_ID_JP90 },
+ { featureCode("jp04"), STR_FONT_FEATURE_ID_JP04 },
+ { featureCode("kern"), STR_FONT_FEATURE_ID_KERN },
+ { featureCode("lfbd"), STR_FONT_FEATURE_ID_LFBD },
+ { featureCode("liga"), STR_FONT_FEATURE_ID_LIGA },
+ { featureCode("lnum"), STR_FONT_FEATURE_ID_LNUM },
+ { featureCode("mgrk"), STR_FONT_FEATURE_ID_MGRK },
+ { featureCode("nalt"), STR_FONT_FEATURE_ID_NALT },
+ { featureCode("nlck"), STR_FONT_FEATURE_ID_NLCK },
+ { featureCode("numr"), STR_FONT_FEATURE_ID_NUMR },
+ { featureCode("onum"), STR_FONT_FEATURE_ID_ONUM },
+ { featureCode("opbd"), STR_FONT_FEATURE_ID_OPBD },
+ { featureCode("ordn"), STR_FONT_FEATURE_ID_ORDN },
+ { featureCode("ornm"), STR_FONT_FEATURE_ID_ORNM },
+ { featureCode("palt"), STR_FONT_FEATURE_ID_PALT },
+ { featureCode("pcap"), STR_FONT_FEATURE_ID_PCAP },
+ { featureCode("pkna"), STR_FONT_FEATURE_ID_PKNA },
+ { featureCode("pnum"), STR_FONT_FEATURE_ID_PNUM },
+ { featureCode("pwid"), STR_FONT_FEATURE_ID_PWID },
+ { featureCode("qwid"), STR_FONT_FEATURE_ID_QWID },
+ { featureCode("rtbd"), STR_FONT_FEATURE_ID_RTBD },
+ { featureCode("ruby"), STR_FONT_FEATURE_ID_RUBY },
+ { featureCode("salt"), STR_FONT_FEATURE_ID_SALT },
+ { featureCode("sinf"), STR_FONT_FEATURE_ID_SINF },
+ { featureCode("smcp"), STR_FONT_FEATURE_ID_SMCP },
+ { featureCode("smpl"), STR_FONT_FEATURE_ID_SMPL },
+ { featureCode("subs"), STR_FONT_FEATURE_ID_SUBS },
+ { featureCode("sups"), STR_FONT_FEATURE_ID_SUPS },
+ { featureCode("swsh"), STR_FONT_FEATURE_ID_SWSH },
+ { featureCode("titl"), STR_FONT_FEATURE_ID_TITL },
+ { featureCode("tnam"), STR_FONT_FEATURE_ID_TNAM },
+ { featureCode("tnum"), STR_FONT_FEATURE_ID_TNUM },
+ { featureCode("trad"), STR_FONT_FEATURE_ID_TRAD },
+ { featureCode("twid"), STR_FONT_FEATURE_ID_TWID },
+ { featureCode("unic"), STR_FONT_FEATURE_ID_UNIC },
+ { featureCode("valt"), STR_FONT_FEATURE_ID_VALT },
+ { featureCode("vhal"), STR_FONT_FEATURE_ID_VHAL },
+ { featureCode("vkna"), STR_FONT_FEATURE_ID_VKNA },
+ { featureCode("vkrn"), STR_FONT_FEATURE_ID_VKRN },
+ { featureCode("vpal"), STR_FONT_FEATURE_ID_VPAL },
+ { featureCode("vrt2"), STR_FONT_FEATURE_ID_VRT2 },
+ { featureCode("vrtr"), STR_FONT_FEATURE_ID_VRTR },
+ { featureCode("zero"), STR_FONT_FEATURE_ID_ZERO },
+ });
+
+ for (size_t i = 0; i < m_aFeatureDefinition.size(); ++i)
+ {
+ m_aCodeToIndex.emplace(m_aFeatureDefinition[i].getCode(), i);
+ }
+
+ m_aRequiredFeatures.assign({
+ featureCode("abvf"), featureCode("abvm"), featureCode("abvs"), featureCode("akhn"),
+ featureCode("blwf"), featureCode("blwm"), featureCode("blws"), featureCode("ccmp"),
+ featureCode("cfar"), featureCode("cjct"), featureCode("curs"), featureCode("dist"),
+ featureCode("dtls"), featureCode("fin2"), featureCode("fin3"), featureCode("fina"),
+ featureCode("flac"), featureCode("half"), featureCode("haln"), featureCode("init"),
+ featureCode("isol"), featureCode("ljmo"), featureCode("locl"), featureCode("ltra"),
+ featureCode("ltrm"), featureCode("mark"), featureCode("med2"), featureCode("medi"),
+ featureCode("mkmk"), featureCode("mset"), featureCode("nukt"), featureCode("pref"),
+ featureCode("pres"), featureCode("pstf"), featureCode("psts"), featureCode("rand"),
+ featureCode("rclt"), featureCode("rkrf"), featureCode("rlig"), featureCode("rphf"),
+ featureCode("rtla"), featureCode("rtlm"), featureCode("rvrn"), featureCode("size"),
+ featureCode("ssty"), featureCode("stch"), featureCode("tjmo"), featureCode("vatu"),
+ featureCode("vert"), featureCode("vjmo"),
+ });
+}
+
+FeatureDefinition OpenTypeFeatureDefinitionListPrivate::getDefinition(vcl::font::Feature& rFeature)
+{
+ if (rFeature.isCharacterVariant() || rFeature.isStylisticSet())
+ {
+ FeatureDefinition aFeatureDefinition;
+ OUString sNumericPart = OUStringChar(char((rFeature.m_nCode >> 8) & 0xFF))
+ + OUStringChar(char((rFeature.m_nCode >> 0) & 0xFF));
+ if (rFeature.isCharacterVariant())
+ aFeatureDefinition = { rFeature.m_nCode, STR_FONT_FEATURE_ID_CVXX, sNumericPart };
+ else if (rFeature.isStylisticSet())
+ aFeatureDefinition = { rFeature.m_nCode, STR_FONT_FEATURE_ID_SSXX, sNumericPart };
+ return aFeatureDefinition;
+ }
+
+ auto nFeatureCode = rFeature.m_nCode;
+ if (m_aCodeToIndex.find(nFeatureCode) != m_aCodeToIndex.end())
+ {
+ size_t nIndex = m_aCodeToIndex.at(nFeatureCode);
+ return m_aFeatureDefinition[nIndex];
+ }
+ return FeatureDefinition();
+}
+
+bool OpenTypeFeatureDefinitionListPrivate::isRequired(sal_uInt32 nFeatureCode)
+{
+ return std::find(m_aRequiredFeatures.begin(), m_aRequiredFeatures.end(), nFeatureCode)
+ != m_aRequiredFeatures.end();
+}
+
+} // end vcl::font namespace
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/PhysicalFontCollection.cxx b/vcl/source/font/PhysicalFontCollection.cxx
new file mode 100644
index 0000000000..04b031ad6b
--- /dev/null
+++ b/vcl/source/font/PhysicalFontCollection.cxx
@@ -0,0 +1,1279 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <memory>
+
+#include <i18nlangtag/languagetag.hxx>
+#include <i18nlangtag/mslangid.hxx>
+#include <unotools/configmgr.hxx>
+#include <unotools/fontdefs.hxx>
+#include <o3tl/sorted_vector.hxx>
+
+#include <font/PhysicalFontFaceCollection.hxx>
+#include <font/PhysicalFontCollection.hxx>
+#include <font/fontsubstitution.hxx>
+
+static ImplFontAttrs lcl_IsCJKFont( std::u16string_view rFontName )
+{
+ // Test, if Fontname includes CJK characters --> In this case we
+ // mention that it is a CJK font
+ for(size_t i = 0; i < rFontName.size(); i++)
+ {
+ const sal_Unicode ch = rFontName[i];
+ // japanese
+ if ( ((ch >= 0x3040) && (ch <= 0x30FF)) ||
+ ((ch >= 0x3190) && (ch <= 0x319F)) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_JP;
+
+ // korean
+ if ( ((ch >= 0xAC00) && (ch <= 0xD7AF)) ||
+ ((ch >= 0xA960) && (ch <= 0xA97F)) ||
+ ((ch >= 0xD7B0) && (ch <= 0xD7FF)) ||
+ ((ch >= 0x3130) && (ch <= 0x318F)) ||
+ ((ch >= 0x1100) && (ch <= 0x11FF)) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_KR;
+
+ // chinese
+ if ( (ch >= 0x3400) && (ch <= 0x9FFF) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_TC|ImplFontAttrs::CJK_SC;
+
+ // cjk
+ if ( ((ch >= 0x3000) && (ch <= 0xD7AF)) ||
+ ((ch >= 0xFF00) && (ch <= 0xFFEE)) )
+ return ImplFontAttrs::CJK;
+
+ }
+
+ return ImplFontAttrs::None;
+}
+
+namespace vcl::font
+{
+
+PhysicalFontCollection::PhysicalFontCollection()
+ : mbMatchData( false )
+ , mpPreMatchHook( nullptr )
+ , mpFallbackHook( nullptr )
+ , mnFallbackCount( -1 )
+{}
+
+PhysicalFontCollection::~PhysicalFontCollection()
+{
+ Clear();
+}
+
+void PhysicalFontCollection::SetPreMatchHook(PreMatchFontSubstitution* pHook)
+{
+ mpPreMatchHook = pHook;
+}
+
+void PhysicalFontCollection::SetFallbackHook(GlyphFallbackFontSubstitution* pHook)
+{
+ mpFallbackHook = pHook;
+}
+
+void PhysicalFontCollection::Clear()
+{
+ // remove fallback lists
+ mpFallbackList.reset();
+ mnFallbackCount = -1;
+
+ // clear all entries in the device font list
+ maPhysicalFontFamilies.clear();
+
+ // match data must be recalculated too
+ mbMatchData = false;
+}
+
+void PhysicalFontCollection::ImplInitGenericGlyphFallback() const
+{
+ // normalized family names of fonts suited for glyph fallback
+ // if a font is available related fonts can be ignored
+ // TODO: implement dynamic lists
+ static const char* aGlyphFallbackList[] = {
+ // empty strings separate the names of unrelated fonts
+ "eudc", "",
+ "arialunicodems", "cyberbit", "code2000", "",
+ "andalesansui", "",
+ "starsymbol", "opensymbol", "",
+ "msmincho", "fzmingti", "fzheiti", "ipamincho", "sazanamimincho", "kochimincho", "",
+ "sunbatang", "sundotum", "baekmukdotum", "gulim", "batang", "dotum", "",
+ "hgmincholightj", "msunglightsc", "msunglighttc", "hymyeongjolightk", "",
+ "tahoma", "dejavusans", "timesnewroman", "liberationsans", "",
+ "shree", "mangal", "",
+ "raavi", "shruti", "tunga", "",
+ "latha", "gautami", "kartika", "vrinda", "",
+ "shayyalmt", "naskmt", "scheherazade", "",
+ "david", "nachlieli", "lucidagrande", "",
+ "norasi", "angsanaupc", "",
+ "khmerossystem", "",
+ "muktinarrow", "",
+ "phetsarathot", "",
+ "padauk", "pinlonmyanmar", "",
+ "iskoolapota", "lklug", "",
+ nullptr
+ };
+
+ bool bHasEudc = false;
+ int nMaxLevel = 0;
+ int nBestQuality = 0;
+ std::unique_ptr<std::array<PhysicalFontFamily*,MAX_GLYPHFALLBACK>> pFallbackList;
+
+ for( const char** ppNames = &aGlyphFallbackList[0];; ++ppNames )
+ {
+ // advance to next sub-list when end-of-sublist marker
+ if( !**ppNames ) // #i46456# check for empty string, i.e., deref string itself not only ptr to it
+ {
+ if( nBestQuality > 0 )
+ if( ++nMaxLevel >= MAX_GLYPHFALLBACK )
+ break;
+
+ if( !ppNames[1] )
+ break;
+
+ nBestQuality = 0;
+ continue;
+ }
+
+ // test if the glyph fallback candidate font is available and scalable
+ OUString aTokenName( *ppNames, strlen(*ppNames), RTL_TEXTENCODING_UTF8 );
+ PhysicalFontFamily* pFallbackFont = FindFontFamily( aTokenName );
+
+ if( !pFallbackFont )
+ continue;
+
+ // keep the best font of the glyph fallback sub-list
+ if( nBestQuality < pFallbackFont->GetMinQuality() )
+ {
+ nBestQuality = pFallbackFont->GetMinQuality();
+ // store available glyph fallback fonts
+ if( !pFallbackList )
+ pFallbackList.reset(new std::array<PhysicalFontFamily*,MAX_GLYPHFALLBACK>);
+
+ (*pFallbackList)[ nMaxLevel ] = pFallbackFont;
+ if( !bHasEudc && !nMaxLevel )
+ bHasEudc = !strncmp( *ppNames, "eudc", 5 );
+ }
+ }
+
+ mnFallbackCount = nMaxLevel;
+ mpFallbackList = std::move(pFallbackList);
+}
+
+PhysicalFontFamily* PhysicalFontCollection::GetGlyphFallbackFont(FontSelectPattern& rFontSelData,
+ LogicalFontInstance* pFontInstance,
+ OUString& rMissingCodes,
+ int nFallbackLevel) const
+{
+ PhysicalFontFamily* pFallbackData = nullptr;
+
+ // find a matching font candidate for platform specific glyph fallback
+ if( mpFallbackHook )
+ {
+ // check cache for the first matching entry
+ // to avoid calling the expensive fallback hook (#i83491#)
+ sal_UCS4 cChar = 0;
+ bool bCached = true;
+ sal_Int32 nStrIndex = 0;
+ while( nStrIndex < rMissingCodes.getLength() )
+ {
+ cChar = rMissingCodes.iterateCodePoints( &nStrIndex );
+ bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(),
+ &rFontSelData.maSearchName,
+ &rFontSelData.mbEmbolden,
+ &rFontSelData.maItalicMatrix);
+
+ // ignore entries which don't have a fallback
+ if( !bCached || !rFontSelData.maSearchName.isEmpty() )
+ break;
+ }
+
+ if( bCached )
+ {
+ // there is a matching fallback in the cache
+ // so update rMissingCodes with codepoints not yet resolved by this fallback
+ int nRemainingLength = 0;
+ std::unique_ptr<sal_UCS4[]> const pRemainingCodes(new sal_UCS4[rMissingCodes.getLength()]);
+ OUString aFontName;
+ bool bEmbolden;
+ ItalicMatrix aMatrix;
+
+ while( nStrIndex < rMissingCodes.getLength() )
+ {
+ cChar = rMissingCodes.iterateCodePoints( &nStrIndex );
+ bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(),
+ &aFontName, &bEmbolden, &aMatrix);
+ if (!bCached || rFontSelData.maSearchName != aFontName ||
+ rFontSelData.mbEmbolden != bEmbolden ||
+ rFontSelData.maItalicMatrix != aMatrix)
+ {
+ pRemainingCodes[ nRemainingLength++ ] = cChar;
+ }
+ }
+ rMissingCodes = OUString( pRemainingCodes.get(), nRemainingLength );
+ }
+ else
+ {
+ OUString aOldMissingCodes = rMissingCodes;
+
+ // call the hook to query the best matching glyph fallback font
+ if (mpFallbackHook->FindFontSubstitute(rFontSelData, pFontInstance, rMissingCodes))
+ // apply outdev3.cxx specific fontname normalization
+ rFontSelData.maSearchName = GetEnglishSearchFontName( rFontSelData.maSearchName );
+ else
+ rFontSelData.maSearchName.clear();
+
+ // Cache the result even if there was no match
+ // See tdf#32665 and tdf#147283 for an example where FreeSerif that has glyphs that exist
+ // in the bold font, but not in the bold+italic version where fontconfig suggest the bold
+ // font + applying a matrix to fake the missing italic.
+ for(;;)
+ {
+ if (!pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(),
+ &rFontSelData.maSearchName,
+ &rFontSelData.mbEmbolden,
+ &rFontSelData.maItalicMatrix))
+ {
+ pFontInstance->AddFallbackForUnicode(cChar, rFontSelData.GetWeight(),
+ rFontSelData.maSearchName,
+ rFontSelData.mbEmbolden,
+ rFontSelData.maItalicMatrix);
+ }
+ if( nStrIndex >= aOldMissingCodes.getLength() )
+ break;
+ cChar = aOldMissingCodes.iterateCodePoints( &nStrIndex );
+ }
+ if( !rFontSelData.maSearchName.isEmpty() )
+ {
+ // remove cache entries that were still not resolved
+ for( nStrIndex = 0; nStrIndex < rMissingCodes.getLength(); )
+ {
+ cChar = rMissingCodes.iterateCodePoints( &nStrIndex );
+ pFontInstance->IgnoreFallbackForUnicode( cChar, rFontSelData.GetWeight(), rFontSelData.maSearchName );
+ }
+ }
+ }
+
+ // find the matching device font
+ if( !rFontSelData.maSearchName.isEmpty() )
+ pFallbackData = FindFontFamily( rFontSelData.maSearchName );
+ }
+
+ // else find a matching font candidate for generic glyph fallback
+ if( !pFallbackData )
+ {
+ // initialize font candidates for generic glyph fallback if needed
+ if( mnFallbackCount < 0 )
+ ImplInitGenericGlyphFallback();
+
+ // TODO: adjust nFallbackLevel by number of levels resolved by the fallback hook
+ if( nFallbackLevel < mnFallbackCount )
+ pFallbackData = (*mpFallbackList)[ nFallbackLevel ];
+ }
+
+ return pFallbackData;
+}
+
+void PhysicalFontCollection::Add(PhysicalFontFace* pNewData)
+{
+ OUString aSearchName = GetEnglishSearchFontName( pNewData->GetFamilyName() );
+
+ PhysicalFontFamily* pFoundData = FindOrCreateFontFamily(aSearchName);
+
+ pFoundData->AddFontFace( pNewData );
+}
+
+// find the font from the normalized font family name
+PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySearchName(const OUString& rSearchName) const
+{
+ // must be called with a normalized name.
+ assert( GetEnglishSearchFontName( rSearchName ) == rSearchName );
+
+ PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rSearchName );
+ if( it == maPhysicalFontFamilies.end() )
+ return nullptr;
+
+ PhysicalFontFamily* pFoundData = (*it).second.get();
+ return pFoundData;
+}
+
+PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(std::u16string_view rFontName) const
+{
+ return ImplFindFontFamilyBySearchName( GetEnglishSearchFontName( rFontName ) );
+}
+
+PhysicalFontFamily *PhysicalFontCollection::FindOrCreateFontFamily(OUString const& rFamilyName)
+{
+ PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rFamilyName );
+ PhysicalFontFamily* pFoundData = nullptr;
+
+ if( it != maPhysicalFontFamilies.end() )
+ pFoundData = (*it).second.get();
+
+ if( !pFoundData )
+ {
+ pFoundData = new PhysicalFontFamily(rFamilyName);
+ maPhysicalFontFamilies[ rFamilyName ].reset(pFoundData);
+ }
+
+ return pFoundData;
+}
+
+PhysicalFontFamily* PhysicalFontCollection::FindFontFamilyByTokenNames(std::u16string_view rTokenStr) const
+{
+ PhysicalFontFamily* pFoundData = nullptr;
+
+ // use normalized font name tokens to find the font
+ for( sal_Int32 nTokenPos = 0; nTokenPos != -1; )
+ {
+ std::u16string_view aFamilyName = GetNextFontToken( rTokenStr, nTokenPos );
+ if( aFamilyName.empty() )
+ continue;
+
+ pFoundData = FindFontFamily( aFamilyName );
+
+ if( pFoundData )
+ break;
+ }
+
+ return pFoundData;
+}
+
+PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySubstFontAttr(utl::FontNameAttr const& rFontAttr) const
+{
+ PhysicalFontFamily* pFoundData = nullptr;
+
+ // use the font substitutions suggested by the FontNameAttr to find the font
+ for (auto const& substitution : rFontAttr.Substitutions)
+ {
+ pFoundData = FindFontFamily(substitution);
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ // use known attributes from the configuration to find a matching substitute
+ const ImplFontAttrs nSearchType = rFontAttr.Type;
+ if( nSearchType != ImplFontAttrs::None )
+ {
+ const FontWeight eSearchWeight = rFontAttr.Weight;
+ const FontWidth eSearchWidth = rFontAttr.Width;
+ const FontItalic eSearchSlant = ITALIC_DONTKNOW;
+
+ pFoundData = FindFontFamilyByAttributes( nSearchType,
+ eSearchWeight, eSearchWidth, eSearchSlant, u"" );
+
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ return nullptr;
+}
+
+void PhysicalFontCollection::ImplInitMatchData() const
+{
+ // short circuit if already done
+ if( mbMatchData )
+ return;
+ mbMatchData = true;
+
+ if (utl::ConfigManager::IsFuzzing())
+ return;
+
+ // calculate MatchData for all entries
+ const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get();
+
+ for (auto const& family : maPhysicalFontFamilies)
+ {
+ const OUString& rSearchName = family.first;
+ PhysicalFontFamily* pEntry = family.second.get();
+
+ pEntry->InitMatchData( rFontSubst, rSearchName );
+ }
+}
+
+PhysicalFontFamily* PhysicalFontCollection::FindFontFamilyByAttributes(ImplFontAttrs nSearchType,
+ FontWeight eSearchWeight,
+ FontWidth eSearchWidth,
+ FontItalic eSearchItalic,
+ std::u16string_view rSearchFamilyName ) const
+{
+ if( (eSearchItalic != ITALIC_NONE) && (eSearchItalic != ITALIC_DONTKNOW) )
+ nSearchType |= ImplFontAttrs::Italic;
+
+ // don't bother to match attributes if the attributes aren't worth matching
+ if( nSearchType == ImplFontAttrs::None
+ && ((eSearchWeight == WEIGHT_DONTKNOW) || (eSearchWeight == WEIGHT_NORMAL))
+ && ((eSearchWidth == WIDTH_DONTKNOW) || (eSearchWidth == WIDTH_NORMAL)) )
+ return nullptr;
+
+ ImplInitMatchData();
+ PhysicalFontFamily* pFoundData = nullptr;
+
+ tools::Long nBestMatch = 40000;
+ ImplFontAttrs nBestType = ImplFontAttrs::None;
+
+ for (auto const& family : maPhysicalFontFamilies)
+ {
+ PhysicalFontFamily* pData = family.second.get();
+
+ // Get all information about the matching font
+ ImplFontAttrs nMatchType = pData->GetMatchType();
+ FontWeight eMatchWeight= pData->GetMatchWeight();
+ FontWidth eMatchWidth = pData->GetMatchWidth();
+
+ // Calculate Match Value
+ // 1000000000
+ // 100000000
+ // 10000000 CJK, CTL, None-Latin, Symbol
+ // 1000000 FamilyName, Script, Fixed, -Special, -Decorative,
+ // Titling, Capitals, Outline, Shadow
+ // 100000 Match FamilyName, Serif, SansSerif, Italic,
+ // Width, Weight
+ // 10000 Scalable, Standard, Default,
+ // full, Normal, Knownfont,
+ // Otherstyle, +Special, +Decorative,
+ // 1000 Typewriter, Rounded, Gothic, Schollbook
+ // 100
+ tools::Long nTestMatch = 0;
+
+ // test CJK script attributes
+ if ( nSearchType & ImplFontAttrs::CJK )
+ {
+ // if the matching font doesn't support any CJK languages, then
+ // it is not appropriate
+ if ( !(nMatchType & ImplFontAttrs::CJK_AllLang) )
+ {
+ nTestMatch -= 10000000;
+ }
+ else
+ {
+ // Matching language
+ if ( (nSearchType & ImplFontAttrs::CJK_AllLang)
+ && (nMatchType & ImplFontAttrs::CJK_AllLang) )
+ nTestMatch += 10000000*3;
+ if ( nMatchType & ImplFontAttrs::CJK )
+ nTestMatch += 10000000*2;
+ if ( nMatchType & ImplFontAttrs::Full )
+ nTestMatch += 10000000;
+ }
+ }
+ else if ( nMatchType & ImplFontAttrs::CJK )
+ {
+ nTestMatch -= 10000000;
+ }
+
+ // test CTL script attributes
+ if( nSearchType & ImplFontAttrs::CTL )
+ {
+ if( nMatchType & ImplFontAttrs::CTL )
+ nTestMatch += 10000000*2;
+ if( nMatchType & ImplFontAttrs::Full )
+ nTestMatch += 10000000;
+ }
+ else if ( nMatchType & ImplFontAttrs::CTL )
+ {
+ nTestMatch -= 10000000;
+ }
+
+ // test LATIN script attributes
+ if( nSearchType & ImplFontAttrs::NoneLatin )
+ {
+ if( nMatchType & ImplFontAttrs::NoneLatin )
+ nTestMatch += 10000000*2;
+ if( nMatchType & ImplFontAttrs::Full )
+ nTestMatch += 10000000;
+ }
+
+ // test SYMBOL attributes
+ if ( nSearchType & ImplFontAttrs::Symbol )
+ {
+ const OUString& rSearchName = family.first;
+ // prefer some special known symbol fonts
+ if ( rSearchName == "starsymbol" )
+ {
+ nTestMatch += 10000000*6+(10000*3);
+ }
+ else if ( rSearchName == "opensymbol" )
+ {
+ nTestMatch += 10000000*6;
+ }
+ else if ( rSearchName == "starbats" ||
+ rSearchName == "wingdings" ||
+ rSearchName == "monotypesorts" ||
+ rSearchName == "dingbats" ||
+ rSearchName == "zapfdingbats" )
+ {
+ nTestMatch += 10000000*5;
+ }
+ else if (pData->GetTypeFaces() & FontTypeFaces::Symbol)
+ {
+ nTestMatch += 10000000*4;
+ }
+ else
+ {
+ if( nMatchType & ImplFontAttrs::Symbol )
+ nTestMatch += 10000000*2;
+ if( nMatchType & ImplFontAttrs::Full )
+ nTestMatch += 10000000;
+ }
+ }
+ else if ((pData->GetTypeFaces() & (FontTypeFaces::Symbol | FontTypeFaces::NoneSymbol)) == FontTypeFaces::Symbol)
+ {
+ nTestMatch -= 10000000;
+ }
+ else if ( nMatchType & ImplFontAttrs::Symbol )
+ {
+ nTestMatch -= 10000;
+ }
+
+ // match stripped family name
+ if( !rSearchFamilyName.empty() && (rSearchFamilyName == pData->GetMatchFamilyName()) )
+ {
+ nTestMatch += 1000000*3;
+ }
+
+ // match ALLSCRIPT? attribute
+ if( nSearchType & ImplFontAttrs::AllScript )
+ {
+ if( nMatchType & ImplFontAttrs::AllScript )
+ {
+ nTestMatch += 1000000*2;
+ }
+ if( nSearchType & ImplFontAttrs::AllSubscript )
+ {
+ if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::AllSubscript) )
+ nTestMatch += 1000000*2;
+ if( ImplFontAttrs::None != ((nSearchType ^ nMatchType) & ImplFontAttrs::BrushScript) )
+ nTestMatch -= 1000000;
+ }
+ }
+ else if( nMatchType & ImplFontAttrs::AllScript )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test MONOSPACE+TYPEWRITER attributes
+ if( nSearchType & ImplFontAttrs::Fixed )
+ {
+ if( nMatchType & ImplFontAttrs::Fixed )
+ nTestMatch += 1000000*2;
+ // a typewriter attribute is even better
+ if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Typewriter) )
+ nTestMatch += 10000*2;
+ }
+ else if( nMatchType & ImplFontAttrs::Fixed )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test SPECIAL attribute
+ if( nSearchType & ImplFontAttrs::Special )
+ {
+ if( nMatchType & ImplFontAttrs::Special )
+ {
+ nTestMatch += 10000;
+ }
+ else if( !(nSearchType & ImplFontAttrs::AllSerifStyle) )
+ {
+ if( nMatchType & ImplFontAttrs::Serif )
+ {
+ nTestMatch += 1000*2;
+ }
+ else if( nMatchType & ImplFontAttrs::SansSerif )
+ {
+ nTestMatch += 1000;
+ }
+ }
+ }
+ else if( (nMatchType & ImplFontAttrs::Special) && !(nSearchType & ImplFontAttrs::Symbol) )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test DECORATIVE attribute
+ if( nSearchType & ImplFontAttrs::Decorative )
+ {
+ if( nMatchType & ImplFontAttrs::Decorative )
+ {
+ nTestMatch += 10000;
+ }
+ else if( !(nSearchType & ImplFontAttrs::AllSerifStyle) )
+ {
+ if( nMatchType & ImplFontAttrs::Serif )
+ nTestMatch += 1000*2;
+ else if ( nMatchType & ImplFontAttrs::SansSerif )
+ nTestMatch += 1000;
+ }
+ }
+ else if( nMatchType & ImplFontAttrs::Decorative )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test TITLE+CAPITALS attributes
+ if( nSearchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) )
+ {
+ if( nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) )
+ {
+ nTestMatch += 1000000*2;
+ }
+ if( ImplFontAttrs::None == ((nSearchType^nMatchType) & ImplFontAttrs(ImplFontAttrs::Titling | ImplFontAttrs::Capitals)))
+ {
+ nTestMatch += 1000000;
+ }
+ else if( (nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals)) &&
+ (nMatchType & (ImplFontAttrs::Standard | ImplFontAttrs::Default)) )
+ {
+ nTestMatch += 1000000;
+ }
+ }
+ else if( nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test OUTLINE+SHADOW attributes
+ if( nSearchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) )
+ {
+ if( nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) )
+ {
+ nTestMatch += 1000000*2;
+ }
+ if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs(ImplFontAttrs::Outline | ImplFontAttrs::Shadow)) )
+ {
+ nTestMatch += 1000000;
+ }
+ else if( (nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow)) &&
+ (nMatchType & (ImplFontAttrs::Standard | ImplFontAttrs::Default)) )
+ {
+ nTestMatch += 1000000;
+ }
+ }
+ else if ( nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test font name substrings
+ // TODO: calculate name matching score using e.g. Levenstein distance
+ if( (rSearchFamilyName.size() >= 4) &&
+ (pData->GetMatchFamilyName().getLength() >= 4) &&
+ ((rSearchFamilyName.find( pData->GetMatchFamilyName() ) != std::u16string_view::npos) ||
+ (pData->GetMatchFamilyName().indexOf( rSearchFamilyName ) != -1)) )
+ {
+ nTestMatch += 5000;
+ }
+ // test SERIF attribute
+ if( nSearchType & ImplFontAttrs::Serif )
+ {
+ if( nMatchType & ImplFontAttrs::Serif )
+ nTestMatch += 1000000*2;
+ else if( nMatchType & ImplFontAttrs::SansSerif )
+ nTestMatch -= 1000000;
+ }
+
+ // test SANSERIF attribute
+ if( nSearchType & ImplFontAttrs::SansSerif )
+ {
+ if( nMatchType & ImplFontAttrs::SansSerif )
+ nTestMatch += 1000000;
+ else if ( nMatchType & ImplFontAttrs::Serif )
+ nTestMatch -= 1000000;
+ }
+
+ // test ITALIC attribute
+ if( nSearchType & ImplFontAttrs::Italic )
+ {
+ if (pData->GetTypeFaces() & FontTypeFaces::Italic)
+ nTestMatch += 1000000*3;
+ if( nMatchType & ImplFontAttrs::Italic )
+ nTestMatch += 1000000;
+ }
+ else if (!(nSearchType & ImplFontAttrs::AllScript)
+ && ((nMatchType & ImplFontAttrs::Italic)
+ || !(pData->GetTypeFaces() & FontTypeFaces::NoneItalic)))
+ {
+ nTestMatch -= 1000000*2;
+ }
+
+ // test WIDTH attribute
+ if( (eSearchWidth != WIDTH_DONTKNOW) && (eSearchWidth != WIDTH_NORMAL) )
+ {
+ if( eSearchWidth < WIDTH_NORMAL )
+ {
+ if( eSearchWidth == eMatchWidth )
+ nTestMatch += 1000000*3;
+ else if( (eMatchWidth < WIDTH_NORMAL) && (eMatchWidth != WIDTH_DONTKNOW) )
+ nTestMatch += 1000000;
+ }
+ else
+ {
+ if( eSearchWidth == eMatchWidth )
+ nTestMatch += 1000000*3;
+ else if( eMatchWidth > WIDTH_NORMAL )
+ nTestMatch += 1000000;
+ }
+ }
+ else if( (eMatchWidth != WIDTH_DONTKNOW) && (eMatchWidth != WIDTH_NORMAL) )
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // test WEIGHT attribute
+ if( (eSearchWeight != WEIGHT_DONTKNOW) &&
+ (eSearchWeight != WEIGHT_NORMAL) &&
+ (eSearchWeight != WEIGHT_MEDIUM) )
+ {
+ if( eSearchWeight < WEIGHT_NORMAL )
+ {
+ if (pData->GetTypeFaces() & FontTypeFaces::Light)
+ nTestMatch += 1000000;
+ if( (eMatchWeight < WEIGHT_NORMAL) && (eMatchWeight != WEIGHT_DONTKNOW) )
+ nTestMatch += 1000000;
+ }
+ else
+ {
+ if (pData->GetTypeFaces() & FontTypeFaces::Bold)
+ nTestMatch += 1000000;
+ if( eMatchWeight > WEIGHT_BOLD )
+ nTestMatch += 1000000;
+ }
+ }
+ else if (((eMatchWeight != WEIGHT_DONTKNOW)
+ && (eMatchWeight != WEIGHT_NORMAL)
+ && (eMatchWeight != WEIGHT_MEDIUM))
+ || !(pData->GetTypeFaces() & FontTypeFaces::Normal))
+ {
+ nTestMatch -= 1000000;
+ }
+
+ // prefer scalable fonts
+ if (pData->GetTypeFaces() & FontTypeFaces::Scalable)
+ nTestMatch += 10000*4;
+ else
+ nTestMatch -= 10000*4;
+
+ // test STANDARD+DEFAULT+FULL+NORMAL attributes
+ if( nMatchType & ImplFontAttrs::Standard )
+ nTestMatch += 10000*2;
+ if( nMatchType & ImplFontAttrs::Default )
+ nTestMatch += 10000;
+ if( nMatchType & ImplFontAttrs::Full )
+ nTestMatch += 10000;
+ if( nMatchType & ImplFontAttrs::Normal )
+ nTestMatch += 10000;
+
+ // test OTHERSTYLE attribute
+ if( ((nSearchType ^ nMatchType) & ImplFontAttrs::OtherStyle) != ImplFontAttrs::None )
+ {
+ nTestMatch -= 10000;
+ }
+
+ // test ROUNDED attribute
+ if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Rounded) )
+ nTestMatch += 1000;
+
+ // test TYPEWRITER attribute
+ if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Typewriter) )
+ nTestMatch += 1000;
+
+ // test GOTHIC attribute
+ if( nSearchType & ImplFontAttrs::Gothic )
+ {
+ if( nMatchType & ImplFontAttrs::Gothic )
+ nTestMatch += 1000*3;
+ if( nMatchType & ImplFontAttrs::SansSerif )
+ nTestMatch += 1000*2;
+ }
+
+ // test SCHOOLBOOK attribute
+ if( nSearchType & ImplFontAttrs::Schoolbook )
+ {
+ if( nMatchType & ImplFontAttrs::Schoolbook )
+ nTestMatch += 1000*3;
+ if( nMatchType & ImplFontAttrs::Serif )
+ nTestMatch += 1000*2;
+ }
+
+ // compare with best matching font yet
+ if ( nTestMatch > nBestMatch )
+ {
+ pFoundData = pData;
+ nBestMatch = nTestMatch;
+ nBestType = nMatchType;
+ }
+ else if( nTestMatch == nBestMatch )
+ {
+ // some fonts are more suitable defaults
+ if( nMatchType & ImplFontAttrs::Default )
+ {
+ pFoundData = pData;
+ nBestType = nMatchType;
+ }
+ else if( (nMatchType & ImplFontAttrs::Standard) &&
+ !(nBestType & ImplFontAttrs::Default) )
+ {
+ pFoundData = pData;
+ nBestType = nMatchType;
+ }
+ }
+ }
+
+ return pFoundData;
+}
+
+PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyOfDefaultFont() const
+{
+ // try to find one of the default fonts of the
+ // UNICODE, SANSSERIF, SERIF or FIXED default font lists
+ PhysicalFontFamily* pFoundData = nullptr;
+ if (!utl::ConfigManager::IsFuzzing())
+ {
+ const utl::DefaultFontConfiguration& rDefaults = utl::DefaultFontConfiguration::get();
+ LanguageTag aLanguageTag("en");
+ OUString aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SANS_UNICODE );
+ pFoundData = FindFontFamilyByTokenNames( aFontname );
+
+ if( pFoundData )
+ return pFoundData;
+
+ aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SANS );
+ pFoundData = FindFontFamilyByTokenNames( aFontname );
+ if( pFoundData )
+ return pFoundData;
+
+ aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SERIF );
+ pFoundData = FindFontFamilyByTokenNames( aFontname );
+ if( pFoundData )
+ return pFoundData;
+
+ aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::FIXED );
+ pFoundData = FindFontFamilyByTokenNames( aFontname );
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ // now try to find a reasonable non-symbol font
+
+ ImplInitMatchData();
+
+ for (auto const& family : maPhysicalFontFamilies)
+ {
+ PhysicalFontFamily* pData = family.second.get();
+ if( pData->GetMatchType() & ImplFontAttrs::Symbol )
+ continue;
+
+ pFoundData = pData;
+ if( pData->GetMatchType() & (ImplFontAttrs::Default|ImplFontAttrs::Standard) )
+ break;
+ }
+ if( pFoundData )
+ return pFoundData;
+
+ // finding any font is better than finding no font at all
+ auto it = maPhysicalFontFamilies.begin();
+ if( it != maPhysicalFontFamilies.end() )
+ pFoundData = (*it).second.get();
+
+ return pFoundData;
+}
+
+std::shared_ptr<PhysicalFontCollection> PhysicalFontCollection::Clone() const
+{
+ auto xClonedCollection = std::make_shared<PhysicalFontCollection>();
+ xClonedCollection->mpPreMatchHook = mpPreMatchHook;
+ xClonedCollection->mpFallbackHook = mpFallbackHook;
+
+ // TODO: clone the config-font attributes too?
+ xClonedCollection->mbMatchData = false;
+
+ for (auto const& family : maPhysicalFontFamilies)
+ {
+ const PhysicalFontFamily* pFontFace = family.second.get();
+ pFontFace->UpdateCloneFontList(*xClonedCollection);
+ }
+
+ return xClonedCollection;
+}
+
+std::unique_ptr<PhysicalFontFaceCollection> PhysicalFontCollection::GetFontFaceCollection() const
+{
+ std::unique_ptr<PhysicalFontFaceCollection> pDeviceFontList(new PhysicalFontFaceCollection);
+
+ for (auto const& family : maPhysicalFontFamilies)
+ {
+ const PhysicalFontFamily* pFontFamily = family.second.get();
+ pFontFamily->UpdateDevFontList( *pDeviceFontList );
+ }
+
+ return pDeviceFontList;
+}
+
+// These are the metric-compatible replacement fonts that are bundled with
+// LibreOffice, we prefer them over generic substitutions that might be
+// provided by the system.
+const std::vector<std::pair<OUString, OUString>> aMetricCompatibleMap =
+{
+ { "Times New Roman", "Liberation Serif" },
+ { "Arial", "Liberation Sans" },
+ { "Arial Narrow", "Liberation Sans Narrow" },
+ { "Courier New", "Liberation Mono" },
+ { "Cambria", "Caladea" },
+ { "Calibri", "Carlito" },
+};
+
+static bool FindMetricCompatibleFont(FontSelectPattern& rFontSelData)
+{
+ for (const auto& aSub : aMetricCompatibleMap)
+ {
+ if (rFontSelData.maSearchName == GetEnglishSearchFontName(aSub.first))
+ {
+ rFontSelData.maSearchName = aSub.second;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(FontSelectPattern& rFSD) const
+{
+ // give up if no fonts are available
+ if( !Count() )
+ return nullptr;
+
+ static bool noFontLookup = getenv("SAL_NO_FONT_LOOKUP") != nullptr;
+ if (noFontLookup)
+ {
+ // Hard code the use of Liberation Sans and skip font search.
+ sal_Int32 nIndex = 0;
+ rFSD.maTargetName = GetNextFontToken(rFSD.GetFamilyName(), nIndex);
+ rFSD.maSearchName = "liberationsans";
+ PhysicalFontFamily* pFont = ImplFindFontFamilyBySearchName(rFSD.maSearchName);
+ assert(pFont);
+ return pFont;
+ }
+
+ bool bMultiToken = false;
+ sal_Int32 nTokenPos = 0;
+ OUString& aSearchName = rFSD.maSearchName; // TODO: get rid of reference
+ for(;;)
+ {
+ rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos );
+ aSearchName = rFSD.maTargetName;
+
+ // Until features are properly supported, they are appended to the
+ // font name, so we need to strip them off so the font is found.
+ sal_Int32 nFeat = aSearchName.indexOf(FontSelectPattern::FEAT_PREFIX);
+ OUString aOrigName = rFSD.maTargetName;
+ OUString aBaseFontName = aSearchName.copy( 0, (nFeat != -1) ? nFeat : aSearchName.getLength() );
+
+ if (nFeat != -1)
+ {
+ aSearchName = aBaseFontName;
+ rFSD.maTargetName = aBaseFontName;
+ }
+
+ aSearchName = GetEnglishSearchFontName( aSearchName );
+ ImplFontSubstitute(aSearchName);
+ // #114999# special emboldening for Ricoh fonts
+ // TODO: smarter check for special cases by using PreMatch infrastructure?
+ if( (rFSD.GetWeight() > WEIGHT_MEDIUM) &&
+ aSearchName.startsWithIgnoreAsciiCase( "hg" ) )
+ {
+ OUString aBoldName;
+ if( aSearchName.startsWithIgnoreAsciiCase( "hggothicb" ) )
+ aBoldName = "hggothice";
+ else if( aSearchName.startsWithIgnoreAsciiCase( "hgpgothicb" ) )
+ aBoldName = "hgpgothice";
+ else if( aSearchName.startsWithIgnoreAsciiCase( "hgminchol" ) )
+ aBoldName = "hgminchob";
+ else if( aSearchName.startsWithIgnoreAsciiCase( "hgpminchol" ) )
+ aBoldName = "hgpminchob";
+ else if( aSearchName.equalsIgnoreAsciiCase( "hgminchob" ) )
+ aBoldName = "hgminchoe";
+ else if( aSearchName.equalsIgnoreAsciiCase( "hgpminchob" ) )
+ aBoldName = "hgpminchoe";
+
+ if( !aBoldName.isEmpty() && ImplFindFontFamilyBySearchName( aBoldName ) )
+ {
+ // the other font is available => use it
+ aSearchName = aBoldName;
+ // prevent synthetic emboldening of bold version
+ rFSD.SetWeight(WEIGHT_DONTKNOW);
+ }
+ }
+
+ // restore the features to make the font selection data unique
+ rFSD.maTargetName = aOrigName;
+
+ // check if the current font name token or its substitute is valid
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName);
+ if( pFoundData )
+ return pFoundData;
+
+ // some systems provide special customization
+ // e.g. they suggest "serif" as UI-font, but this name cannot be used directly
+ // because the system wants to map it to another font first, e.g. "Helvetica"
+
+ // use the target name to search in the prematch hook
+ rFSD.maTargetName = aBaseFontName;
+
+ // Related: fdo#49271 RTF files often contain weird-ass
+ // Win 3.1/Win95 style fontnames which attempt to put the
+ // charset encoding into the filename
+ // http://www.webcenter.ru/~kazarn/eng/fonts_ttf.htm
+ OUString sStrippedName = StripScriptFromName(rFSD.maTargetName);
+ if (sStrippedName != rFSD.maTargetName)
+ {
+ rFSD.maTargetName = sStrippedName;
+ aSearchName = GetEnglishSearchFontName(rFSD.maTargetName);
+ pFoundData = ImplFindFontFamilyBySearchName(aSearchName);
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ if (FindMetricCompatibleFont(rFSD) ||
+ (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD)))
+ {
+ aSearchName = GetEnglishSearchFontName(aSearchName);
+ }
+
+ // the prematch hook uses the target name to search, but we now need
+ // to restore the features to make the font selection data unique
+ rFSD.maTargetName = aOrigName;
+
+ pFoundData = ImplFindFontFamilyBySearchName( aSearchName );
+ if( pFoundData )
+ return pFoundData;
+
+ // break after last font name token was checked unsuccessfully
+ if( nTokenPos == -1)
+ break;
+ bMultiToken = true;
+ }
+
+ // if the first font was not available find the next available font in
+ // the semicolon separated list of font names. A font is also considered
+ // available when there is a matching entry in the Tools->Options->Fonts
+ // dialog with neither ALWAYS nor SCREENONLY flags set and the substitution
+ // font is available
+ for( nTokenPos = 0; nTokenPos != -1; )
+ {
+ if( bMultiToken )
+ {
+ rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos );
+ aSearchName = GetEnglishSearchFontName( rFSD.maTargetName );
+ }
+ else
+ nTokenPos = -1;
+ if (FindMetricCompatibleFont(rFSD) ||
+ (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD)))
+ {
+ aSearchName = GetEnglishSearchFontName( aSearchName );
+ }
+ ImplFontSubstitute(aSearchName);
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName);
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ // if no font with a directly matching name is available use the
+ // first font name token and get its attributes to find a replacement
+ if ( bMultiToken )
+ {
+ nTokenPos = 0;
+ rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos );
+ aSearchName = GetEnglishSearchFontName( rFSD.maTargetName );
+ }
+
+ OUString aSearchShortName;
+ OUString aSearchFamilyName;
+ FontWeight eSearchWeight = rFSD.GetWeight();
+ FontWidth eSearchWidth = rFSD.GetWidthType();
+ ImplFontAttrs nSearchType = ImplFontAttrs::None;
+ utl::FontSubstConfiguration::getMapName( aSearchName, aSearchShortName, aSearchFamilyName,
+ eSearchWeight, eSearchWidth, nSearchType );
+
+ // note: the search name was already translated to english (if possible)
+ // use the font's shortened name if needed
+ if ( aSearchShortName != aSearchName )
+ {
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchShortName);
+ if( pFoundData )
+ {
+#ifdef UNX
+ /* #96738# don't use mincho as a replacement for "MS Mincho" on X11: Mincho is
+ a korean bitmap font that is not suitable here. Use the font replacement table,
+ that automatically leads to the desired "HG Mincho Light J". Same story for
+ MS Gothic, there are thai and korean "Gothic" fonts, so we even prefer Andale */
+ if ((aSearchName != "msmincho") && (aSearchName != "msgothic"))
+ // TODO: add heuristic to only throw out the fake ms* fonts
+#endif
+ {
+ return pFoundData;
+ }
+ }
+ }
+
+ // use font fallback
+ const utl::FontNameAttr* pFontAttr = nullptr;
+ if (!aSearchName.isEmpty() && !utl::ConfigManager::IsFuzzing())
+ {
+ // get fallback info using FontSubstConfiguration and
+ // the target name, it's shortened name and family name in that order
+ const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get();
+ pFontAttr = rFontSubst.getSubstInfo( aSearchName );
+ if ( !pFontAttr && (aSearchShortName != aSearchName) )
+ pFontAttr = rFontSubst.getSubstInfo( aSearchShortName );
+ if ( !pFontAttr && (aSearchFamilyName != aSearchShortName) )
+ pFontAttr = rFontSubst.getSubstInfo( aSearchFamilyName );
+
+ // try the font substitutions suggested by the fallback info
+ if( pFontAttr )
+ {
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySubstFontAttr(*pFontAttr);
+ if( pFoundData )
+ return pFoundData;
+ }
+ }
+
+ // if a target symbol font is not available use a default symbol font
+ if( rFSD.IsMicrosoftSymbolEncoded() )
+ {
+ LanguageTag aDefaultLanguageTag("en");
+ if (utl::ConfigManager::IsFuzzing())
+ aSearchName = "OpenSymbol";
+ else
+ aSearchName = utl::DefaultFontConfiguration::get().getDefaultFont( aDefaultLanguageTag, DefaultFontType::SYMBOL );
+ PhysicalFontFamily* pFoundData = FindFontFamilyByTokenNames(aSearchName);
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ // now try the other font name tokens
+ while( nTokenPos != -1 )
+ {
+ rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos );
+ if( rFSD.maTargetName.isEmpty() )
+ continue;
+
+ aSearchName = GetEnglishSearchFontName( rFSD.maTargetName );
+
+ OUString aTempShortName;
+ OUString aTempFamilyName;
+ ImplFontAttrs nTempType = ImplFontAttrs::None;
+ FontWeight eTempWeight = rFSD.GetWeight();
+ FontWidth eTempWidth = WIDTH_DONTKNOW;
+ utl::FontSubstConfiguration::getMapName( aSearchName, aTempShortName, aTempFamilyName,
+ eTempWeight, eTempWidth, nTempType );
+
+ // use a shortened token name if available
+ if( aTempShortName != aSearchName )
+ {
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aTempShortName);
+ if( pFoundData )
+ return pFoundData;
+ }
+
+ const utl::FontNameAttr* pTempFontAttr = nullptr;
+ if (!utl::ConfigManager::IsFuzzing())
+ {
+ // use a font name from font fallback list to determine font attributes
+ // get fallback info using FontSubstConfiguration and
+ // the target name, it's shortened name and family name in that order
+ const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get();
+ pTempFontAttr = rFontSubst.getSubstInfo( aSearchName );
+
+ if ( !pTempFontAttr && (aTempShortName != aSearchName) )
+ pTempFontAttr = rFontSubst.getSubstInfo( aTempShortName );
+
+ if ( !pTempFontAttr && (aTempFamilyName != aTempShortName) )
+ pTempFontAttr = rFontSubst.getSubstInfo( aTempFamilyName );
+ }
+
+ // try the font substitutions suggested by the fallback info
+ if( pTempFontAttr )
+ {
+ PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySubstFontAttr(*pTempFontAttr);
+ if( pFoundData )
+ return pFoundData;
+ if( !pFontAttr )
+ pFontAttr = pTempFontAttr;
+ }
+ }
+
+ // if still needed use the font request's attributes to find a good match
+ if (MsLangId::isSimplifiedChinese(rFSD.meLanguage))
+ nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_SC;
+ else if (MsLangId::isTraditionalChinese(rFSD.meLanguage))
+ nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_TC;
+ else if (MsLangId::isKorean(rFSD.meLanguage))
+ nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_KR;
+ else if (rFSD.meLanguage == LANGUAGE_JAPANESE)
+ nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_JP;
+ else
+ {
+ nSearchType |= lcl_IsCJKFont( rFSD.GetFamilyName() );
+ if( rFSD.IsMicrosoftSymbolEncoded() )
+ nSearchType |= ImplFontAttrs::Symbol;
+ }
+
+ PhysicalFontFamily::CalcType(nSearchType, eSearchWeight, eSearchWidth, rFSD.GetFamilyType(), pFontAttr);
+ PhysicalFontFamily* pFoundData = FindFontFamilyByAttributes(nSearchType,
+ eSearchWeight, eSearchWidth, rFSD.GetItalic(), aSearchFamilyName);
+
+ if( pFoundData )
+ {
+ // overwrite font selection attributes using info from the typeface flags
+ if ((eSearchWeight >= WEIGHT_BOLD)
+ && (eSearchWeight > rFSD.GetWeight())
+ && (pFoundData->GetTypeFaces() & FontTypeFaces::Bold))
+ {
+ rFSD.SetWeight( eSearchWeight );
+ }
+ else if ((eSearchWeight < WEIGHT_NORMAL)
+ && (eSearchWeight < rFSD.GetWeight())
+ && (eSearchWeight != WEIGHT_DONTKNOW)
+ && (pFoundData->GetTypeFaces() & FontTypeFaces::Light))
+ {
+ rFSD.SetWeight( eSearchWeight );
+ }
+
+ if ((nSearchType & ImplFontAttrs::Italic)
+ && ((rFSD.GetItalic() == ITALIC_DONTKNOW)
+ || (rFSD.GetItalic() == ITALIC_NONE))
+ && (pFoundData->GetTypeFaces() & FontTypeFaces::Italic))
+ {
+ rFSD.SetItalic( ITALIC_NORMAL );
+ }
+ }
+ else
+ {
+ // if still needed fall back to default fonts
+ pFoundData = ImplFindFontFamilyOfDefaultFont();
+ }
+
+ return pFoundData;
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
diff --git a/vcl/source/font/PhysicalFontFace.cxx b/vcl/source/font/PhysicalFontFace.cxx
new file mode 100644
index 0000000000..aa9a9327f7
--- /dev/null
+++ b/vcl/source/font/PhysicalFontFace.cxx
@@ -0,0 +1,510 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <sal/types.h>
+#include <tools/fontenum.hxx>
+#include <unotools/fontdefs.hxx>
+#include <osl/file.hxx>
+#include <osl/thread.h>
+
+#include <fontattributes.hxx>
+#include <impfontcharmap.hxx>
+#include <sft.hxx>
+#include <salgdi.hxx>
+
+#include <font/FontSelectPattern.hxx>
+#include <font/PhysicalFontFace.hxx>
+#include <o3tl/string_view.hxx>
+
+#include <string_view>
+
+#include <hb-ot.h>
+
+namespace vcl::font
+{
+PhysicalFontFace::PhysicalFontFace(const FontAttributes& rDFA)
+ : FontAttributes(rDFA)
+ , mpHbFace(nullptr)
+ , mpHbUnscaledFont(nullptr)
+{
+}
+
+PhysicalFontFace::~PhysicalFontFace()
+{
+ if (mpHbFace)
+ hb_face_destroy(mpHbFace);
+ if (mpHbUnscaledFont)
+ hb_font_destroy(mpHbUnscaledFont);
+}
+
+sal_Int32 PhysicalFontFace::CompareIgnoreSize(const PhysicalFontFace& rOther) const
+{
+ // compare their width, weight, italic, style name and family name
+ if (GetWidthType() < rOther.GetWidthType())
+ return -1;
+ else if (GetWidthType() > rOther.GetWidthType())
+ return 1;
+
+ if (GetWeight() < rOther.GetWeight())
+ return -1;
+ else if (GetWeight() > rOther.GetWeight())
+ return 1;
+
+ if (GetItalic() < rOther.GetItalic())
+ return -1;
+ else if (GetItalic() > rOther.GetItalic())
+ return 1;
+
+ sal_Int32 nRet = GetFamilyName().compareTo(rOther.GetFamilyName());
+
+ if (nRet == 0)
+ {
+ nRet = GetStyleName().compareTo(rOther.GetStyleName());
+ }
+
+ return nRet;
+}
+
+static int FamilyNameMatchValue(FontSelectPattern const& rFSP, std::u16string_view sFontFamily)
+{
+ const OUString& rFontName = rFSP.maTargetName;
+
+ if (rFontName.equalsIgnoreAsciiCase(sFontFamily))
+ return 240000;
+
+ return 0;
+}
+
+static int StyleNameMatchValue(FontMatchStatus const& rStatus, std::u16string_view rStyle)
+{
+ if (rStatus.mpTargetStyleName
+ && o3tl::equalsIgnoreAsciiCase(rStyle, *rStatus.mpTargetStyleName))
+ return 120000;
+
+ return 0;
+}
+
+static int PitchMatchValue(FontSelectPattern const& rFSP, FontPitch ePitch)
+{
+ if ((rFSP.GetPitch() != PITCH_DONTKNOW) && (rFSP.GetPitch() == ePitch))
+ return 20000;
+
+ return 0;
+}
+
+static int PreferNormalFontWidthMatchValue(FontWidth eWidthType)
+{
+ // TODO: change when the upper layers can tell their width preference
+ if (eWidthType == WIDTH_NORMAL)
+ return 400;
+ else if ((eWidthType == WIDTH_SEMI_EXPANDED) || (eWidthType == WIDTH_SEMI_CONDENSED))
+ return 300;
+
+ return 0;
+}
+
+static int WeightMatchValue(FontSelectPattern const& rFSP, FontWeight eWeight)
+{
+ int nMatch = 0;
+
+ if (rFSP.GetWeight() != WEIGHT_DONTKNOW)
+ {
+ // if not bold or requiring emboldening prefer light fonts to bold fonts
+ FontWeight ePatternWeight = rFSP.mbEmbolden ? WEIGHT_NORMAL : rFSP.GetWeight();
+
+ int nReqWeight = static_cast<int>(ePatternWeight);
+ if (ePatternWeight > WEIGHT_MEDIUM)
+ nReqWeight += 100;
+
+ int nGivenWeight = static_cast<int>(eWeight);
+ if (eWeight > WEIGHT_MEDIUM)
+ nGivenWeight += 100;
+
+ int nWeightDiff = nReqWeight - nGivenWeight;
+
+ if (nWeightDiff == 0)
+ nMatch += 1000;
+ else if (nWeightDiff == +1 || nWeightDiff == -1)
+ nMatch += 700;
+ else if (nWeightDiff < +50 && nWeightDiff > -50)
+ nMatch += 200;
+ }
+ else
+ {
+ // prefer NORMAL font weight
+ // TODO: change when the upper layers can tell their weight preference
+ if (eWeight == WEIGHT_NORMAL)
+ nMatch += 450;
+ else if (eWeight == WEIGHT_MEDIUM)
+ nMatch += 350;
+ else if ((eWeight == WEIGHT_SEMILIGHT) || (eWeight == WEIGHT_SEMIBOLD))
+ nMatch += 200;
+ else if (eWeight == WEIGHT_LIGHT)
+ nMatch += 150;
+ }
+
+ return nMatch;
+}
+
+static int ItalicMatchValue(FontSelectPattern const& rFSP, FontItalic eItalic)
+{
+ // if requiring custom matrix to fake italic, prefer upright font
+ FontItalic ePatternItalic
+ = rFSP.maItalicMatrix != ItalicMatrix() ? ITALIC_NONE : rFSP.GetItalic();
+
+ if (ePatternItalic == ITALIC_NONE)
+ {
+ if (eItalic == ITALIC_NONE)
+ return 900;
+ }
+ else
+ {
+ if (ePatternItalic == eItalic)
+ return 900;
+ else if (eItalic != ITALIC_NONE)
+ return 600;
+ }
+
+ return 0;
+}
+
+bool PhysicalFontFace::IsBetterMatch(const FontSelectPattern& rFSP, FontMatchStatus& rStatus) const
+{
+ int nMatch = FamilyNameMatchValue(rFSP, GetFamilyName());
+ nMatch += StyleNameMatchValue(rStatus, GetStyleName());
+ nMatch += PitchMatchValue(rFSP, GetPitch());
+ nMatch += PreferNormalFontWidthMatchValue(GetWidthType());
+ nMatch += WeightMatchValue(rFSP, GetWeight());
+ nMatch += ItalicMatchValue(rFSP, GetItalic());
+
+ if (rFSP.mnOrientation != 0_deg10)
+ nMatch += 80;
+ else if (rFSP.mnWidth != 0)
+ nMatch += 25;
+ else
+ nMatch += 5;
+
+ if (rStatus.mnFaceMatch > nMatch)
+ {
+ return false;
+ }
+ else if (rStatus.mnFaceMatch < nMatch)
+ {
+ rStatus.mnFaceMatch = nMatch;
+ return true;
+ }
+
+ return true;
+}
+
+RawFontData PhysicalFontFace::GetRawFontData(uint32_t nTag) const
+{
+ auto pHbFace = GetHbFace();
+ // If nTag is 0, reference the whole font.
+ if (!nTag)
+ return RawFontData(hb_face_reference_blob(pHbFace));
+ return RawFontData(hb_face_reference_table(pHbFace, nTag));
+}
+
+static hb_blob_t* getTable(hb_face_t*, hb_tag_t nTag, void* pUserData)
+{
+ return static_cast<const PhysicalFontFace*>(pUserData)->GetHbTable(nTag);
+}
+
+hb_face_t* PhysicalFontFace::GetHbFace() const
+{
+ if (mpHbFace == nullptr)
+ mpHbFace
+ = hb_face_create_for_tables(getTable, const_cast<PhysicalFontFace*>(this), nullptr);
+ return mpHbFace;
+}
+
+hb_font_t* PhysicalFontFace::GetHbUnscaledFont() const
+{
+ if (mpHbUnscaledFont == nullptr)
+ mpHbUnscaledFont = hb_font_create(GetHbFace());
+ return mpHbUnscaledFont;
+}
+
+FontCharMapRef PhysicalFontFace::GetFontCharMap() const
+{
+ if (mxCharMap.is())
+ return mxCharMap;
+
+ // Check if this font is using symbol cmap subtable, most likely redundant
+ // since HarfBuzz handles mapping symbol fonts for us.
+ RawFontData aData(GetRawFontData(HB_TAG('c', 'm', 'a', 'p')));
+ bool bSymbol = HasMicrosoftSymbolCmap(aData.data(), aData.size());
+
+ hb_face_t* pHbFace = GetHbFace();
+ hb_set_t* pUnicodes = hb_set_create();
+ hb_face_collect_unicodes(pHbFace, pUnicodes);
+
+ if (hb_set_get_population(pUnicodes))
+ {
+ // Convert HarfBuzz set to code ranges.
+ std::vector<sal_UCS4> aRangeCodes;
+ hb_codepoint_t nFirst, nLast = HB_SET_VALUE_INVALID;
+ while (hb_set_next_range(pUnicodes, &nFirst, &nLast))
+ {
+ aRangeCodes.push_back(nFirst);
+ aRangeCodes.push_back(nLast + 1);
+ }
+
+ mxCharMap = new FontCharMap(bSymbol, std::move(aRangeCodes));
+ }
+
+ hb_set_destroy(pUnicodes);
+
+ if (!mxCharMap.is())
+ mxCharMap = FontCharMap::GetDefaultMap(IsMicrosoftSymbolEncoded());
+
+ return mxCharMap;
+}
+
+bool PhysicalFontFace::GetFontCapabilities(vcl::FontCapabilities& rFontCapabilities) const
+{
+ if (!mxFontCapabilities)
+ {
+ mxFontCapabilities.emplace();
+ RawFontData aData(GetRawFontData(HB_TAG('O', 'S', '/', '2')));
+ getTTCoverage(mxFontCapabilities->oUnicodeRange, mxFontCapabilities->oCodePageRange,
+ aData.data(), aData.size());
+ }
+
+ rFontCapabilities = *mxFontCapabilities;
+ return rFontCapabilities.oUnicodeRange || rFontCapabilities.oCodePageRange;
+}
+
+namespace
+{
+class RawFace
+{
+public:
+ RawFace(hb_face_t* pFace)
+ : mpFace(hb_face_reference(pFace))
+ {
+ }
+
+ RawFace(const RawFace& rOther)
+ : mpFace(hb_face_reference(rOther.mpFace))
+ {
+ }
+
+ ~RawFace() { hb_face_destroy(mpFace); }
+
+ RawFontData GetTable(uint32_t nTag) const
+ {
+ return RawFontData(hb_face_reference_table(mpFace, nTag));
+ }
+
+private:
+ hb_face_t* mpFace;
+};
+
+class TrueTypeFace final : public AbstractTrueTypeFont
+{
+ const RawFace m_aFace;
+ mutable std::array<RawFontData, NUM_TAGS> m_aTableList;
+
+ const RawFontData& table(sal_uInt32 nIdx) const
+ {
+ assert(nIdx < NUM_TAGS);
+ static const uint32_t aTags[NUM_TAGS] = {
+ T_maxp, T_glyf, T_head, T_loca, T_name, T_hhea, T_hmtx, T_cmap,
+ T_vhea, T_vmtx, T_OS2, T_post, T_cvt, T_prep, T_fpgm, T_CFF,
+ };
+ if (m_aTableList[nIdx].empty())
+ m_aTableList[nIdx] = std::move(m_aFace.GetTable(aTags[nIdx]));
+ return m_aTableList[nIdx];
+ }
+
+public:
+ TrueTypeFace(RawFace aFace, const FontCharMapRef rCharMap)
+ : AbstractTrueTypeFont(nullptr, rCharMap)
+ , m_aFace(std::move(aFace))
+ {
+ }
+
+ bool hasTable(sal_uInt32 nIdx) const override { return !table(nIdx).empty(); }
+ const sal_uInt8* table(sal_uInt32 nIdx, sal_uInt32& nSize) const override
+ {
+ auto& rTable = table(nIdx);
+ nSize = rTable.size();
+ return rTable.data();
+ }
+};
+}
+
+bool PhysicalFontFace::CreateFontSubset(std::vector<sal_uInt8>& rOutBuffer,
+ const sal_GlyphId* pGlyphIds, const sal_uInt8* pEncoding,
+ const int nGlyphCount, FontSubsetInfo& rInfo) const
+{
+ // Prepare data for font subsetter.
+ TrueTypeFace aSftFont(RawFace(GetHbFace()), GetFontCharMap());
+ if (aSftFont.initialize() != SFErrCodes::Ok)
+ return false;
+
+ // write subset into destination file
+ return CreateTTFfontSubset(aSftFont, rOutBuffer, pGlyphIds, pEncoding, nGlyphCount, rInfo);
+}
+
+bool PhysicalFontFace::HasColorLayers() const
+{
+ const auto pHbFace = GetHbFace();
+ return hb_ot_color_has_layers(pHbFace) && hb_ot_color_has_palettes(pHbFace);
+}
+
+const std::vector<ColorPalette>& PhysicalFontFace::GetColorPalettes() const
+{
+ if (!mxColorPalettes)
+ {
+ mxColorPalettes.emplace();
+ const auto pHbFace = GetHbFace();
+ auto nPalettes = hb_ot_color_palette_get_count(pHbFace);
+ mxColorPalettes->reserve(nPalettes);
+ for (auto nPalette = 0u; nPalette < nPalettes; nPalette++)
+ {
+ auto nColors = hb_ot_color_palette_get_colors(pHbFace, nPalette, 0, nullptr, nullptr);
+ ColorPalette aPalette(nColors);
+ for (auto nColor = 0u; nColor < nColors; nColor++)
+ {
+ uint32_t nCount = 1;
+ hb_color_t aColor;
+ hb_ot_color_palette_get_colors(pHbFace, nPalette, nColor, &nCount, &aColor);
+ auto a = hb_color_get_alpha(aColor);
+ auto r = hb_color_get_red(aColor);
+ auto g = hb_color_get_green(aColor);
+ auto b = hb_color_get_blue(aColor);
+ aPalette[nColor] = Color(ColorAlphaTag::ColorAlpha, a, r, g, b);
+ }
+ mxColorPalettes->push_back(aPalette);
+ }
+ }
+
+ return *mxColorPalettes;
+}
+
+std::vector<ColorLayer> PhysicalFontFace::GetGlyphColorLayers(sal_GlyphId nGlyphIndex) const
+{
+ if (!HasColorLayers())
+ return {};
+
+ const auto pHbFace = GetHbFace();
+
+ auto nLayers = hb_ot_color_glyph_get_layers(pHbFace, nGlyphIndex, 0, nullptr, nullptr);
+ std::vector<ColorLayer> aLayers(nLayers);
+ for (auto nLayer = 0u; nLayer < nLayers; nLayer++)
+ {
+ hb_ot_color_layer_t aLayer;
+ uint32_t nCount = 1;
+ hb_ot_color_glyph_get_layers(pHbFace, nGlyphIndex, nLayer, &nCount, &aLayer);
+ aLayers[nLayer] = { aLayer.glyph, aLayer.color_index };
+ }
+
+ return aLayers;
+}
+
+bool PhysicalFontFace::HasColorBitmaps() const { return hb_ot_color_has_png(GetHbFace()); }
+
+RawFontData PhysicalFontFace::GetGlyphColorBitmap(sal_GlyphId nGlyphIndex,
+ tools::Rectangle& rRect) const
+{
+ if (!HasColorBitmaps())
+ return {};
+
+ hb_font_t* pHbFont = GetHbUnscaledFont();
+ auto aData = RawFontData(hb_ot_color_glyph_reference_png(pHbFont, nGlyphIndex));
+ if (!aData.empty())
+ {
+ hb_glyph_extents_t aExtents;
+ if (hb_font_get_glyph_extents(pHbFont, nGlyphIndex, &aExtents))
+ {
+ auto aPoint = Point(aExtents.x_bearing, aExtents.y_bearing + aExtents.height);
+ auto aSize = Size(aExtents.width, -aExtents.height);
+ rRect = tools::Rectangle(aPoint, aSize);
+ }
+ }
+
+ return aData;
+}
+
+OString PhysicalFontFace::GetGlyphName(sal_GlyphId nGlyphIndex, bool bValidate) const
+{
+ char aBuffer[256];
+ hb_font_glyph_to_string(GetHbUnscaledFont(), nGlyphIndex, aBuffer, 256);
+ if (bValidate)
+ {
+ // https://learn.microsoft.com/en-us/typography/opentype/spec/post#version-20
+ // Valid characters are limited to A–Z, a–z, 0–9, “.” (FULL STOP), and “_” (LOW LINE).
+ const char* p = aBuffer;
+ while ((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z')
+ || *p == '.' || *p == '_')
+ ++p;
+ if (*p != '\0')
+ return "g" + OString::number(nGlyphIndex);
+ }
+
+ return OString(aBuffer);
+}
+
+OUString PhysicalFontFace::GetName(NameID aNameID, const LanguageTag& rLanguageTag) const
+{
+ auto pHbFace = GetHbFace();
+
+ auto aHbLang = HB_LANGUAGE_INVALID;
+ if (rLanguageTag.getLanguageType() != LANGUAGE_NONE)
+ {
+ auto aLanguage(rLanguageTag.getBcp47().toUtf8());
+ aHbLang = hb_language_from_string(aLanguage.getStr(), aLanguage.getLength());
+ }
+
+ auto nName = hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, nullptr, nullptr);
+ if (!nName && aHbLang == HB_LANGUAGE_INVALID)
+ {
+ // Fallback to English if localized name is missing.
+ aHbLang = hb_language_from_string("en", 2);
+ nName = hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, nullptr, nullptr);
+ }
+
+ OUString sName;
+ if (nName)
+ {
+ std::vector<uint16_t> aBuf(++nName); // make space for terminating NUL.
+ hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, &nName, aBuf.data());
+ sName = OUString(reinterpret_cast<sal_Unicode*>(aBuf.data()), nName);
+ }
+
+ return sName;
+}
+
+const std::vector<hb_variation_t>& PhysicalFontFace::GetVariations(const LogicalFontInstance&) const
+{
+ if (!mxVariations)
+ {
+ SAL_WARN("vcl.fonts", "Getting font variations is not supported.");
+ mxVariations.emplace();
+ }
+ return *mxVariations;
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
diff --git a/vcl/source/font/PhysicalFontFamily.cxx b/vcl/source/font/PhysicalFontFamily.cxx
new file mode 100644
index 0000000000..6956394a59
--- /dev/null
+++ b/vcl/source/font/PhysicalFontFamily.cxx
@@ -0,0 +1,269 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <rtl/ustring.hxx>
+#include <unotools/fontdefs.hxx>
+
+#include <font/PhysicalFontFaceCollection.hxx>
+#include <font/PhysicalFontCollection.hxx>
+#include <utility>
+
+namespace vcl::font
+{
+
+void PhysicalFontFamily::CalcType( ImplFontAttrs& rType, FontWeight& rWeight, FontWidth& rWidth,
+ FontFamily eFamily, const utl::FontNameAttr* pFontAttr )
+{
+ if ( eFamily != FAMILY_DONTKNOW )
+ {
+ if ( eFamily == FAMILY_SWISS )
+ rType |= ImplFontAttrs::SansSerif;
+ else if ( eFamily == FAMILY_ROMAN )
+ rType |= ImplFontAttrs::Serif;
+ else if ( eFamily == FAMILY_SCRIPT )
+ rType |= ImplFontAttrs::Script;
+ else if ( eFamily == FAMILY_MODERN )
+ rType |= ImplFontAttrs::Fixed;
+ else if ( eFamily == FAMILY_DECORATIVE )
+ rType |= ImplFontAttrs::Decorative;
+ }
+
+ if ( pFontAttr )
+ {
+ rType |= pFontAttr->Type;
+
+ if ( ((rWeight == WEIGHT_DONTKNOW) || (rWeight == WEIGHT_NORMAL)) &&
+ (pFontAttr->Weight != WEIGHT_DONTKNOW) )
+ rWeight = pFontAttr->Weight;
+ if ( ((rWidth == WIDTH_DONTKNOW) || (rWidth == WIDTH_NORMAL)) &&
+ (pFontAttr->Width != WIDTH_DONTKNOW) )
+ rWidth = pFontAttr->Width;
+ }
+}
+
+static ImplFontAttrs lcl_IsCJKFont( std::u16string_view rFontName )
+{
+ // Test, if Fontname includes CJK characters --> In this case we
+ // mention that it is a CJK font
+ for(size_t i = 0; i < rFontName.size(); i++)
+ {
+ const sal_Unicode ch = rFontName[i];
+ // japanese
+ if ( ((ch >= 0x3040) && (ch <= 0x30FF)) ||
+ ((ch >= 0x3190) && (ch <= 0x319F)) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_JP;
+
+ // korean
+ if ( ((ch >= 0xAC00) && (ch <= 0xD7AF)) ||
+ ((ch >= 0xA960) && (ch <= 0xA97F)) ||
+ ((ch >= 0xD7B0) && (ch <= 0xD7FF)) ||
+ ((ch >= 0x3130) && (ch <= 0x318F)) ||
+ ((ch >= 0x1100) && (ch <= 0x11FF)) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_KR;
+
+ // chinese
+ if ( (ch >= 0x3400) && (ch <= 0x9FFF) )
+ return ImplFontAttrs::CJK|ImplFontAttrs::CJK_TC|ImplFontAttrs::CJK_SC;
+
+ // cjk
+ if ( ((ch >= 0x3000) && (ch <= 0xD7AF)) ||
+ ((ch >= 0xFF00) && (ch <= 0xFFEE)) )
+ return ImplFontAttrs::CJK;
+
+ }
+
+ return ImplFontAttrs::None;
+}
+
+PhysicalFontFamily::PhysicalFontFamily( OUString aSearchName )
+: maSearchName(std::move( aSearchName )),
+ mnTypeFaces( FontTypeFaces::NONE ),
+ meFamily( FAMILY_DONTKNOW ),
+ mePitch( PITCH_DONTKNOW ),
+ mnMinQuality( -1 ),
+ mnMatchType( ImplFontAttrs::None ),
+ meMatchWeight( WEIGHT_DONTKNOW ),
+ meMatchWidth( WIDTH_DONTKNOW )
+{}
+
+PhysicalFontFamily::~PhysicalFontFamily()
+{
+}
+
+void PhysicalFontFamily::AddFontFace( PhysicalFontFace* pNewFontFace )
+{
+ if( maFontFaces.empty() )
+ {
+ maFamilyName = pNewFontFace->GetFamilyName();
+ meFamily = pNewFontFace->GetFamilyType();
+ mePitch = pNewFontFace->GetPitch();
+ mnMinQuality = pNewFontFace->GetQuality();
+ }
+ else
+ {
+ if( meFamily == FAMILY_DONTKNOW )
+ meFamily = pNewFontFace->GetFamilyType();
+ if( mePitch == PITCH_DONTKNOW )
+ mePitch = pNewFontFace->GetPitch();
+ if( mnMinQuality > pNewFontFace->GetQuality() )
+ mnMinQuality = pNewFontFace->GetQuality();
+ }
+
+ // set attributes for attribute based font matching
+ mnTypeFaces |= FontTypeFaces::Scalable;
+
+ if( pNewFontFace->IsMicrosoftSymbolEncoded() )
+ mnTypeFaces |= FontTypeFaces::Symbol;
+ else
+ mnTypeFaces |= FontTypeFaces::NoneSymbol;
+
+ if( pNewFontFace->GetWeight() != WEIGHT_DONTKNOW )
+ {
+ if( pNewFontFace->GetWeight() >= WEIGHT_SEMIBOLD )
+ mnTypeFaces |= FontTypeFaces::Bold;
+ else if( pNewFontFace->GetWeight() <= WEIGHT_SEMILIGHT )
+ mnTypeFaces |= FontTypeFaces::Light;
+ else
+ mnTypeFaces |= FontTypeFaces::Normal;
+ }
+
+ if( pNewFontFace->GetItalic() == ITALIC_NONE )
+ mnTypeFaces |= FontTypeFaces::NoneItalic;
+ else if( (pNewFontFace->GetItalic() == ITALIC_NORMAL)
+ || (pNewFontFace->GetItalic() == ITALIC_OBLIQUE) )
+ mnTypeFaces |= FontTypeFaces::Italic;
+
+ // reassign name (sharing saves memory)
+ if( pNewFontFace->GetFamilyName() == GetFamilyName() )
+ pNewFontFace->SetFamilyName( GetFamilyName() );
+
+ // add the new physical font face, replacing existing font face if necessary
+ // TODO: get rid of linear search?
+ auto it(maFontFaces.begin());
+ for (; it != maFontFaces.end(); ++it)
+ {
+ PhysicalFontFace* pFoundFontFace = it->get();
+ sal_Int32 eComp = pNewFontFace->CompareIgnoreSize( *pFoundFontFace );
+ if( eComp > 0 )
+ continue;
+ if( eComp < 0 )
+ break;
+
+ // ignore duplicate if its quality is worse
+ if( pNewFontFace->GetQuality() < pFoundFontFace->GetQuality() )
+ return;
+
+ // keep the device font if its quality is good enough
+ if( pNewFontFace->GetQuality() == pFoundFontFace->GetQuality() )
+ return;
+
+ // replace existing font face with a better one
+ *it = pNewFontFace; // insert at sort position
+ return;
+ }
+
+ maFontFaces.emplace(it, pNewFontFace); // insert at sort position
+}
+
+// get font attributes using the normalized font family name
+void PhysicalFontFamily::InitMatchData( const utl::FontSubstConfiguration& rFontSubst,
+ const OUString& rSearchName )
+{
+ OUString aShortName;
+ OUString aMatchFamilyName(maMatchFamilyName);
+ // get font attributes from the decorated font name
+ utl::FontSubstConfiguration::getMapName( rSearchName, aShortName, aMatchFamilyName,
+ meMatchWeight, meMatchWidth, mnMatchType );
+ maMatchFamilyName = aMatchFamilyName;
+ const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( rSearchName );
+ // eventually use the stripped name
+ if( !pFontAttr )
+ if( aShortName != rSearchName )
+ pFontAttr = rFontSubst.getSubstInfo( aShortName );
+ CalcType( mnMatchType, meMatchWeight, meMatchWidth, meFamily, pFontAttr );
+ mnMatchType |= lcl_IsCJKFont( maFamilyName );
+}
+
+PhysicalFontFace* PhysicalFontFamily::FindBestFontFace( const vcl::font::FontSelectPattern& rFSD ) const
+{
+ if( maFontFaces.empty() )
+ return nullptr;
+ if( maFontFaces.size() == 1)
+ return maFontFaces[0].get();
+
+ // FontName+StyleName should map to FamilyName+StyleName
+ const OUString& rSearchName = rFSD.maTargetName;
+ OUString aTargetStyleName;
+ const OUString* pTargetStyleName = nullptr;
+ if((rSearchName.getLength() > maSearchName.getLength())
+ && rSearchName.startsWith( maSearchName ) )
+ {
+ aTargetStyleName = rSearchName.copy(maSearchName.getLength() + 1);
+ pTargetStyleName = &aTargetStyleName;
+ }
+
+ // TODO: linear search improve!
+ PhysicalFontFace* pBestFontFace = maFontFaces[0].get();
+ FontMatchStatus aFontMatchStatus = {0, pTargetStyleName};
+ for (auto const& font : maFontFaces)
+ {
+ PhysicalFontFace* pFoundFontFace = font.get();
+ if( pFoundFontFace->IsBetterMatch( rFSD, aFontMatchStatus ) )
+ pBestFontFace = pFoundFontFace;
+ }
+
+ return pBestFontFace;
+}
+
+// update device font list with unique font faces, with uniqueness
+// meaning different font attributes, but not different fonts sizes
+void PhysicalFontFamily::UpdateDevFontList( vcl::font::PhysicalFontFaceCollection& rDevFontList ) const
+{
+ PhysicalFontFace* pPrevFace = nullptr;
+ for (auto const& font : maFontFaces)
+ {
+ PhysicalFontFace* pFoundFontFace = font.get();
+ if( !pPrevFace || pFoundFontFace->CompareIgnoreSize( *pPrevFace ) )
+ rDevFontList.Add( pFoundFontFace );
+ pPrevFace = pFoundFontFace;
+ }
+}
+
+void PhysicalFontFamily::UpdateCloneFontList(vcl::font::PhysicalFontCollection& rFontCollection) const
+{
+ OUString aFamilyName = GetEnglishSearchFontName( GetFamilyName() );
+ PhysicalFontFamily* pFamily(nullptr);
+
+ for (auto const& font : maFontFaces)
+ {
+ PhysicalFontFace *pFoundFontFace = font.get();
+
+ if (!pFamily)
+ { // tdf#98989 lazy create as family without faces won't work
+ pFamily = rFontCollection.FindOrCreateFontFamily(aFamilyName);
+ }
+ assert(pFamily);
+ pFamily->AddFontFace( pFoundFontFace );
+ }
+}
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/font.cxx b/vcl/source/font/font.cxx
new file mode 100644
index 0000000000..6dfee423a9
--- /dev/null
+++ b/vcl/source/font/font.cxx
@@ -0,0 +1,1185 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <tools/stream.hxx>
+#include <tools/vcompat.hxx>
+#include <tools/gen.hxx>
+#include <unotools/configmgr.hxx>
+#include <unotools/fontcfg.hxx>
+#include <unotools/fontdefs.hxx>
+#include <o3tl/hash_combine.hxx>
+#include <i18nlangtag/mslangid.hxx>
+
+#include <vcl/font.hxx>
+#include <vcl/svapp.hxx>
+#include <vcl/outdev.hxx>
+#include <vcl/virdev.hxx>
+
+#include <impfont.hxx>
+#include <fontattributes.hxx>
+#include <fontsubset.hxx>
+#include <sft.hxx>
+
+#include <algorithm>
+#include <string_view>
+
+#include <vcl/TypeSerializer.hxx>
+
+#ifdef _WIN32
+#include <vcl/metric.hxx>
+#endif
+
+using namespace vcl;
+
+namespace
+{
+ Font::ImplType& GetGlobalDefault()
+ {
+ static Font::ImplType gDefault;
+ return gDefault;
+ }
+}
+
+Font::Font() : mpImplFont(GetGlobalDefault())
+{
+}
+
+Font::Font( const vcl::Font& rFont ) : mpImplFont( rFont.mpImplFont )
+{
+}
+
+Font::Font( vcl::Font&& rFont ) noexcept : mpImplFont( std::move(rFont.mpImplFont) )
+{
+}
+
+Font::Font( const OUString& rFamilyName, const Size& rSize )
+{
+ if (GetFamilyName() != rFamilyName
+ || GetAverageFontSize() != rSize)
+ {
+ mpImplFont->SetFamilyName( rFamilyName );
+ mpImplFont->SetFontSize( rSize );
+ }
+}
+
+Font::Font( const OUString& rFamilyName, const OUString& rStyleName, const Size& rSize )
+{
+ if (GetFamilyName() != rFamilyName
+ || GetStyleName() != rStyleName
+ || GetAverageFontSize() != rSize)
+ {
+ mpImplFont->SetFamilyName( rFamilyName );
+ mpImplFont->SetStyleName( rStyleName );
+ mpImplFont->SetFontSize( rSize );
+ }
+}
+
+Font::Font( FontFamily eFamily, const Size& rSize )
+{
+ if (GetFontFamily() != eFamily
+ || GetAverageFontSize() != rSize)
+ {
+ mpImplFont->SetFamilyType( eFamily );
+ mpImplFont->SetFontSize( rSize );
+ }
+}
+
+Font::~Font()
+{
+}
+
+void Font::SetColor( const Color& rColor )
+{
+ if (GetColor() != rColor)
+ {
+ mpImplFont->maColor = rColor;
+ }
+}
+
+void Font::SetFillColor( const Color& rColor )
+{
+ if (GetFillColor() != rColor)
+ {
+ mpImplFont->maFillColor = rColor;
+ if ( rColor.IsTransparent() )
+ mpImplFont->mbTransparent = true;
+ }
+}
+
+void Font::SetTransparent( bool bTransparent )
+{
+ if (IsTransparent() != bTransparent)
+ mpImplFont->mbTransparent = bTransparent;
+}
+
+void Font::SetAlignment( TextAlign eAlign )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meAlign != eAlign)
+ mpImplFont->SetAlignment(eAlign);
+}
+
+void Font::SetFamilyName( const OUString& rFamilyName )
+{
+ if (GetFamilyName() != rFamilyName)
+ mpImplFont->SetFamilyName( rFamilyName );
+}
+
+void Font::SetStyleName( const OUString& rStyleName )
+{
+ if (GetStyleName() != rStyleName)
+ mpImplFont->maStyleName = rStyleName;
+}
+
+void Font::SetFontSize( const Size& rSize )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetFontSize() != rSize)
+ mpImplFont->SetFontSize( rSize );
+}
+
+void Font::SetFamily( FontFamily eFamily )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetFamilyTypeNoAsk() != eFamily)
+ mpImplFont->SetFamilyType( eFamily );
+}
+
+void Font::SetCharSet( rtl_TextEncoding eCharSet )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetCharSet() != eCharSet)
+ mpImplFont->SetCharSet( eCharSet );
+}
+
+void Font::SetLanguageTag( const LanguageTag& rLanguageTag )
+{
+ if (GetLanguageTag() != rLanguageTag)
+ mpImplFont->maLanguageTag = rLanguageTag;
+}
+
+void Font::SetCJKContextLanguageTag( const LanguageTag& rLanguageTag )
+{
+ if (GetCJKContextLanguageTag() != rLanguageTag)
+ mpImplFont->maCJKLanguageTag = rLanguageTag;
+}
+
+void Font::SetLanguage( LanguageType eLanguage )
+{
+ if (GetLanguage() != eLanguage)
+ mpImplFont->maLanguageTag.reset( eLanguage);
+}
+
+void Font::SetCJKContextLanguage( LanguageType eLanguage )
+{
+ if (GetCJKContextLanguage() != eLanguage)
+ mpImplFont->maCJKLanguageTag.reset( eLanguage);
+}
+
+void Font::SetPitch( FontPitch ePitch )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetPitchNoAsk() != ePitch)
+ mpImplFont->SetPitch( ePitch );
+}
+
+void Font::SetOrientation( Degree10 nOrientation )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mnOrientation != nOrientation)
+ mpImplFont->mnOrientation = nOrientation;
+}
+
+void Font::SetVertical( bool bVertical )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mbVertical != bVertical)
+ mpImplFont->mbVertical = bVertical;
+}
+
+void Font::SetKerning( FontKerning eKerning )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meKerning != eKerning)
+ mpImplFont->meKerning = eKerning;
+}
+
+bool Font::IsKerning() const
+{
+ return mpImplFont->meKerning != FontKerning::NONE;
+}
+
+void Font::SetFixKerning( short nSpacing )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mnSpacing != nSpacing)
+ mpImplFont->mnSpacing = nSpacing;
+}
+
+short Font::GetFixKerning() const
+{
+ return mpImplFont->mnSpacing;
+}
+
+bool Font::IsFixKerning() const
+{
+ return mpImplFont->mnSpacing != 0;
+}
+
+void Font::SetWeight( FontWeight eWeight )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetWeightNoAsk() != eWeight)
+ mpImplFont->SetWeight( eWeight );
+}
+
+void Font::SetWidthType( FontWidth eWidth )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetWidthTypeNoAsk() != eWidth)
+ mpImplFont->SetWidthType( eWidth );
+}
+
+void Font::SetItalic( FontItalic eItalic )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->GetItalicNoAsk() != eItalic)
+ mpImplFont->SetItalic( eItalic );
+}
+
+void Font::SetOutline( bool bOutline )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mbOutline != bOutline)
+ mpImplFont->mbOutline = bOutline;
+}
+
+void Font::SetShadow( bool bShadow )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mbShadow != bShadow)
+ mpImplFont->mbShadow = bShadow;
+}
+
+void Font::SetUnderline( FontLineStyle eUnderline )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meUnderline != eUnderline)
+ mpImplFont->meUnderline = eUnderline;
+}
+
+void Font::SetOverline( FontLineStyle eOverline )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meOverline != eOverline)
+ mpImplFont->meOverline = eOverline;
+}
+
+void Font::SetStrikeout( FontStrikeout eStrikeout )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meStrikeout != eStrikeout)
+ mpImplFont->meStrikeout = eStrikeout;
+}
+
+void Font::SetRelief( FontRelief eRelief )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meRelief != eRelief)
+ mpImplFont->meRelief = eRelief;
+}
+
+void Font::SetEmphasisMark( FontEmphasisMark eEmphasisMark )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->meEmphasisMark != eEmphasisMark )
+ mpImplFont->meEmphasisMark = eEmphasisMark;
+}
+
+void Font::SetWordLineMode( bool bWordLine )
+{
+ if (const_cast<const ImplType&>(mpImplFont)->mbWordLine != bWordLine)
+ mpImplFont->mbWordLine = bWordLine;
+}
+
+Font& Font::operator=( const vcl::Font& rFont )
+{
+ mpImplFont = rFont.mpImplFont;
+ return *this;
+}
+
+Font& Font::operator=( vcl::Font&& rFont ) noexcept
+{
+ mpImplFont = std::move(rFont.mpImplFont);
+ return *this;
+}
+
+FontEmphasisMark Font::GetEmphasisMarkStyle() const
+{
+ FontEmphasisMark nEmphasisMark = GetEmphasisMark();
+
+ // If no Position is set, then calculate the default position, which
+ // depends on the language
+ if (!(nEmphasisMark & (FontEmphasisMark::PosAbove | FontEmphasisMark::PosBelow)))
+ {
+ LanguageType eLang = GetLanguage();
+ // In Chinese Simplified the EmphasisMarks are below/left
+ if (MsLangId::isSimplifiedChinese(eLang))
+ {
+ nEmphasisMark |= FontEmphasisMark::PosBelow;
+ }
+ else
+ {
+ eLang = GetCJKContextLanguage();
+
+ // In Chinese Simplified the EmphasisMarks are below/left
+ if (MsLangId::isSimplifiedChinese(eLang))
+ nEmphasisMark |= FontEmphasisMark::PosBelow;
+ else
+ nEmphasisMark |= FontEmphasisMark::PosAbove;
+ }
+ }
+
+ return nEmphasisMark;
+}
+
+bool Font::operator==( const vcl::Font& rFont ) const
+{
+ return mpImplFont == rFont.mpImplFont;
+}
+
+bool Font::EqualIgnoreColor( const vcl::Font& rFont ) const
+{
+ return mpImplFont->EqualIgnoreColor( *rFont.mpImplFont );
+}
+
+size_t Font::GetHashValueIgnoreColor() const
+{
+ return mpImplFont->GetHashValueIgnoreColor();
+}
+
+void Font::Merge( const vcl::Font& rFont )
+{
+ if ( !rFont.GetFamilyName().isEmpty() )
+ {
+ SetFamilyName( rFont.GetFamilyName() );
+ SetStyleName( rFont.GetStyleName() );
+ SetCharSet( GetCharSet() );
+ SetLanguageTag( rFont.GetLanguageTag() );
+ SetCJKContextLanguageTag( rFont.GetCJKContextLanguageTag() );
+ // don't use access methods here, might lead to AskConfig(), if DONTKNOW
+ SetFamily( rFont.mpImplFont->GetFamilyTypeNoAsk() );
+ SetPitch( rFont.mpImplFont->GetPitchNoAsk() );
+ }
+
+ // don't use access methods here, might lead to AskConfig(), if DONTKNOW
+ if ( rFont.mpImplFont->GetWeightNoAsk() != WEIGHT_DONTKNOW )
+ SetWeight( rFont.GetWeight() );
+ if ( rFont.mpImplFont->GetItalicNoAsk() != ITALIC_DONTKNOW )
+ SetItalic( rFont.GetItalic() );
+ if ( rFont.mpImplFont->GetWidthTypeNoAsk() != WIDTH_DONTKNOW )
+ SetWidthType( rFont.GetWidthType() );
+
+ if ( rFont.GetFontSize().Height() )
+ SetFontSize( rFont.GetFontSize() );
+ if ( rFont.GetUnderline() != LINESTYLE_DONTKNOW )
+ {
+ SetUnderline( rFont.GetUnderline() );
+ SetWordLineMode( rFont.IsWordLineMode() );
+ }
+ if ( rFont.GetOverline() != LINESTYLE_DONTKNOW )
+ {
+ SetOverline( rFont.GetOverline() );
+ SetWordLineMode( rFont.IsWordLineMode() );
+ }
+ if ( rFont.GetStrikeout() != STRIKEOUT_DONTKNOW )
+ {
+ SetStrikeout( rFont.GetStrikeout() );
+ SetWordLineMode( rFont.IsWordLineMode() );
+ }
+
+ // Defaults?
+ SetOrientation( rFont.GetOrientation() );
+ SetVertical( rFont.IsVertical() );
+ SetEmphasisMark( rFont.GetEmphasisMark() );
+ SetKerning( rFont.IsKerning() ? FontKerning::FontSpecific : FontKerning::NONE );
+ SetOutline( rFont.IsOutline() );
+ SetShadow( rFont.IsShadow() );
+ SetRelief( rFont.GetRelief() );
+}
+
+void Font::GetFontAttributes( FontAttributes& rAttrs ) const
+{
+ rAttrs.SetFamilyName( mpImplFont->GetFamilyName() );
+ rAttrs.SetStyleName( mpImplFont->maStyleName );
+ rAttrs.SetFamilyType( mpImplFont->GetFamilyTypeNoAsk() );
+ rAttrs.SetPitch( mpImplFont->GetPitchNoAsk() );
+ rAttrs.SetItalic( mpImplFont->GetItalicNoAsk() );
+ rAttrs.SetWeight( mpImplFont->GetWeightNoAsk() );
+ rAttrs.SetWidthType( WIDTH_DONTKNOW );
+ rAttrs.SetMicrosoftSymbolEncoded( mpImplFont->GetCharSet() == RTL_TEXTENCODING_SYMBOL );
+}
+
+// tdf#127471 for corrections on EMF/WMF we need the AvgFontWidth in Windows-specific notation
+tools::Long Font::GetOrCalculateAverageFontWidth() const
+{
+ if(0 == mpImplFont->GetCalculatedAverageFontWidth())
+ {
+ // VirtualDevice is not thread safe
+ SolarMutexGuard aGuard;
+
+ // create unscaled copy of font (this), a VirtualDevice and set it there
+ vcl::Font aUnscaledFont(*this);
+ ScopedVclPtr<VirtualDevice> pTempVirtualDevice(VclPtr<VirtualDevice>::Create());
+ aUnscaledFont.SetAverageFontWidth(0);
+ pTempVirtualDevice->SetFont(aUnscaledFont);
+
+#ifdef _WIN32
+ // on Windows systems use FontMetric to get/create AverageFontWidth from system
+ const FontMetric aMetric(pTempVirtualDevice->GetFontMetric());
+ const_cast<Font*>(this)->mpImplFont->SetCalculatedAverageFontWidth(aMetric.GetAverageFontWidth());
+#else
+ // On non-Windows systems we need to calculate AvgFontWidth
+ // as close as possible (discussion see documentation in task),
+ // so calculate it. For discussion of method used, see task
+ // buffer measure string creation, will always use the same
+ static constexpr OUString aMeasureString
+ = u"\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027"
+ "\u0028\u0029\u002A\u002B\u002C\u002D\u002E\u002F"
+ "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037"
+ "\u0038\u0039\u003A\u003B\u003C\u003D\u003E\u003F"
+ "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047"
+ "\u0048\u0049\u004A\u004B\u004C\u004D\u004E\u004F"
+ "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057"
+ "\u0058\u0059\u005A\u005B\u005C\u005D\u005E\u005F"
+ "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067"
+ "\u0068\u0069\u006A\u006B\u006C\u006D\u006E\u006F"
+ "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077"
+ "\u0078\u0079\u007A\u007B\u007C\u007D\u007E"_ustr;
+
+ const double fAverageFontWidth(
+ pTempVirtualDevice->GetTextWidth(aMeasureString) /
+ static_cast<double>(aMeasureString.getLength()));
+ const_cast<Font*>(this)->mpImplFont->SetCalculatedAverageFontWidth(basegfx::fround(fAverageFontWidth));
+#endif
+ }
+
+ return mpImplFont->GetCalculatedAverageFontWidth();
+}
+
+SvStream& ReadImplFont( SvStream& rIStm, ImplFont& rImplFont, tools::Long& rnNormedFontScaling )
+{
+ VersionCompatRead aCompat( rIStm );
+ sal_uInt16 nTmp16(0);
+ sal_Int16 nTmps16(0);
+ bool bTmp(false);
+ sal_uInt8 nTmp8(0);
+
+ rImplFont.SetFamilyName( rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet()) );
+ rImplFont.maStyleName = rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet());
+ TypeSerializer aSerializer(rIStm);
+ aSerializer.readSize(rImplFont.maAverageFontSize);
+
+ static const bool bFuzzing = utl::ConfigManager::IsFuzzing();
+ if (bFuzzing)
+ {
+ if (rImplFont.maAverageFontSize.Width() > 8192)
+ {
+ SAL_WARN("vcl.gdi", "suspicious average width of: " << rImplFont.maAverageFontSize.Width());
+ rImplFont.maAverageFontSize.setWidth(8192);
+ }
+ if (rImplFont.maAverageFontSize.Height() > 8192)
+ {
+ SAL_WARN("vcl.gdi", "suspicious average height of: " << rImplFont.maAverageFontSize.Height());
+ rImplFont.maAverageFontSize.setHeight(8192);
+ }
+ }
+
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.SetCharSet( static_cast<rtl_TextEncoding>(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.SetFamilyType( static_cast<FontFamily>(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.SetPitch( static_cast<FontPitch>(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.SetWeight( static_cast<FontWeight>(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.meUnderline = static_cast<FontLineStyle>(nTmp16);
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.meStrikeout = static_cast<FontStrikeout>(nTmp16);
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.SetItalic( static_cast<FontItalic>(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.maLanguageTag.reset( LanguageType(nTmp16) );
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.meWidthType = static_cast<FontWidth>(nTmp16);
+
+ rIStm.ReadInt16( nTmps16 ); rImplFont.mnOrientation = Degree10(nTmps16);
+
+ rIStm.ReadCharAsBool( bTmp ); rImplFont.mbWordLine = bTmp;
+ rIStm.ReadCharAsBool( bTmp ); rImplFont.mbOutline = bTmp;
+ rIStm.ReadCharAsBool( bTmp ); rImplFont.mbShadow = bTmp;
+ rIStm.ReadUChar( nTmp8 ); rImplFont.meKerning = static_cast<FontKerning>(nTmp8);
+
+ if( aCompat.GetVersion() >= 2 )
+ {
+ rIStm.ReadUChar( nTmp8 ); rImplFont.meRelief = static_cast<FontRelief>(nTmp8);
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.maCJKLanguageTag.reset( LanguageType(nTmp16) );
+ rIStm.ReadCharAsBool( bTmp ); rImplFont.mbVertical = bTmp;
+ rIStm.ReadUInt16( nTmp16 );
+ rImplFont.meEmphasisMark = static_cast<FontEmphasisMark>(nTmp16 & o3tl::typed_flags<FontEmphasisMark>::mask);
+ }
+
+ if( aCompat.GetVersion() >= 3 )
+ {
+ rIStm.ReadUInt16( nTmp16 ); rImplFont.meOverline = static_cast<FontLineStyle>(nTmp16);
+ }
+
+ // tdf#127471 read NormedFontScaling
+ if( aCompat.GetVersion() >= 4 )
+ {
+ sal_Int32 nNormedFontScaling(0);
+ rIStm.ReadInt32(nNormedFontScaling);
+ rnNormedFontScaling = nNormedFontScaling;
+ }
+
+ if( aCompat.GetVersion() >= 5 )
+ {
+ rIStm.ReadInt16( nTmps16 );
+ rImplFont.mnSpacing = nTmps16;
+ }
+
+ // Relief
+ // CJKContextLanguage
+
+ return rIStm;
+}
+
+SvStream& WriteImplFont( SvStream& rOStm, const ImplFont& rImplFont, tools::Long nNormedFontScaling )
+{
+ // tdf#127471 increase to version 4
+ // tdf#66819 increase to version 5
+ VersionCompatWrite aCompat( rOStm, 5 );
+
+ TypeSerializer aSerializer(rOStm);
+ rOStm.WriteUniOrByteString( rImplFont.GetFamilyName(), rOStm.GetStreamCharSet() );
+ rOStm.WriteUniOrByteString( rImplFont.GetStyleName(), rOStm.GetStreamCharSet() );
+ aSerializer.writeSize(rImplFont.maAverageFontSize);
+
+ rOStm.WriteUInt16( GetStoreCharSet( rImplFont.GetCharSet() ) );
+ rOStm.WriteUInt16( rImplFont.GetFamilyTypeNoAsk() );
+ rOStm.WriteUInt16( rImplFont.GetPitchNoAsk() );
+ rOStm.WriteUInt16( rImplFont.GetWeightNoAsk() );
+ rOStm.WriteUInt16( rImplFont.meUnderline );
+ rOStm.WriteUInt16( rImplFont.meStrikeout );
+ rOStm.WriteUInt16( rImplFont.GetItalicNoAsk() );
+ rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.maLanguageTag.getLanguageType( false)) );
+ rOStm.WriteUInt16( rImplFont.GetWidthTypeNoAsk() );
+
+ rOStm.WriteInt16( rImplFont.mnOrientation.get() );
+
+ rOStm.WriteBool( rImplFont.mbWordLine );
+ rOStm.WriteBool( rImplFont.mbOutline );
+ rOStm.WriteBool( rImplFont.mbShadow );
+ rOStm.WriteUChar( static_cast<sal_uInt8>(rImplFont.meKerning) );
+
+ // new in version 2
+ rOStm.WriteUChar( static_cast<unsigned char>(rImplFont.meRelief) );
+ rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.maCJKLanguageTag.getLanguageType( false)) );
+ rOStm.WriteBool( rImplFont.mbVertical );
+ rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.meEmphasisMark) );
+
+ // new in version 3
+ rOStm.WriteUInt16( rImplFont.meOverline );
+
+ // new in version 4, NormedFontScaling
+ rOStm.WriteInt32(nNormedFontScaling);
+
+ // new in version 5
+ rOStm.WriteInt16( rImplFont.mnSpacing );
+ return rOStm;
+}
+
+SvStream& ReadFont( SvStream& rIStm, vcl::Font& rFont )
+{
+ // tdf#127471 try to read NormedFontScaling
+ tools::Long nNormedFontScaling(0);
+ SvStream& rRetval(ReadImplFont( rIStm, *rFont.mpImplFont, nNormedFontScaling ));
+
+ if (nNormedFontScaling > 0)
+ {
+#ifdef _WIN32
+ // we run on windows and a NormedFontScaling was written
+ if(rFont.GetFontSize().getWidth() == nNormedFontScaling)
+ {
+ // the writing producer was running on a non-windows system, adapt to needed windows
+ // system-specific pre-multiply
+ const tools::Long nHeight(std::max<tools::Long>(rFont.GetFontSize().getHeight(), 0));
+ sal_uInt32 nScaledWidth(0);
+
+ if(nHeight > 0)
+ {
+ vcl::Font aUnscaledFont(rFont);
+ aUnscaledFont.SetAverageFontWidth(0);
+ const FontMetric aUnscaledFontMetric(Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont));
+
+ if (nHeight > 0)
+ {
+ const double fScaleFactor(static_cast<double>(nNormedFontScaling) / static_cast<double>(nHeight));
+ nScaledWidth = basegfx::fround(static_cast<double>(aUnscaledFontMetric.GetAverageFontWidth()) * fScaleFactor);
+ }
+ }
+
+ rFont.SetAverageFontWidth(nScaledWidth);
+ }
+ else
+ {
+ // the writing producer was on a windows system, correct pre-multiplied value
+ // is already set, nothing to do. Ignore 2nd value. Here a check
+ // could be done if adapting the 2nd, NormedFontScaling value would be similar to
+ // the set value for plausibility reasons
+ }
+#else
+ // we do not run on windows and a NormedFontScaling was written
+ if(rFont.GetFontSize().getWidth() == nNormedFontScaling)
+ {
+ // the writing producer was not on a windows system, correct value
+ // already set, nothing to do
+ }
+ else
+ {
+ // the writing producer was on a windows system, correct FontScaling.
+ // The correct non-pre-multiplied value is the 2nd one, use it
+ rFont.SetAverageFontWidth(nNormedFontScaling);
+ }
+#endif
+ }
+
+ return rRetval;
+}
+
+SvStream& WriteFont( SvStream& rOStm, const vcl::Font& rFont )
+{
+ // tdf#127471 prepare NormedFontScaling for additional export
+ tools::Long nNormedFontScaling(rFont.GetFontSize().getWidth());
+
+ // FontScaling usage at vcl-Font is detected by checking that FontWidth != 0
+ if (nNormedFontScaling > 0)
+ {
+ const tools::Long nHeight(std::max<tools::Long>(rFont.GetFontSize().getHeight(), 0));
+
+ // check for negative height
+ if(0 == nHeight)
+ {
+ nNormedFontScaling = 0;
+ }
+ else
+ {
+#ifdef _WIN32
+ // for WIN32 the value is pre-multiplied with AverageFontWidth
+ // which makes it system-dependent. Turn that back to have the
+ // normed non-windows form of it for export as 2nd value
+ vcl::Font aUnscaledFont(rFont);
+ aUnscaledFont.SetAverageFontWidth(0);
+ const FontMetric aUnscaledFontMetric(
+ Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont));
+
+ if (aUnscaledFontMetric.GetAverageFontWidth() > 0)
+ {
+ const double fScaleFactor(
+ static_cast<double>(nNormedFontScaling)
+ / static_cast<double>(aUnscaledFontMetric.GetAverageFontWidth()));
+ nNormedFontScaling = static_cast<tools::Long>(fScaleFactor * nHeight);
+ }
+#endif
+ }
+ }
+
+ return WriteImplFont( rOStm, *rFont.mpImplFont, nNormedFontScaling );
+}
+
+namespace
+{
+ bool identifyTrueTypeFont( const void* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult )
+ {
+ bool bResult = false;
+ TrueTypeFont* pTTF = nullptr;
+ if( OpenTTFontBuffer( i_pBuffer, i_nSize, 0, &pTTF ) == SFErrCodes::Ok )
+ {
+ TTGlobalFontInfo aInfo;
+ GetTTGlobalFontInfo( pTTF, &aInfo );
+ // most importantly: the family name
+ if( !aInfo.ufamily.isEmpty() )
+ o_rResult.SetFamilyName( aInfo.ufamily );
+ else if( !aInfo.family.isEmpty() )
+ o_rResult.SetFamilyName( OStringToOUString( aInfo.family, RTL_TEXTENCODING_ASCII_US ) );
+ // set weight
+ if( aInfo.weight )
+ {
+ if( aInfo.weight < FW_EXTRALIGHT )
+ o_rResult.SetWeight( WEIGHT_THIN );
+ else if( aInfo.weight < FW_LIGHT )
+ o_rResult.SetWeight( WEIGHT_ULTRALIGHT );
+ else if( aInfo.weight < FW_NORMAL )
+ o_rResult.SetWeight( WEIGHT_LIGHT );
+ else if( aInfo.weight < FW_MEDIUM )
+ o_rResult.SetWeight( WEIGHT_NORMAL );
+ else if( aInfo.weight < FW_SEMIBOLD )
+ o_rResult.SetWeight( WEIGHT_MEDIUM );
+ else if( aInfo.weight < FW_BOLD )
+ o_rResult.SetWeight( WEIGHT_SEMIBOLD );
+ else if( aInfo.weight < FW_EXTRABOLD )
+ o_rResult.SetWeight( WEIGHT_BOLD );
+ else if( aInfo.weight < FW_BLACK )
+ o_rResult.SetWeight( WEIGHT_ULTRABOLD );
+ else
+ o_rResult.SetWeight( WEIGHT_BLACK );
+ }
+ else
+ o_rResult.SetWeight( (aInfo.macStyle & 1) ? WEIGHT_BOLD : WEIGHT_NORMAL );
+ // set width
+ if( aInfo.width )
+ {
+ if( aInfo.width == FWIDTH_ULTRA_CONDENSED )
+ o_rResult.SetAverageFontWidth( WIDTH_ULTRA_CONDENSED );
+ else if( aInfo.width == FWIDTH_EXTRA_CONDENSED )
+ o_rResult.SetAverageFontWidth( WIDTH_EXTRA_CONDENSED );
+ else if( aInfo.width == FWIDTH_CONDENSED )
+ o_rResult.SetAverageFontWidth( WIDTH_CONDENSED );
+ else if( aInfo.width == FWIDTH_SEMI_CONDENSED )
+ o_rResult.SetAverageFontWidth( WIDTH_SEMI_CONDENSED );
+ else if( aInfo.width == FWIDTH_NORMAL )
+ o_rResult.SetAverageFontWidth( WIDTH_NORMAL );
+ else if( aInfo.width == FWIDTH_SEMI_EXPANDED )
+ o_rResult.SetAverageFontWidth( WIDTH_SEMI_EXPANDED );
+ else if( aInfo.width == FWIDTH_EXPANDED )
+ o_rResult.SetAverageFontWidth( WIDTH_EXPANDED );
+ else if( aInfo.width == FWIDTH_EXTRA_EXPANDED )
+ o_rResult.SetAverageFontWidth( WIDTH_EXTRA_EXPANDED );
+ else if( aInfo.width >= FWIDTH_ULTRA_EXPANDED )
+ o_rResult.SetAverageFontWidth( WIDTH_ULTRA_EXPANDED );
+ }
+ // set italic
+ o_rResult.SetItalic( (aInfo.italicAngle != 0) ? ITALIC_NORMAL : ITALIC_NONE );
+
+ // set pitch
+ o_rResult.SetPitch( (aInfo.pitch == 0) ? PITCH_VARIABLE : PITCH_FIXED );
+
+ // set style name
+ if( !aInfo.usubfamily.isEmpty() )
+ o_rResult.SetStyleName( aInfo.usubfamily );
+ else if( !aInfo.subfamily.isEmpty() )
+ o_rResult.SetStyleName( OUString::createFromAscii( aInfo.subfamily ) );
+
+ // cleanup
+ CloseTTFont( pTTF );
+ // success
+ bResult = true;
+ }
+ return bResult;
+ }
+
+ struct WeightSearchEntry
+ {
+ const char* string;
+ int string_len;
+ FontWeight weight;
+
+ bool operator<( const WeightSearchEntry& rRight ) const
+ {
+ return rtl_str_compareIgnoreAsciiCase_WithLength( string, string_len, rRight.string, rRight.string_len ) < 0;
+ }
+ }
+ const weight_table[] =
+ {
+ { "black", 5, WEIGHT_BLACK },
+ { "bold", 4, WEIGHT_BOLD },
+ { "book", 4, WEIGHT_LIGHT },
+ { "demi", 4, WEIGHT_SEMIBOLD },
+ { "heavy", 5, WEIGHT_BLACK },
+ { "light", 5, WEIGHT_LIGHT },
+ { "medium", 6, WEIGHT_MEDIUM },
+ { "regular", 7, WEIGHT_NORMAL },
+ { "super", 5, WEIGHT_ULTRABOLD },
+ { "thin", 4, WEIGHT_THIN }
+ };
+
+ bool identifyType1Font( const char* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult )
+ {
+ // might be a type1, find eexec
+ const char* pStream = i_pBuffer;
+ const char* const pExec = "eexec";
+ const char* pExecPos = std::search( pStream, pStream+i_nSize, pExec, pExec+5 );
+ if( pExecPos != pStream+i_nSize)
+ {
+ // find /FamilyName entry
+ static const char* const pFam = "/FamilyName";
+ const char* pFamPos = std::search( pStream, pExecPos, pFam, pFam+11 );
+ if( pFamPos != pExecPos )
+ {
+ // extract the string value behind /FamilyName
+ const char* pOpen = pFamPos+11;
+ while( pOpen < pExecPos && *pOpen != '(' )
+ pOpen++;
+ const char* pClose = pOpen;
+ while( pClose < pExecPos && *pClose != ')' )
+ pClose++;
+ if( pClose - pOpen > 1 )
+ {
+ o_rResult.SetFamilyName( OStringToOUString( std::string_view( pOpen+1, pClose-pOpen-1 ), RTL_TEXTENCODING_ASCII_US ) );
+ }
+ }
+
+ // parse /ItalicAngle
+ static const char* const pItalic = "/ItalicAngle";
+ const char* pItalicPos = std::search( pStream, pExecPos, pItalic, pItalic+12 );
+ if( pItalicPos != pExecPos )
+ {
+ const char* pItalicEnd = pItalicPos + 12;
+ auto nItalic = rtl_str_toInt64_WithLength(pItalicEnd, 10, pExecPos - pItalicEnd);
+ o_rResult.SetItalic( (nItalic != 0) ? ITALIC_NORMAL : ITALIC_NONE );
+ }
+
+ // parse /Weight
+ static const char* const pWeight = "/Weight";
+ const char* pWeightPos = std::search( pStream, pExecPos, pWeight, pWeight+7 );
+ if( pWeightPos != pExecPos )
+ {
+ // extract the string value behind /Weight
+ const char* pOpen = pWeightPos+7;
+ while( pOpen < pExecPos && *pOpen != '(' )
+ pOpen++;
+ const char* pClose = pOpen;
+ while( pClose < pExecPos && *pClose != ')' )
+ pClose++;
+ if( pClose - pOpen > 1 )
+ {
+ WeightSearchEntry aEnt;
+ aEnt.string = pOpen+1;
+ aEnt.string_len = (pClose-pOpen)-1;
+ aEnt.weight = WEIGHT_NORMAL;
+ WeightSearchEntry const * pFound = std::lower_bound( std::begin(weight_table), std::end(weight_table), aEnt );
+ if( pFound != std::end(weight_table) &&
+ rtl_str_compareIgnoreAsciiCase_WithLength( pFound->string, pFound->string_len, aEnt.string, aEnt.string_len) == 0 )
+ o_rResult.SetWeight( pFound->weight );
+ }
+ }
+
+ // parse isFixedPitch
+ static const char* const pFixed = "/isFixedPitch";
+ const char* pFixedPos = std::search( pStream, pExecPos, pFixed, pFixed+13 );
+ if( pFixedPos != pExecPos )
+ {
+ // skip whitespace
+ while( pFixedPos < pExecPos-4 &&
+ ( *pFixedPos == ' ' ||
+ *pFixedPos == '\t' ||
+ *pFixedPos == '\r' ||
+ *pFixedPos == '\n' ) )
+ {
+ pFixedPos++;
+ }
+ // find "true" value
+ if( rtl_str_compareIgnoreAsciiCase_WithLength( pFixedPos, 4, "true", 4 ) == 0 )
+ o_rResult.SetPitch( PITCH_FIXED );
+ else
+ o_rResult.SetPitch( PITCH_VARIABLE );
+ }
+ }
+ return false;
+ }
+}
+
+Font Font::identifyFont( const void* i_pBuffer, sal_uInt32 i_nSize )
+{
+ Font aResult;
+ if( ! identifyTrueTypeFont( i_pBuffer, i_nSize, aResult ) )
+ {
+ const char* pStream = static_cast<const char*>(i_pBuffer);
+ if( pStream && i_nSize > 100 &&
+ *pStream == '%' && pStream[1] == '!' )
+ {
+ identifyType1Font( pStream, i_nSize, aResult );
+ }
+ }
+
+ return aResult;
+}
+
+// The inlines from the font.hxx header are now instantiated for pImpl-ification
+const Color& Font::GetColor() const { return mpImplFont->maColor; }
+const Color& Font::GetFillColor() const { return mpImplFont->maFillColor; }
+bool Font::IsTransparent() const { return mpImplFont->mbTransparent; }
+
+TextAlign Font::GetAlignment() const { return mpImplFont->GetAlignment(); }
+
+const OUString& Font::GetFamilyName() const { return mpImplFont->GetFamilyName(); }
+const OUString& Font::GetStyleName() const { return mpImplFont->maStyleName; }
+const FontFamily& Font::GetFontFamily() const { return mpImplFont->meFamily; }
+
+const Size& Font::GetFontSize() const { return mpImplFont->GetFontSize(); }
+void Font::SetFontHeight( tools::Long nHeight ) { SetFontSize( Size( std::as_const(mpImplFont)->GetFontSize().Width(), nHeight ) ); }
+tools::Long Font::GetFontHeight() const { return mpImplFont->GetFontSize().Height(); }
+void Font::SetAverageFontWidth( tools::Long nWidth ) { SetFontSize( Size( nWidth, std::as_const(mpImplFont)->GetFontSize().Height() ) ); }
+tools::Long Font::GetAverageFontWidth() const { return mpImplFont->GetFontSize().Width(); }
+const Size& Font::GetAverageFontSize() const { return mpImplFont->maAverageFontSize; }
+
+rtl_TextEncoding Font::GetCharSet() const { return mpImplFont->GetCharSet(); }
+
+const LanguageTag& Font::GetLanguageTag() const { return mpImplFont->maLanguageTag; }
+const LanguageTag& Font::GetCJKContextLanguageTag() const { return mpImplFont->maCJKLanguageTag; }
+LanguageType Font::GetLanguage() const { return mpImplFont->maLanguageTag.getLanguageType( false); }
+LanguageType Font::GetCJKContextLanguage() const { return mpImplFont->maCJKLanguageTag.getLanguageType( false); }
+
+Degree10 Font::GetOrientation() const { return mpImplFont->mnOrientation; }
+bool Font::IsVertical() const { return mpImplFont->mbVertical; }
+FontKerning Font::GetKerning() const { return mpImplFont->meKerning; }
+
+FontPitch Font::GetPitch() { return mpImplFont->GetPitch(); }
+FontWeight Font::GetWeight() { return mpImplFont->GetWeight(); }
+FontWidth Font::GetWidthType() { return mpImplFont->GetWidthType(); }
+FontItalic Font::GetItalic() { return mpImplFont->GetItalic(); }
+FontFamily Font::GetFamilyType() { return mpImplFont->GetFamilyType(); }
+
+FontPitch Font::GetPitch() const { return mpImplFont->GetPitchNoAsk(); }
+FontWeight Font::GetWeight() const { return mpImplFont->GetWeightNoAsk(); }
+FontWidth Font::GetWidthType() const { return mpImplFont->GetWidthTypeNoAsk(); }
+FontItalic Font::GetItalic() const { return mpImplFont->GetItalicNoAsk(); }
+FontFamily Font::GetFamilyType() const { return mpImplFont->GetFamilyTypeNoAsk(); }
+
+int Font::GetQuality() const { return mpImplFont->GetQuality(); }
+void Font::SetQuality( int nQuality ) { mpImplFont->SetQuality( nQuality ); }
+void Font::IncreaseQualityBy( int nQualityAmount ) { mpImplFont->IncreaseQualityBy( nQualityAmount ); }
+void Font::DecreaseQualityBy( int nQualityAmount ) { mpImplFont->DecreaseQualityBy( nQualityAmount ); }
+
+bool Font::IsOutline() const { return mpImplFont->mbOutline; }
+bool Font::IsShadow() const { return mpImplFont->mbShadow; }
+FontRelief Font::GetRelief() const { return mpImplFont->meRelief; }
+FontLineStyle Font::GetUnderline() const { return mpImplFont->meUnderline; }
+FontLineStyle Font::GetOverline() const { return mpImplFont->meOverline; }
+FontStrikeout Font::GetStrikeout() const { return mpImplFont->meStrikeout; }
+FontEmphasisMark Font::GetEmphasisMark() const { return mpImplFont->meEmphasisMark; }
+bool Font::IsWordLineMode() const { return mpImplFont->mbWordLine; }
+bool Font::IsSameInstance( const vcl::Font& rFont ) const { return (mpImplFont == rFont.mpImplFont); }
+
+
+ImplFont::ImplFont() :
+ meWeight( WEIGHT_DONTKNOW ),
+ meFamily( FAMILY_DONTKNOW ),
+ mePitch( PITCH_DONTKNOW ),
+ meWidthType( WIDTH_DONTKNOW ),
+ meItalic( ITALIC_NONE ),
+ meAlign( ALIGN_TOP ),
+ meUnderline( LINESTYLE_NONE ),
+ meOverline( LINESTYLE_NONE ),
+ meStrikeout( STRIKEOUT_NONE ),
+ meRelief( FontRelief::NONE ),
+ meEmphasisMark( FontEmphasisMark::NONE ),
+ meKerning( FontKerning::FontSpecific ),
+ mnSpacing( 0 ),
+ meCharSet( RTL_TEXTENCODING_DONTKNOW ),
+ maLanguageTag( LANGUAGE_DONTKNOW ),
+ maCJKLanguageTag( LANGUAGE_DONTKNOW ),
+ mbOutline( false ),
+ mbConfigLookup( false ),
+ mbShadow( false ),
+ mbVertical( false ),
+ mbTransparent( true ),
+ maColor( COL_TRANSPARENT ),
+ maFillColor( COL_TRANSPARENT ),
+ mbWordLine( false ),
+ mnOrientation( 0 ),
+ mnQuality( 0 ),
+ mnCalculatedAverageFontWidth( 0 )
+{}
+
+ImplFont::ImplFont( const ImplFont& rImplFont ) :
+ maFamilyName( rImplFont.maFamilyName ),
+ maStyleName( rImplFont.maStyleName ),
+ meWeight( rImplFont.meWeight ),
+ meFamily( rImplFont.meFamily ),
+ mePitch( rImplFont.mePitch ),
+ meWidthType( rImplFont.meWidthType ),
+ meItalic( rImplFont.meItalic ),
+ meAlign( rImplFont.meAlign ),
+ meUnderline( rImplFont.meUnderline ),
+ meOverline( rImplFont.meOverline ),
+ meStrikeout( rImplFont.meStrikeout ),
+ meRelief( rImplFont.meRelief ),
+ meEmphasisMark( rImplFont.meEmphasisMark ),
+ meKerning( rImplFont.meKerning ),
+ mnSpacing( rImplFont.mnSpacing ),
+ maAverageFontSize( rImplFont.maAverageFontSize ),
+ meCharSet( rImplFont.meCharSet ),
+ maLanguageTag( rImplFont.maLanguageTag ),
+ maCJKLanguageTag( rImplFont.maCJKLanguageTag ),
+ mbOutline( rImplFont.mbOutline ),
+ mbConfigLookup( rImplFont.mbConfigLookup ),
+ mbShadow( rImplFont.mbShadow ),
+ mbVertical( rImplFont.mbVertical ),
+ mbTransparent( rImplFont.mbTransparent ),
+ maColor( rImplFont.maColor ),
+ maFillColor( rImplFont.maFillColor ),
+ mbWordLine( rImplFont.mbWordLine ),
+ mnOrientation( rImplFont.mnOrientation ),
+ mnQuality( rImplFont.mnQuality ),
+ mnCalculatedAverageFontWidth( rImplFont.mnCalculatedAverageFontWidth )
+{}
+
+bool ImplFont::operator==( const ImplFont& rOther ) const
+{
+ if(!EqualIgnoreColor( rOther ))
+ return false;
+
+ if( (maColor != rOther.maColor)
+ || (maFillColor != rOther.maFillColor) )
+ return false;
+
+ return true;
+}
+
+bool ImplFont::EqualIgnoreColor( const ImplFont& rOther ) const
+{
+ // equality tests split up for easier debugging
+ if( (meWeight != rOther.meWeight)
+ || (meItalic != rOther.meItalic)
+ || (meFamily != rOther.meFamily)
+ || (mePitch != rOther.mePitch) )
+ return false;
+
+ if( (meCharSet != rOther.meCharSet)
+ || (maLanguageTag != rOther.maLanguageTag)
+ || (maCJKLanguageTag != rOther.maCJKLanguageTag)
+ || (meAlign != rOther.meAlign) )
+ return false;
+
+ if( (maAverageFontSize != rOther.maAverageFontSize)
+ || (mnOrientation != rOther.mnOrientation)
+ || (mbVertical != rOther.mbVertical) )
+ return false;
+
+ if( (maFamilyName != rOther.maFamilyName)
+ || (maStyleName != rOther.maStyleName) )
+ return false;
+
+ if( (meUnderline != rOther.meUnderline)
+ || (meOverline != rOther.meOverline)
+ || (meStrikeout != rOther.meStrikeout)
+ || (meRelief != rOther.meRelief)
+ || (meEmphasisMark != rOther.meEmphasisMark)
+ || (mbWordLine != rOther.mbWordLine)
+ || (mbOutline != rOther.mbOutline)
+ || (mbShadow != rOther.mbShadow)
+ || (meKerning != rOther.meKerning)
+ || (mnSpacing != rOther.mnSpacing)
+ || (mbTransparent != rOther.mbTransparent) )
+ return false;
+
+ return true;
+}
+
+size_t ImplFont::GetHashValue() const
+{
+ size_t hash = GetHashValueIgnoreColor();
+ o3tl::hash_combine( hash, static_cast<sal_uInt32>( maColor ));
+ o3tl::hash_combine( hash, static_cast<sal_uInt32>( maFillColor ));
+ return hash;
+}
+
+size_t ImplFont::GetHashValueIgnoreColor() const
+{
+ size_t hash = 0;
+
+ o3tl::hash_combine( hash, meWeight );
+ o3tl::hash_combine( hash, meItalic );
+ o3tl::hash_combine( hash, meFamily );
+ o3tl::hash_combine( hash, mePitch );
+
+ o3tl::hash_combine( hash, meCharSet );
+ o3tl::hash_combine( hash, maLanguageTag.getLanguageType( false ).get());
+ o3tl::hash_combine( hash, maCJKLanguageTag.getLanguageType( false ).get());
+ o3tl::hash_combine( hash, meAlign );
+
+ o3tl::hash_combine( hash, maAverageFontSize.GetHashValue());
+ o3tl::hash_combine( hash, mnOrientation.get());
+ o3tl::hash_combine( hash, mbVertical );
+
+ o3tl::hash_combine( hash, maFamilyName );
+ o3tl::hash_combine( hash, maStyleName );
+
+ o3tl::hash_combine( hash, meUnderline );
+ o3tl::hash_combine( hash, meOverline );
+ o3tl::hash_combine( hash, meStrikeout );
+ o3tl::hash_combine( hash, meRelief );
+ o3tl::hash_combine( hash, meEmphasisMark );
+ o3tl::hash_combine( hash, mbWordLine );
+ o3tl::hash_combine( hash, mbOutline );
+ o3tl::hash_combine( hash, mbShadow );
+ o3tl::hash_combine( hash, meKerning );
+ o3tl::hash_combine( hash, mnSpacing );
+ o3tl::hash_combine( hash, mbTransparent );
+
+ return hash;
+}
+
+void ImplFont::AskConfig()
+{
+ if( mbConfigLookup )
+ return;
+
+ mbConfigLookup = true;
+
+ // prepare the FontSubst configuration lookup
+ const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get();
+
+ OUString aShortName;
+ OUString aFamilyName;
+ ImplFontAttrs nType = ImplFontAttrs::None;
+ FontWeight eWeight = WEIGHT_DONTKNOW;
+ FontWidth eWidthType = WIDTH_DONTKNOW;
+ OUString aMapName = GetEnglishSearchFontName( maFamilyName );
+
+ utl::FontSubstConfiguration::getMapName( aMapName,
+ aShortName, aFamilyName, eWeight, eWidthType, nType );
+
+ // lookup the font name in the configuration
+ const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( aMapName );
+
+ // if the direct lookup failed try again with an alias name
+ if ( !pFontAttr && (aShortName != aMapName) )
+ pFontAttr = rFontSubst.getSubstInfo( aShortName );
+
+ if( pFontAttr )
+ {
+ // the font was found in the configuration
+ if( meFamily == FAMILY_DONTKNOW )
+ {
+ if ( pFontAttr->Type & ImplFontAttrs::Serif )
+ meFamily = FAMILY_ROMAN;
+ else if ( pFontAttr->Type & ImplFontAttrs::SansSerif )
+ meFamily = FAMILY_SWISS;
+ else if ( pFontAttr->Type & ImplFontAttrs::Typewriter )
+ meFamily = FAMILY_MODERN;
+ else if ( pFontAttr->Type & ImplFontAttrs::Italic )
+ meFamily = FAMILY_SCRIPT;
+ else if ( pFontAttr->Type & ImplFontAttrs::Decorative )
+ meFamily = FAMILY_DECORATIVE;
+ }
+
+ if( mePitch == PITCH_DONTKNOW )
+ {
+ if ( pFontAttr->Type & ImplFontAttrs::Fixed )
+ mePitch = PITCH_FIXED;
+ }
+ }
+
+ // if some attributes are still unknown then use the FontSubst magic
+ if( meFamily == FAMILY_DONTKNOW )
+ {
+ if( nType & ImplFontAttrs::Serif )
+ meFamily = FAMILY_ROMAN;
+ else if( nType & ImplFontAttrs::SansSerif )
+ meFamily = FAMILY_SWISS;
+ else if( nType & ImplFontAttrs::Typewriter )
+ meFamily = FAMILY_MODERN;
+ else if( nType & ImplFontAttrs::Italic )
+ meFamily = FAMILY_SCRIPT;
+ else if( nType & ImplFontAttrs::Decorative )
+ meFamily = FAMILY_DECORATIVE;
+ }
+
+ if( GetWeight() == WEIGHT_DONTKNOW )
+ SetWeight( eWeight );
+ if( meWidthType == WIDTH_DONTKNOW )
+ meWidthType = eWidthType;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/fontattributes.cxx b/vcl/source/font/fontattributes.cxx
new file mode 100644
index 0000000000..5c020d0724
--- /dev/null
+++ b/vcl/source/font/fontattributes.cxx
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <fontattributes.hxx>
+
+FontAttributes::FontAttributes()
+: meWeight( WEIGHT_DONTKNOW ),
+ meFamily( FAMILY_DONTKNOW ),
+ mePitch( PITCH_DONTKNOW ),
+ meWidthType ( WIDTH_DONTKNOW ),
+ meItalic ( ITALIC_NONE ),
+ mbMicrosoftSymbolEncoded( false ),
+ mnQuality( 0 )
+{}
+
+bool FontAttributes::CompareDeviceIndependentFontAttributes(const FontAttributes& rOther) const
+{
+ if (maFamilyName != rOther.maFamilyName)
+ return false;
+
+ if (maStyleName != rOther.maStyleName)
+ return false;
+
+ if (meWeight != rOther.meWeight)
+ return false;
+
+ if (meItalic != rOther.meItalic)
+ return false;
+
+ if (meFamily != rOther.meFamily)
+ return false;
+
+ if (mePitch != rOther.mePitch)
+ return false;
+
+ if (meWidthType != rOther.meWidthType)
+ return false;
+
+ if (mbMicrosoftSymbolEncoded != rOther.mbMicrosoftSymbolEncoded)
+ return false;
+
+ return true;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/fontcache.cxx b/vcl/source/font/fontcache.cxx
new file mode 100644
index 0000000000..c0dba15350
--- /dev/null
+++ b/vcl/source/font/fontcache.cxx
@@ -0,0 +1,283 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <sal/log.hxx>
+
+#include <font/PhysicalFontCollection.hxx>
+#include <font/PhysicalFontFace.hxx>
+#include <font/PhysicalFontFamily.hxx>
+#include <font/LogicalFontInstance.hxx>
+#include <tools/debug.hxx>
+#include <impfontcache.hxx>
+
+using namespace vcl::font;
+
+size_t ImplFontCache::IFSD_Hash::operator()( const vcl::font::FontSelectPattern& rFSD ) const
+{
+ return rFSD.hashCode();
+}
+
+bool ImplFontCache::IFSD_Equal::operator()(const vcl::font::FontSelectPattern& rA, const vcl::font::FontSelectPattern& rB) const
+{
+ // check normalized font family name
+ if( rA.maSearchName != rB.maSearchName )
+ return false;
+
+ // check font transformation
+ if( (rA.mnHeight != rB.mnHeight)
+ || (rA.mnWidth != rB.mnWidth)
+ || (rA.mnOrientation != rB.mnOrientation) )
+ return false;
+
+ // check mapping relevant attributes
+ if( (rA.mbVertical != rB.mbVertical)
+ || (rA.meLanguage != rB.meLanguage) )
+ return false;
+
+ // check font face attributes
+ if( (rA.GetWeight() != rB.GetWeight())
+ || (rA.GetItalic() != rB.GetItalic())
+// || (rA.meFamily != rB.meFamily) // TODO: remove this mostly obsolete member
+ || (rA.GetPitch() != rB.GetPitch()) )
+ return false;
+
+ // check style name
+ if( rA.GetStyleName() != rB.GetStyleName() )
+ return false;
+
+ // Symbol fonts may recode from one type to another So they are only
+ // safely equivalent for equal targets
+ if (rA.IsMicrosoftSymbolEncoded() || rB.IsMicrosoftSymbolEncoded())
+ {
+ if (rA.maTargetName != rB.maTargetName)
+ return false;
+ }
+
+ // check for features
+ if ((rA.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX)
+ != -1 ||
+ rB.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX)
+ != -1) && rA.maTargetName != rB.maTargetName)
+ return false;
+
+ if (rA.mbEmbolden != rB.mbEmbolden)
+ return false;
+
+ if (rA.maItalicMatrix != rB.maItalicMatrix)
+ return false;
+
+ return true;
+}
+
+ImplFontCache::ImplFontCache()
+ : mpLastHitCacheEntry( nullptr )
+ , maFontInstanceList(std::numeric_limits<size_t>::max()) // "unlimited", i.e. no cleanup
+ // The cache limit is set by the rough number of characters needed to read your average Asian newspaper.
+ , m_aBoundRectCache(3000)
+{}
+
+ImplFontCache::~ImplFontCache()
+{
+ DBG_TESTSOLARMUTEX();
+ for (const auto & rLFI : maFontInstanceList)
+ {
+ rLFI.second->mpFontCache = nullptr;
+ }
+}
+
+rtl::Reference<LogicalFontInstance> ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList,
+ const vcl::Font& rFont, const Size& rSize, float fExactHeight, bool bNonAntialias )
+{
+ // initialize internal font request object
+ vcl::font::FontSelectPattern aFontSelData(rFont, rFont.GetFamilyName(), rSize, fExactHeight, bNonAntialias);
+ return GetFontInstance( pFontList, aFontSelData );
+}
+
+rtl::Reference<LogicalFontInstance> ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList,
+ vcl::font::FontSelectPattern& aFontSelData )
+{
+ DBG_TESTSOLARMUTEX();
+ rtl::Reference<LogicalFontInstance> pFontInstance;
+ PhysicalFontFamily* pFontFamily = nullptr;
+
+ // check if a directly matching logical font instance is already cached,
+ // the most recently used font usually has a hit rate of >50%
+ if (mpLastHitCacheEntry && IFSD_Equal()(aFontSelData, mpLastHitCacheEntry->GetFontSelectPattern()))
+ pFontInstance = mpLastHitCacheEntry;
+ else
+ {
+ FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData );
+ if( it != maFontInstanceList.end() )
+ pFontInstance = (*it).second;
+ }
+
+ if( !pFontInstance ) // no direct cache hit
+ {
+ // find the best matching logical font family and update font selector accordingly
+ pFontFamily = pFontList->FindFontFamily( aFontSelData );
+ SAL_WARN_IF( (pFontFamily == nullptr), "vcl", "ImplFontCache::Get() No logical font found!" );
+ if( pFontFamily )
+ {
+ aFontSelData.maSearchName = pFontFamily->GetSearchName();
+
+ // check if an indirectly matching logical font instance is already cached
+ FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData );
+ if( it != maFontInstanceList.end() )
+ pFontInstance = (*it).second;
+ }
+ }
+
+ if( !pFontInstance && pFontFamily) // still no cache hit => create a new font instance
+ {
+ vcl::font::PhysicalFontFace* pFontData = pFontFamily->FindBestFontFace(aFontSelData);
+
+ // create a new logical font instance from this physical font face
+ pFontInstance = pFontData->CreateFontInstance( aFontSelData );
+ pFontInstance->mpFontCache = this;
+
+ // if we're substituting from or to a symbol font we may need a symbol
+ // conversion table
+ if( pFontData->IsMicrosoftSymbolEncoded() || aFontSelData.IsMicrosoftSymbolEncoded() || IsOpenSymbol(aFontSelData.maSearchName) )
+ {
+ if( aFontSelData.maTargetName != aFontSelData.maSearchName )
+ pFontInstance->mpConversion = ConvertChar::GetRecodeData( aFontSelData.maTargetName, aFontSelData.maSearchName );
+ }
+
+#ifdef MACOSX
+ //It might be better to dig out the font version of the target font
+ //to see if it's a modern re-coded apple symbol font in case that
+ //font shows up on a different platform
+ if (!pFontInstance->mpConversion &&
+ aFontSelData.maTargetName.equalsIgnoreAsciiCase("symbol") &&
+ aFontSelData.maSearchName.equalsIgnoreAsciiCase("symbol"))
+ {
+ pFontInstance->mpConversion = ConvertChar::GetRecodeData( u"Symbol", u"AppleSymbol" );
+ }
+#endif
+
+ static const size_t FONTCACHE_MAX = getenv("LO_TESTNAME") ? 1 : 50;
+
+ if (maFontInstanceList.size() >= FONTCACHE_MAX)
+ {
+ struct limit_exception : public std::exception {};
+ try
+ {
+ maFontInstanceList.remove_if([this] (FontInstanceList::key_value_pair_t const& rFontPair)
+ {
+ if (maFontInstanceList.size() < FONTCACHE_MAX)
+ throw limit_exception();
+ LogicalFontInstance* pFontEntry = rFontPair.second.get();
+ if (pFontEntry->m_nCount > 1)
+ return false;
+ m_aBoundRectCache.remove_if([&pFontEntry] (GlyphBoundRectCache::key_value_pair_t const& rGlyphPair)
+ { return rGlyphPair.first.m_pFont == pFontEntry; });
+ if (mpLastHitCacheEntry == pFontEntry)
+ mpLastHitCacheEntry = nullptr;
+ return true;
+ });
+ }
+ catch (limit_exception&) {}
+ }
+
+ assert(pFontInstance);
+ // add the new entry to the cache
+ maFontInstanceList.insert({aFontSelData, pFontInstance.get()});
+ }
+
+ mpLastHitCacheEntry = pFontInstance.get();
+ return pFontInstance;
+}
+
+rtl::Reference<LogicalFontInstance> ImplFontCache::GetGlyphFallbackFont( PhysicalFontCollection const * pFontCollection,
+ vcl::font::FontSelectPattern& rFontSelData, LogicalFontInstance* pFontInstance, int nFallbackLevel, OUString& rMissingCodes )
+{
+ // get a candidate font for glyph fallback
+ // unless the previously selected font got a device specific substitution
+ // e.g. PsPrint Arial->Helvetica for udiaeresis when Helvetica doesn't support it
+ if( nFallbackLevel >= 1)
+ {
+ PhysicalFontFamily* pFallbackData = nullptr;
+
+ //fdo#33898 If someone has EUDC installed then they really want that to
+ //be used as the first-choice glyph fallback seeing as it's filled with
+ //private area codes with don't make any sense in any other font so
+ //prioritize it here if it's available. Ideally we would remove from
+ //rMissingCodes all the glyphs which it is able to resolve as an
+ //optimization, but that's tricky to achieve cross-platform without
+ //sufficient heavy-weight code that's likely to undo the value of the
+ //optimization
+ if (nFallbackLevel == 1)
+ pFallbackData = pFontCollection->FindFontFamily(u"EUDC");
+ if (!pFallbackData)
+ pFallbackData = pFontCollection->GetGlyphFallbackFont(rFontSelData, pFontInstance, rMissingCodes, nFallbackLevel-1);
+ // escape when there are no font candidates
+ if( !pFallbackData )
+ return nullptr;
+ // override the font name
+ rFontSelData.SetFamilyName( pFallbackData->GetFamilyName() );
+ // clear the cached normalized name
+ rFontSelData.maSearchName.clear();
+ }
+
+ rtl::Reference<LogicalFontInstance> pFallbackFont = GetFontInstance( pFontCollection, rFontSelData );
+ return pFallbackFont;
+}
+
+void ImplFontCache::Invalidate()
+{
+ DBG_TESTSOLARMUTEX();
+ // #112304# make sure the font cache is really clean
+ mpLastHitCacheEntry = nullptr;
+ for (auto const & pair : maFontInstanceList)
+ pair.second->mpFontCache = nullptr;
+ maFontInstanceList.clear();
+ m_aBoundRectCache.clear();
+}
+
+bool ImplFontCache::GetCachedGlyphBoundRect(const LogicalFontInstance *pFont, sal_GlyphId nID, tools::Rectangle &rRect)
+{
+ if (!pFont->GetFontCache())
+ return false;
+ assert(pFont->GetFontCache() == this);
+ if (pFont->GetFontCache() != this)
+ return false;
+
+ auto it = m_aBoundRectCache.find({pFont, nID});
+ if (it != m_aBoundRectCache.end())
+ {
+ rRect = it->second;
+ return true;
+ }
+ return false;
+}
+
+void ImplFontCache::CacheGlyphBoundRect(const LogicalFontInstance *pFont, sal_GlyphId nID, tools::Rectangle &rRect)
+{
+ if (!pFont->GetFontCache())
+ return;
+ assert(pFont->GetFontCache() == this);
+ if (pFont->GetFontCache() != this)
+ return;
+
+ m_aBoundRectCache.insert({{pFont, nID}, rRect});
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/fontcharmap.cxx b/vcl/source/font/fontcharmap.cxx
new file mode 100644
index 0000000000..1a149bcc7d
--- /dev/null
+++ b/vcl/source/font/fontcharmap.cxx
@@ -0,0 +1,251 @@
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+#include <utility>
+#include <vcl/fontcharmap.hxx>
+#include <impfontcharmap.hxx>
+#include <sal/log.hxx>
+
+#include <algorithm>
+#include <vector>
+
+static ImplFontCharMapRef g_pDefaultImplFontCharMap;
+const std::vector<sal_uInt32> aDefaultUnicodeRanges = { 0x0020, 0xD800, 0xE000, 0xFFF0 };
+const std::vector<sal_uInt32> aDefaultSymbolRanges = { 0x0020, 0x0100, 0xF020, 0xF100 };
+
+ImplFontCharMap::~ImplFontCharMap()
+{
+}
+
+ImplFontCharMap::ImplFontCharMap(bool bMicrosoftSymbolMap, std::vector<sal_uInt32> aRangeCodes)
+: maRangeCodes(std::move(aRangeCodes))
+, mnCharCount( 0 )
+, m_bMicrosoftSymbolMap(bMicrosoftSymbolMap)
+{
+ for (size_t i = 0; i < maRangeCodes.size(); i += 2)
+ {
+ sal_UCS4 cFirst = maRangeCodes[i];
+ sal_UCS4 cLast = maRangeCodes[i + 1];
+ mnCharCount += cLast - cFirst;
+ }
+}
+
+ImplFontCharMapRef const & ImplFontCharMap::getDefaultMap(bool bMicrosoftSymbolMap)
+{
+ const auto& rRanges = bMicrosoftSymbolMap ? aDefaultSymbolRanges : aDefaultUnicodeRanges;
+ g_pDefaultImplFontCharMap = ImplFontCharMapRef(new ImplFontCharMap(bMicrosoftSymbolMap, rRanges));
+ return g_pDefaultImplFontCharMap;
+}
+
+bool ImplFontCharMap::isDefaultMap() const
+{
+ const bool bIsDefault = (maRangeCodes == aDefaultUnicodeRanges) || (maRangeCodes == aDefaultSymbolRanges);
+ return bIsDefault;
+}
+
+static unsigned GetUShort(const unsigned char* p) { return((p[0]<<8) | p[1]);}
+
+bool HasMicrosoftSymbolCmap(const unsigned char* pCmap, int nLength)
+{
+ // parse the table header and check for validity
+ if( !pCmap || (nLength < 24) )
+ return false;
+
+ if( GetUShort( pCmap ) != 0x0000 ) // simple check for CMAP corruption
+ return false;
+
+ int nSubTables = GetUShort(pCmap + 2);
+ if( (nSubTables <= 0) || (nSubTables > (nLength - 24) / 8) )
+ return false;
+
+ for (const unsigned char* p = pCmap + 4; --nSubTables >= 0; p += 8)
+ {
+ int nPlatform = GetUShort(p);
+ int nEncoding = GetUShort(p + 2);
+ // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
+ // When the platformID is 3 (Windows), an encoding of 0 is Symbol
+ if (nPlatform == 3 && nEncoding == 0)
+ return true;
+ }
+
+ return false;
+}
+
+FontCharMap::FontCharMap()
+ : mpImplFontCharMap( ImplFontCharMap::getDefaultMap() )
+{
+}
+
+FontCharMap::FontCharMap( ImplFontCharMapRef pIFCMap )
+ : mpImplFontCharMap(std::move( pIFCMap ))
+{
+}
+
+FontCharMap::FontCharMap(bool bMicrosoftSymbolMap, std::vector<sal_uInt32> aRangeCodes)
+ : mpImplFontCharMap(new ImplFontCharMap(bMicrosoftSymbolMap, std::move(aRangeCodes)))
+{
+}
+
+FontCharMap::~FontCharMap()
+{
+ mpImplFontCharMap = nullptr;
+}
+
+FontCharMapRef FontCharMap::GetDefaultMap(bool bMicrosoftSymbolMap)
+{
+ FontCharMapRef xFontCharMap( new FontCharMap( ImplFontCharMap::getDefaultMap(bMicrosoftSymbolMap) ) );
+ return xFontCharMap;
+}
+
+bool FontCharMap::IsDefaultMap() const
+{
+ return mpImplFontCharMap->isDefaultMap();
+}
+
+bool FontCharMap::isMicrosoftSymbolMap() const { return mpImplFontCharMap->m_bMicrosoftSymbolMap; }
+
+int FontCharMap::GetCharCount() const
+{
+ return mpImplFontCharMap->mnCharCount;
+}
+
+int FontCharMap::CountCharsInRange( sal_UCS4 cMin, sal_UCS4 cMax ) const
+{
+ const auto& rRanges = mpImplFontCharMap->maRangeCodes;
+ int nCount = 0;
+
+ // find and adjust range and char count for cMin
+ int nRangeMin = findRangeIndex( cMin );
+ if( nRangeMin & 1 )
+ ++nRangeMin;
+ else if (cMin > rRanges[nRangeMin])
+ nCount -= cMin - rRanges[nRangeMin];
+
+ // find and adjust range and char count for cMax
+ int nRangeMax = findRangeIndex( cMax );
+ if( nRangeMax & 1 )
+ --nRangeMax;
+ else
+ nCount -= rRanges[nRangeMax + 1] - cMax - 1;
+
+ // count chars in complete ranges between cMin and cMax
+ for( int i = nRangeMin; i <= nRangeMax; i+=2 )
+ nCount += rRanges[i + 1] - rRanges[i];
+
+ return nCount;
+}
+
+bool FontCharMap::HasChar( sal_UCS4 cChar ) const
+{
+ const int nRange = findRangeIndex( cChar );
+ if (nRange==0 && cChar < mpImplFontCharMap->maRangeCodes[0])
+ return false;
+ return ((nRange & 1) == 0); // inside a range
+}
+
+sal_UCS4 FontCharMap::GetFirstChar() const
+{
+ return mpImplFontCharMap->maRangeCodes.front();
+}
+
+sal_UCS4 FontCharMap::GetLastChar() const
+{
+ return mpImplFontCharMap->maRangeCodes.back() - 1;
+}
+
+sal_UCS4 FontCharMap::GetNextChar( sal_UCS4 cChar ) const
+{
+ if( cChar < GetFirstChar() )
+ return GetFirstChar();
+ if( cChar >= GetLastChar() )
+ return GetLastChar();
+
+ int nRange = findRangeIndex( cChar + 1 );
+ if( nRange & 1 ) // outside of range?
+ return mpImplFontCharMap->maRangeCodes[nRange + 1]; // => first in next range
+ return (cChar + 1);
+}
+
+sal_UCS4 FontCharMap::GetPrevChar( sal_UCS4 cChar ) const
+{
+ if( cChar <= GetFirstChar() )
+ return GetFirstChar();
+ if( cChar > GetLastChar() )
+ return GetLastChar();
+
+ int nRange = findRangeIndex( cChar - 1 );
+ if( nRange & 1 ) // outside a range?
+ return mpImplFontCharMap->maRangeCodes[nRange] - 1; // => last in prev range
+ return (cChar - 1);
+}
+
+int FontCharMap::GetIndexFromChar( sal_UCS4 cChar ) const
+{
+ // TODO: improve linear walk?
+ int nCharIndex = 0;
+ const auto& rRanges = mpImplFontCharMap->maRangeCodes;
+ for (size_t i = 0; i < rRanges.size(); i += 2)
+ {
+ sal_UCS4 cFirst = rRanges[i];
+ sal_UCS4 cLast = rRanges[i + 1];
+ if( cChar >= cLast )
+ nCharIndex += cLast - cFirst;
+ else if( cChar >= cFirst )
+ return nCharIndex + (cChar - cFirst);
+ else
+ break;
+ }
+
+ return -1;
+}
+
+sal_UCS4 FontCharMap::GetCharFromIndex( int nIndex ) const
+{
+ // TODO: improve linear walk?
+ const auto& rRanges = mpImplFontCharMap->maRangeCodes;
+ for (size_t i = 0; i < rRanges.size(); i += 2)
+ {
+ sal_UCS4 cFirst = rRanges[i];
+ sal_UCS4 cLast = rRanges[i + 1];
+ nIndex -= cLast - cFirst;
+ if( nIndex < 0 )
+ return (cLast + nIndex);
+ }
+
+ // we can only get here with an out-of-bounds charindex
+ return mpImplFontCharMap->maRangeCodes.front();
+}
+
+int FontCharMap::findRangeIndex( sal_UCS4 cChar ) const
+{
+ const auto& rRanges = mpImplFontCharMap->maRangeCodes;
+ int nLower = 0;
+ int nMid = rRanges.size() / 2;
+ int nUpper = rRanges.size() - 1;
+ while( nLower < nUpper )
+ {
+ if (cChar >= rRanges[nMid])
+ nLower = nMid;
+ else
+ nUpper = nMid - 1;
+ nMid = (nLower + nUpper + 1) / 2;
+ }
+
+ return nMid;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/font/fontmetric.cxx b/vcl/source/font/fontmetric.cxx
new file mode 100644
index 0000000000..115b3da6fb
--- /dev/null
+++ b/vcl/source/font/fontmetric.cxx
@@ -0,0 +1,563 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <sal/config.h>
+
+#include <i18nlangtag/mslangid.hxx>
+#include <officecfg/Office/Common.hxx>
+#include <sal/log.hxx>
+#include <tools/stream.hxx>
+#include <unotools/configmgr.hxx>
+#include <vcl/metric.hxx>
+#include <vcl/outdev.hxx>
+
+#include <font/FontSelectPattern.hxx>
+#include <font/PhysicalFontFace.hxx>
+#include <font/LogicalFontInstance.hxx>
+#include <font/FontMetricData.hxx>
+#include <sft.hxx>
+
+#include <com/sun/star/uno/Sequence.hxx>
+#include <comphelper/sequence.hxx>
+#include <hb-ot.h>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::rtl;
+using namespace ::utl;
+
+FontMetric::FontMetric()
+: mnAscent( 0 ),
+ mnDescent( 0 ),
+ mnIntLeading( 0 ),
+ mnExtLeading( 0 ),
+ mnLineHeight( 0 ),
+ mnSlant( 0 ),
+ mnBulletOffset( 0 ),
+ mnHangingBaseline( 0 ),
+ mbFullstopCentered( false )
+{}
+
+FontMetric::FontMetric( const FontMetric& rFontMetric ) = default;
+
+FontMetric::FontMetric(vcl::font::PhysicalFontFace const& rFace)
+ : FontMetric()
+{
+ SetFamilyName(rFace.GetFamilyName());
+ SetStyleName(rFace.GetStyleName());
+ SetCharSet(rFace.IsMicrosoftSymbolEncoded() ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE);
+ SetFamily(rFace.GetFamilyType());
+ SetPitch(rFace.GetPitch());
+ SetWeight(rFace.GetWeight());
+ SetItalic(rFace.GetItalic());
+ SetAlignment(TextAlign::ALIGN_TOP);
+ SetWidthType(rFace.GetWidthType());
+ SetQuality(rFace.GetQuality() );
+}
+
+FontMetric::~FontMetric()
+{
+}
+
+FontMetric& FontMetric::operator=(const FontMetric& rFontMetric) = default;
+
+FontMetric& FontMetric::operator=(FontMetric&& rFontMetric) = default;
+
+bool FontMetric::EqualNoBase( const FontMetric& r ) const
+{
+ if (mbFullstopCentered != r.mbFullstopCentered)
+ return false;
+ if( mnAscent != r.mnAscent )
+ return false;
+ if( mnDescent != r.mnDescent )
+ return false;
+ if( mnIntLeading != r.mnIntLeading )
+ return false;
+ if( mnExtLeading != r.mnExtLeading )
+ return false;
+ if( mnSlant != r.mnSlant )
+ return false;
+
+ return true;
+}
+
+bool FontMetric::operator==( const FontMetric& r ) const
+{
+ if( Font::operator!=(r) )
+ return false;
+ return EqualNoBase(r);
+}
+
+bool FontMetric::EqualIgnoreColor( const FontMetric& r ) const
+{
+ if( !Font::EqualIgnoreColor(r) )
+ return false;
+ return EqualNoBase(r);
+}
+
+size_t FontMetric::GetHashValueNoBase() const
+{
+ size_t hash = 0;
+ o3tl::hash_combine( hash, mbFullstopCentered );
+ o3tl::hash_combine( hash, mnAscent );
+ o3tl::hash_combine( hash, mnDescent );
+ o3tl::hash_combine( hash, mnIntLeading );
+ o3tl::hash_combine( hash, mnExtLeading );
+ o3tl::hash_combine( hash, mnSlant );
+ return hash;
+}
+
+size_t FontMetric::GetHashValueIgnoreColor() const
+{
+ size_t hash = GetHashValueNoBase();
+ o3tl::hash_combine( hash, Font::GetHashValueIgnoreColor());
+ return hash;
+}
+
+FontMetricData::FontMetricData( const vcl::font::FontSelectPattern& rFontSelData )
+ : FontAttributes( rFontSelData )
+ , mnHeight ( rFontSelData.mnHeight )
+ , mnWidth ( rFontSelData.mnWidth )
+ , mnOrientation( static_cast<short>(rFontSelData.mnOrientation) )
+ , mnAscent( 0 )
+ , mnDescent( 0 )
+ , mnIntLeading( 0 )
+ , mnExtLeading( 0 )
+ , mnSlant( 0 )
+ , mnMinKashida( 0 )
+ , mnHangingBaseline( 0 )
+ , mbFullstopCentered( false )
+ , mnBulletOffset( 0 )
+ , mnUnderlineSize( 0 )
+ , mnUnderlineOffset( 0 )
+ , mnBUnderlineSize( 0 )
+ , mnBUnderlineOffset( 0 )
+ , mnDUnderlineSize( 0 )
+ , mnDUnderlineOffset1( 0 )
+ , mnDUnderlineOffset2( 0 )
+ , mnWUnderlineSize( 0 )
+ , mnWUnderlineOffset( 0 )
+ , mnAboveUnderlineSize( 0 )
+ , mnAboveUnderlineOffset( 0 )
+ , mnAboveBUnderlineSize( 0 )
+ , mnAboveBUnderlineOffset( 0 )
+ , mnAboveDUnderlineSize( 0 )
+ , mnAboveDUnderlineOffset1( 0 )
+ , mnAboveDUnderlineOffset2( 0 )
+ , mnAboveWUnderlineSize( 0 )
+ , mnAboveWUnderlineOffset( 0 )
+ , mnStrikeoutSize( 0 )
+ , mnStrikeoutOffset( 0 )
+ , mnBStrikeoutSize( 0 )
+ , mnBStrikeoutOffset( 0 )
+ , mnDStrikeoutSize( 0 )
+ , mnDStrikeoutOffset1( 0 )
+ , mnDStrikeoutOffset2( 0 )
+{
+ // initialize the used font name
+ sal_Int32 nTokenPos = 0;
+ SetFamilyName( OUString(GetNextFontToken( rFontSelData.GetFamilyName(), nTokenPos )) );
+ SetStyleName( rFontSelData.GetStyleName() );
+}
+
+bool FontMetricData::ShouldNotUseUnderlineMetrics() const
+{
+ if (utl::ConfigManager::IsFuzzing())
+ return false;
+
+ css::uno::Sequence<OUString> rNoUnderlineMetricsList(
+ officecfg::Office::Common::Misc::FontsDontUseUnderlineMetrics::get());
+ if (comphelper::findValue(rNoUnderlineMetricsList, GetFamilyName()) != -1)
+ {
+ SAL_INFO("vcl.gdi.fontmetric", "Not using underline metrics for: " << GetFamilyName());
+ return true;
+ }
+ return false;
+}
+
+bool FontMetricData::ImplInitTextLineSizeHarfBuzz(LogicalFontInstance* pFont)
+{
+ if (ShouldNotUseUnderlineMetrics())
+ return false;
+
+ auto* pHbFont = pFont->GetHbFont();
+
+ hb_position_t nUnderlineSize;
+ if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_UNDERLINE_SIZE, &nUnderlineSize))
+ return false;
+ hb_position_t nUnderlineOffset;
+ if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_UNDERLINE_OFFSET, &nUnderlineOffset))
+ return false;
+ hb_position_t nStrikeoutSize;
+ if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_STRIKEOUT_SIZE, &nStrikeoutSize))
+ return false;
+ hb_position_t nStrikeoutOffset;
+ if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_STRIKEOUT_OFFSET, &nStrikeoutOffset))
+ return false;
+
+ double fScale = 0;
+ pFont->GetScale(nullptr, &fScale);
+
+ double nOffset = -nUnderlineOffset * fScale;
+ double nSize = nUnderlineSize * fScale;
+ double nSize2 = nSize / 2.;
+ double nBSize = nSize * 2.;
+ double n2Size = nBSize / 3.;
+
+ mnUnderlineSize = std::ceil(nSize);
+ mnUnderlineOffset = std::ceil(nOffset);
+
+ mnBUnderlineSize = std::ceil(nBSize);
+ mnBUnderlineOffset = std::ceil(nOffset - nSize2);
+
+ mnDUnderlineSize = std::ceil(n2Size);
+ mnDUnderlineOffset1 = mnBUnderlineOffset;
+ mnDUnderlineOffset2 = mnBUnderlineOffset + mnDUnderlineSize * 2;
+
+ mnWUnderlineSize = mnBUnderlineSize;
+ mnWUnderlineOffset = std::ceil(nOffset + nSize);
+
+ nOffset = -nStrikeoutOffset * fScale;
+ nSize = nStrikeoutSize * fScale;
+ nSize2 = nSize / 2.;
+ nBSize = nSize * 2.;
+ n2Size = nBSize / 3.;
+
+ mnStrikeoutSize = std::ceil(nSize);
+ mnStrikeoutOffset = std::ceil(nOffset);
+
+ mnBStrikeoutSize = std::ceil(nBSize);
+ mnBStrikeoutOffset = std::round(nOffset - nSize2);
+
+ mnDStrikeoutSize = std::ceil(n2Size);
+ mnDStrikeoutOffset1 = mnBStrikeoutOffset;
+ mnDStrikeoutOffset2 = mnBStrikeoutOffset + mnDStrikeoutSize * 2;
+
+ return true;
+}
+
+void FontMetricData::ImplInitTextLineSize( const OutputDevice* pDev )
+{
+ mnBulletOffset = ( pDev->GetTextWidth( OUString( u' ' ) ) - pDev->GetTextWidth( OUString( u'\x00b7' ) ) ) >> 1 ;
+
+ if (ImplInitTextLineSizeHarfBuzz(const_cast<LogicalFontInstance*>(pDev->GetFontInstance())))
+ return;
+
+ tools::Long nDescent = mnDescent;
+ if ( nDescent <= 0 )
+ {
+ nDescent = mnAscent / 10;
+ if ( !nDescent )
+ nDescent = 1;
+ }
+
+ // #i55341# for some fonts it is not a good idea to calculate
+ // their text line metrics from the real font descent
+ // => work around this problem just for these fonts
+ if( 3*nDescent > mnAscent )
+ nDescent = mnAscent / 3;
+
+ tools::Long nLineHeight = ((nDescent*25)+50) / 100;
+ if ( !nLineHeight )
+ nLineHeight = 1;
+ tools::Long nLineHeight2 = nLineHeight / 2;
+ if ( !nLineHeight2 )
+ nLineHeight2 = 1;
+
+ tools::Long nBLineHeight = ((nDescent*50)+50) / 100;
+ if ( nBLineHeight == nLineHeight )
+ nBLineHeight++;
+ tools::Long nBLineHeight2 = nBLineHeight/2;
+ if ( !nBLineHeight2 )
+ nBLineHeight2 = 1;
+
+ tools::Long n2LineHeight = ((nDescent*16)+50) / 100;
+ if ( !n2LineHeight )
+ n2LineHeight = 1;
+ tools::Long n2LineDY = n2LineHeight;
+ /* #117909#
+ * add some pixels to minimum double line distance on higher resolution devices
+ */
+ tools::Long nMin2LineDY = 1 + pDev->GetDPIY()/150;
+ if ( n2LineDY < nMin2LineDY )
+ n2LineDY = nMin2LineDY;
+ tools::Long n2LineDY2 = n2LineDY/2;
+ if ( !n2LineDY2 )
+ n2LineDY2 = 1;
+
+ const vcl::Font& rFont ( pDev->GetFont() );
+ bool bCJKVertical = MsLangId::isCJK(rFont.GetLanguage()) && rFont.IsVertical();
+ tools::Long nUnderlineOffset = bCJKVertical ? mnDescent : (mnDescent/2 + 1);
+ tools::Long nStrikeoutOffset = rFont.IsVertical() ? -((mnAscent - mnDescent) / 2) : -((mnAscent - mnIntLeading) / 3);
+
+ mnUnderlineSize = nLineHeight;
+ mnUnderlineOffset = nUnderlineOffset - nLineHeight2;
+
+ mnBUnderlineSize = nBLineHeight;
+ mnBUnderlineOffset = nUnderlineOffset - nBLineHeight2;
+
+ mnDUnderlineSize = n2LineHeight;
+ mnDUnderlineOffset1 = nUnderlineOffset - n2LineDY2 - n2LineHeight;
+ mnDUnderlineOffset2 = mnDUnderlineOffset1 + n2LineDY + n2LineHeight;
+
+ tools::Long nWCalcSize = mnDescent;
+ if ( nWCalcSize < 6 )
+ {
+ if ( (nWCalcSize == 1) || (nWCalcSize == 2) )
+ mnWUnderlineSize = nWCalcSize;
+ else
+ mnWUnderlineSize = 3;
+ }
+ else
+ mnWUnderlineSize = ((nWCalcSize*50)+50) / 100;
+
+
+ // Don't assume that wavelines are never placed below the descent, because for most fonts the waveline
+ // is drawn into the text
+ mnWUnderlineOffset = nUnderlineOffset;
+
+ mnStrikeoutSize = nLineHeight;
+ mnStrikeoutOffset = nStrikeoutOffset - nLineHeight2;
+
+ mnBStrikeoutSize = nBLineHeight;
+ mnBStrikeoutOffset = nStrikeoutOffset - nBLineHeight2;
+
+ mnDStrikeoutSize = n2LineHeight;
+ mnDStrikeoutOffset1 = nStrikeoutOffset - n2LineDY2 - n2LineHeight;
+ mnDStrikeoutOffset2 = mnDStrikeoutOffset1 + n2LineDY + n2LineHeight;
+
+}
+
+
+void FontMetricData::ImplInitAboveTextLineSize( const OutputDevice* pDev )
+{
+ ImplInitTextLineSize(pDev);
+
+ tools::Long nIntLeading = mnIntLeading;
+ // TODO: assess usage of nLeading below (changed in extleading CWS)
+ // if no leading is available, we assume 15% of the ascent
+ if ( nIntLeading <= 0 )
+ {
+ nIntLeading = mnAscent*15/100;
+ if ( !nIntLeading )
+ nIntLeading = 1;
+ }
+
+ tools::Long nCeiling = -mnAscent;
+
+ mnAboveUnderlineSize = mnUnderlineSize;
+ mnAboveUnderlineOffset = nCeiling + (nIntLeading - mnUnderlineSize + 1) / 2;
+
+ mnAboveBUnderlineSize = mnBUnderlineSize;
+ mnAboveBUnderlineOffset = nCeiling + (nIntLeading - mnBUnderlineSize + 1) / 2;
+
+ mnAboveDUnderlineSize = mnDUnderlineSize;
+ mnAboveDUnderlineOffset1 = nCeiling + (nIntLeading - 3*mnDUnderlineSize + 1) / 2;
+ mnAboveDUnderlineOffset2 = nCeiling + (nIntLeading + mnDUnderlineSize + 1) / 2;
+
+ mnAboveWUnderlineSize = mnWUnderlineSize;
+ mnAboveWUnderlineOffset = nCeiling + (nIntLeading + 1) / 2;
+}
+
+void FontMetricData::ImplInitFlags( const OutputDevice* pDev )
+{
+ const vcl::Font& rFont ( pDev->GetFont() );
+ bool bCentered = true;
+ if (MsLangId::isCJK(rFont.GetLanguage()))
+ {
+ tools::Rectangle aRect;
+ pDev->GetTextBoundRect( aRect, u"\x3001"_ustr ); // Fullwidth fullstop
+ const auto nH = rFont.GetFontSize().Height();
+ const auto nB = aRect.Left();
+ // Use 18.75% as a threshold to define a centered fullwidth fullstop.
+ // In general, nB/nH < 5% for most Japanese fonts.
+ bCentered = nB > (((nH >> 1)+nH)>>3);
+ }
+ SetFullstopCenteredFlag( bCentered );
+}
+
+bool FontMetricData::ShouldUseWinMetrics(int nAscent, int nDescent, int nTypoAscent,
+ int nTypoDescent, int nWinAscent,
+ int nWinDescent) const
+{
+ if (utl::ConfigManager::IsFuzzing())
+ return false;
+
+ OUString aFontIdentifier(
+ GetFamilyName() + ","
+ + OUString::number(nAscent) + "," + OUString::number(nDescent) + ","
+ + OUString::number(nTypoAscent) + "," + OUString::number(nTypoDescent) + ","
+ + OUString::number(nWinAscent) + "," + OUString::number(nWinDescent));
+
+ css::uno::Sequence<OUString> rWinMetricFontList(
+ officecfg::Office::Common::Misc::FontsUseWinMetrics::get());
+ if (comphelper::findValue(rWinMetricFontList, aFontIdentifier) != -1)
+ {
+ SAL_INFO("vcl.gdi.fontmetric", "Using win metrics for: " << aFontIdentifier);
+ return true;
+ }
+ return false;
+}
+
+// These are “private” HarfBuzz metrics tags, they are supported by not exposed
+// in the public header. They are safe to use, HarfBuzz just does not want to
+// advertise them.
+constexpr auto ASCENT_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'a', 's', 'c'));
+constexpr auto DESCENT_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'd', 's', 'c'));
+constexpr auto LINEGAP_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'l', 'g', 'p'));
+constexpr auto ASCENT_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'a', 's', 'c'));
+constexpr auto DESCENT_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'd', 's', 'c'));
+constexpr auto LINEGAP_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'l', 'g', 'p'));
+
+void FontMetricData::ImplCalcLineSpacing(LogicalFontInstance* pFontInstance)
+{
+ mnAscent = mnDescent = mnExtLeading = mnIntLeading = 0;
+ auto* pFace = pFontInstance->GetFontFace();
+ auto* pHbFont = pFontInstance->GetHbFont();
+
+ double fScale = 0;
+ pFontInstance->GetScale(nullptr, &fScale);
+ double fAscent = 0, fDescent = 0, fExtLeading = 0;
+
+ auto aFvar(pFace->GetRawFontData(HB_TAG('f', 'v', 'a', 'r')));
+ if (!aFvar.empty())
+ {
+ // This is a variable font, trust HarfBuzz to give us the right metrics
+ // and apply variations to them.
+ hb_position_t nAscent, nDescent, nLineGap;
+ if (hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_ASCENDER, &nAscent)
+ && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_DESCENDER,
+ &nDescent)
+ && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_LINE_GAP,
+ &nLineGap))
+ {
+ fAscent = nAscent * fScale;
+ fDescent = -nDescent * fScale;
+ fExtLeading = nLineGap * fScale;
+ }
+ }
+ else
+ {
+ // This is not a variable font, we try to choose the best metrics
+ // ourselves for backward comparability:
+ //
+ // - hhea metrics should be used, since hhea is a mandatory font table
+ // and should always be present.
+ // - But if OS/2 is present, it should be used since it is mandatory in
+ // Windows.
+ // OS/2 has Typo and Win metrics, but the later was meant to control
+ // text clipping not line spacing and can be ridiculously large.
+ // Unfortunately many Windows application incorrectly use the Win
+ // metrics (thanks to GDI’s TEXTMETRIC) and old fonts might be
+ // designed with this in mind, so OpenType introduced a flag for
+ // fonts to indicate that they really want to use Typo metrics. So
+ // for best backward compatibility:
+ // - Use Win metrics if available.
+ // - Unless USE_TYPO_METRICS flag is set, in which case use Typo
+ // metrics.
+
+ // Try hhea table first.
+ hb_position_t nAscent = 0, nDescent = 0, nLineGap = 0;
+ if (hb_ot_metrics_get_position(pHbFont, ASCENT_HHEA, &nAscent)
+ && hb_ot_metrics_get_position(pHbFont, DESCENT_HHEA, &nDescent)
+ && hb_ot_metrics_get_position(pHbFont, LINEGAP_HHEA, &nLineGap))
+ {
+ // tdf#107605: Some fonts have weird values here, so check that
+ // ascender is +ve and descender is -ve as they normally should.
+ if (nAscent >= 0 && nDescent <= 0)
+ {
+ fAscent = nAscent * fScale;
+ fDescent = -nDescent * fScale;
+ fExtLeading = nLineGap * fScale;
+ }
+ }
+
+ // But if OS/2 is present, prefer it.
+ hb_position_t nTypoAscent, nTypoDescent, nTypoLineGap, nWinAscent, nWinDescent;
+ if (hb_ot_metrics_get_position(pHbFont, ASCENT_OS2, &nTypoAscent)
+ && hb_ot_metrics_get_position(pHbFont, DESCENT_OS2, &nTypoDescent)
+ && hb_ot_metrics_get_position(pHbFont, LINEGAP_OS2, &nTypoLineGap)
+ && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_ASCENT,
+ &nWinAscent)
+ && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_DESCENT,
+ &nWinDescent))
+ {
+ if ((fAscent == 0.0 && fDescent == 0.0)
+ || ShouldUseWinMetrics(nAscent, nDescent, nTypoAscent, nTypoDescent, nWinAscent,
+ nWinDescent))
+ {
+ fAscent = nWinAscent * fScale;
+ fDescent = nWinDescent * fScale;
+ fExtLeading = 0;
+ }
+
+ bool bUseTypoMetrics = false;
+ {
+ // TODO: Use HarfBuzz API instead of raw access
+ // https://github.com/harfbuzz/harfbuzz/issues/1920
+ sal_uInt16 fsSelection = 0;
+ auto aOS2(pFace->GetRawFontData(HB_TAG('O', 'S', '/', '2')));
+ SvMemoryStream aStream(const_cast<uint8_t*>(aOS2.data()), aOS2.size(),
+ StreamMode::READ);
+ // Font data are big endian.
+ aStream.SetEndian(SvStreamEndian::BIG);
+ if (aStream.Seek(vcl::OS2_fsSelection_offset) == vcl::OS2_fsSelection_offset)
+ aStream.ReadUInt16(fsSelection);
+ bUseTypoMetrics = fsSelection & (1 << 7);
+ }
+ if (bUseTypoMetrics && nTypoAscent >= 0 && nTypoDescent <= 0)
+ {
+ fAscent = nTypoAscent * fScale;
+ fDescent = -nTypoDescent * fScale;
+ fExtLeading = nTypoLineGap * fScale;
+ }
+ }
+ }
+
+ mnAscent = round(fAscent);
+ mnDescent = round(fDescent);
+ mnExtLeading = round(fExtLeading);
+
+ if (mnAscent || mnDescent)
+ mnIntLeading = mnAscent + mnDescent - mnHeight;
+}
+
+void FontMetricData::ImplInitBaselines(LogicalFontInstance *pFontInstance)
+{
+ hb_font_t* pHbFont = pFontInstance->GetHbFont();
+ double fScale = 0;
+ pFontInstance->GetScale(nullptr, &fScale);
+ hb_position_t nBaseline = 0;
+
+ if (hb_ot_layout_get_baseline(pHbFont,
+ HB_OT_LAYOUT_BASELINE_TAG_HANGING,
+ HB_DIRECTION_INVALID,
+ HB_SCRIPT_UNKNOWN,
+ HB_TAG_NONE,
+ &nBaseline))
+ {
+ mnHangingBaseline = nBaseline * fScale;
+ }
+ else
+ {
+ mnHangingBaseline = 0;
+ }
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/cff.cxx b/vcl/source/fontsubset/cff.cxx
new file mode 100644
index 0000000000..2021a6a44d
--- /dev/null
+++ b/vcl/source/fontsubset/cff.cxx
@@ -0,0 +1,2625 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <cstdio>
+#include <cstring>
+#include <vector>
+#include <assert.h>
+
+#include <fontsubset.hxx>
+
+#include <comphelper/flagguard.hxx>
+#include <o3tl/safeint.hxx>
+#include <o3tl/sprintf.hxx>
+#include <rtl/math.hxx>
+#include <rtl/strbuf.hxx>
+#include <rtl/string.hxx>
+#include <strhelper.hxx>
+#include <sal/log.hxx>
+#include <tools/stream.hxx>
+
+typedef sal_uInt8 U8;
+typedef sal_uInt16 U16;
+typedef sal_Int64 S64;
+
+typedef double RealType;
+typedef RealType ValType;
+
+constexpr OString tok_notdef = ".notdef"_ostr;
+constexpr OString tok_space = "space"_ostr;
+constexpr OString tok_exclam = "exclam"_ostr;
+constexpr OString tok_quotedbl = "quotedbl"_ostr;
+constexpr OString tok_numbersign = "numbersign"_ostr;
+constexpr OString tok_dollar = "dollar"_ostr;
+constexpr OString tok_percent = "percent"_ostr;
+constexpr OString tok_ampersand = "ampersand"_ostr;
+constexpr OString tok_quoteright = "quoteright"_ostr;
+constexpr OString tok_parenleft = "parenleft"_ostr;
+constexpr OString tok_parenright = "parenright"_ostr;
+constexpr OString tok_asterisk = "asterisk"_ostr;
+constexpr OString tok_plus = "plus"_ostr;
+constexpr OString tok_comma = "comma"_ostr;
+constexpr OString tok_hyphen = "hyphen"_ostr;
+constexpr OString tok_period = "period"_ostr;
+constexpr OString tok_slash = "slash"_ostr;
+constexpr OString tok_zero = "zero"_ostr;
+constexpr OString tok_one = "one"_ostr;
+constexpr OString tok_two = "two"_ostr;
+constexpr OString tok_three = "three"_ostr;
+constexpr OString tok_four = "four"_ostr;
+constexpr OString tok_five = "five"_ostr;
+constexpr OString tok_six = "six"_ostr;
+constexpr OString tok_seven = "seven"_ostr;
+constexpr OString tok_eight = "eight"_ostr;
+constexpr OString tok_nine = "nine"_ostr;
+constexpr OString tok_colon = "colon"_ostr;
+constexpr OString tok_semicolon = "semicolon"_ostr;
+constexpr OString tok_less = "less"_ostr;
+constexpr OString tok_equal = "equal"_ostr;
+constexpr OString tok_greater = "greater"_ostr;
+constexpr OString tok_question = "question"_ostr;
+constexpr OString tok_at = "at"_ostr;
+constexpr OString tok_A = "A"_ostr;
+constexpr OString tok_B = "B"_ostr;
+constexpr OString tok_C = "C"_ostr;
+constexpr OString tok_D = "D"_ostr;
+constexpr OString tok_E = "E"_ostr;
+constexpr OString tok_F = "F"_ostr;
+constexpr OString tok_G = "G"_ostr;
+constexpr OString tok_H = "H"_ostr;
+constexpr OString tok_I = "I"_ostr;
+constexpr OString tok_J = "J"_ostr;
+constexpr OString tok_K = "K"_ostr;
+constexpr OString tok_L = "L"_ostr;
+constexpr OString tok_M = "M"_ostr;
+constexpr OString tok_N = "N"_ostr;
+constexpr OString tok_O = "O"_ostr;
+constexpr OString tok_P = "P"_ostr;
+constexpr OString tok_Q = "Q"_ostr;
+constexpr OString tok_R = "R"_ostr;
+constexpr OString tok_S = "S"_ostr;
+constexpr OString tok_T = "T"_ostr;
+constexpr OString tok_U = "U"_ostr;
+constexpr OString tok_V = "V"_ostr;
+constexpr OString tok_W = "W"_ostr;
+constexpr OString tok_X = "X"_ostr;
+constexpr OString tok_Y = "Y"_ostr;
+constexpr OString tok_Z = "Z"_ostr;
+constexpr OString tok_bracketleft = "bracketleft"_ostr;
+constexpr OString tok_backslash = "backslash"_ostr;
+constexpr OString tok_bracketright = "bracketright"_ostr;
+constexpr OString tok_asciicircum = "asciicircum"_ostr;
+constexpr OString tok_underscore = "underscore"_ostr;
+constexpr OString tok_quoteleft = "quoteleft"_ostr;
+constexpr OString tok_a = "a"_ostr;
+constexpr OString tok_b = "b"_ostr;
+constexpr OString tok_c = "c"_ostr;
+constexpr OString tok_d = "d"_ostr;
+constexpr OString tok_e = "e"_ostr;
+constexpr OString tok_f = "f"_ostr;
+constexpr OString tok_g = "g"_ostr;
+constexpr OString tok_h = "h"_ostr;
+constexpr OString tok_i = "i"_ostr;
+constexpr OString tok_j = "j"_ostr;
+constexpr OString tok_k = "k"_ostr;
+constexpr OString tok_l = "l"_ostr;
+constexpr OString tok_m = "m"_ostr;
+constexpr OString tok_n = "n"_ostr;
+constexpr OString tok_o = "o"_ostr;
+constexpr OString tok_p = "p"_ostr;
+constexpr OString tok_q = "q"_ostr;
+constexpr OString tok_r = "r"_ostr;
+constexpr OString tok_s = "s"_ostr;
+constexpr OString tok_t = "t"_ostr;
+constexpr OString tok_u = "u"_ostr;
+constexpr OString tok_v = "v"_ostr;
+constexpr OString tok_w = "w"_ostr;
+constexpr OString tok_x = "x"_ostr;
+constexpr OString tok_y = "y"_ostr;
+constexpr OString tok_z = "z"_ostr;
+constexpr OString tok_braceleft = "braceleft"_ostr;
+constexpr OString tok_bar = "bar"_ostr;
+constexpr OString tok_braceright = "braceright"_ostr;
+constexpr OString tok_asciitilde = "asciitilde"_ostr;
+constexpr OString tok_exclamdown = "exclamdown"_ostr;
+constexpr OString tok_cent = "cent"_ostr;
+constexpr OString tok_sterlin = "sterlin"_ostr;
+constexpr OString tok_fraction = "fraction"_ostr;
+constexpr OString tok_yen = "yen"_ostr;
+constexpr OString tok_florin = "florin"_ostr;
+constexpr OString tok_section = "section"_ostr;
+constexpr OString tok_currency = "currency"_ostr;
+constexpr OString tok_quotesingle = "quotesingle"_ostr;
+constexpr OString tok_quotedblleft = "quotedblleft"_ostr;
+constexpr OString tok_guillemotleft = "guillemotleft"_ostr;
+constexpr OString tok_guilsinglleft = "guilsinglleft"_ostr;
+constexpr OString tok_guilsinglright = "guilsinglright"_ostr;
+constexpr OString tok_fi = "fi"_ostr;
+constexpr OString tok_fl = "fl"_ostr;
+constexpr OString tok_endash = "endash"_ostr;
+constexpr OString tok_dagger = "dagger"_ostr;
+constexpr OString tok_daggerdbl = "daggerdbl"_ostr;
+constexpr OString tok_periodcentered = "periodcentered"_ostr;
+constexpr OString tok_paragraph = "paragraph"_ostr;
+constexpr OString tok_bullet = "bullet"_ostr;
+constexpr OString tok_quotesinglbase = "quotesinglbase"_ostr;
+constexpr OString tok_quotedblbase = "quotedblbase"_ostr;
+constexpr OString tok_quotedblright = "quotedblright"_ostr;
+constexpr OString tok_guillemotright = "guillemotright"_ostr;
+constexpr OString tok_ellipsis = "ellipsis"_ostr;
+constexpr OString tok_perthousand = "perthousand"_ostr;
+constexpr OString tok_questiondown = "questiondown"_ostr;
+constexpr OString tok_grave = "grave"_ostr;
+constexpr OString tok_acute = "acute"_ostr;
+constexpr OString tok_circumflex = "circumflex"_ostr;
+constexpr OString tok_tilde = "tilde"_ostr;
+constexpr OString tok_macron = "macron"_ostr;
+constexpr OString tok_breve = "breve"_ostr;
+constexpr OString tok_dotaccent = "dotaccent"_ostr;
+constexpr OString tok_dieresis = "dieresis"_ostr;
+constexpr OString tok_ring = "ring"_ostr;
+constexpr OString tok_cedilla = "cedilla"_ostr;
+constexpr OString tok_hungarumlaut = "hungarumlaut"_ostr;
+constexpr OString tok_ogonek = "ogonek"_ostr;
+constexpr OString tok_caron = "caron"_ostr;
+constexpr OString tok_emdash = "emdash"_ostr;
+constexpr OString tok_AE = "AE"_ostr;
+constexpr OString tok_ordfeminine = "ordfeminine"_ostr;
+constexpr OString tok_Lslash = "Lslash"_ostr;
+constexpr OString tok_Oslash = "Oslash"_ostr;
+constexpr OString tok_OE = "OE"_ostr;
+constexpr OString tok_ordmasculine = "ordmasculine"_ostr;
+constexpr OString tok_ae = "ae"_ostr;
+constexpr OString tok_dotlessi = "dotlessi"_ostr;
+constexpr OString tok_lslash = "lslash"_ostr;
+constexpr OString tok_oslash = "oslash"_ostr;
+constexpr OString tok_oe = "oe"_ostr;
+constexpr OString tok_germandbls = "germandbls"_ostr;
+constexpr OString tok_onesuperior = "onesuperior"_ostr;
+constexpr OString tok_logicalnot = "logicalnot"_ostr;
+constexpr OString tok_mu = "mu"_ostr;
+constexpr OString tok_trademark = "trademark"_ostr;
+constexpr OString tok_Eth = "Eth"_ostr;
+constexpr OString tok_onehalf = "onehalf"_ostr;
+constexpr OString tok_plusminus = "plusminus"_ostr;
+constexpr OString tok_Thorn = "Thorn"_ostr;
+constexpr OString tok_onequarter = "onequarter"_ostr;
+constexpr OString tok_divide = "divide"_ostr;
+constexpr OString tok_brokenbar = "brokenbar"_ostr;
+constexpr OString tok_degree = "degree"_ostr;
+constexpr OString tok_thorn = "thorn"_ostr;
+constexpr OString tok_threequarters = "threequarters"_ostr;
+constexpr OString tok_twosuperior = "twosuperior"_ostr;
+constexpr OString tok_registered = "registered"_ostr;
+constexpr OString tok_minus = "minus"_ostr;
+constexpr OString tok_eth = "eth"_ostr;
+constexpr OString tok_multiply = "multiply"_ostr;
+constexpr OString tok_threesuperior = "threesuperior"_ostr;
+constexpr OString tok_copyright = "copyright"_ostr;
+constexpr OString tok_Aacute = "Aacute"_ostr;
+constexpr OString tok_Acircumflex = "Acircumflex"_ostr;
+constexpr OString tok_Adieresis = "Adieresis"_ostr;
+constexpr OString tok_Agrave = "Agrave"_ostr;
+constexpr OString tok_Aring = "Aring"_ostr;
+constexpr OString tok_Atilde = "Atilde"_ostr;
+constexpr OString tok_Ccedilla = "Ccedilla"_ostr;
+constexpr OString tok_Eacute = "Eacute"_ostr;
+constexpr OString tok_Ecircumflex = "Ecircumflex"_ostr;
+constexpr OString tok_Edieresis = "Edieresis"_ostr;
+constexpr OString tok_Egrave = "Egrave"_ostr;
+constexpr OString tok_Iacute = "Iacute"_ostr;
+constexpr OString tok_Icircumflex = "Icircumflex"_ostr;
+constexpr OString tok_Idieresis = "Idieresis"_ostr;
+constexpr OString tok_Igrave = "Igrave"_ostr;
+constexpr OString tok_Ntilde = "Ntilde"_ostr;
+constexpr OString tok_Oacute = "Oacute"_ostr;
+constexpr OString tok_Ocircumflex = "Ocircumflex"_ostr;
+constexpr OString tok_Odieresis = "Odieresis"_ostr;
+constexpr OString tok_Ograve = "Ograve"_ostr;
+constexpr OString tok_Otilde = "Otilde"_ostr;
+constexpr OString tok_Scaron = "Scaron"_ostr;
+constexpr OString tok_Uacute = "Uacute"_ostr;
+constexpr OString tok_Ucircumflex = "Ucircumflex"_ostr;
+constexpr OString tok_Udieresis = "Udieresis"_ostr;
+constexpr OString tok_Ugrave = "Ugrave"_ostr;
+constexpr OString tok_Yacute = "Yacute"_ostr;
+constexpr OString tok_Ydieresis = "Ydieresis"_ostr;
+constexpr OString tok_Zcaron = "Zcaron"_ostr;
+constexpr OString tok_aacute = "aacute"_ostr;
+constexpr OString tok_acircumflex = "acircumflex"_ostr;
+constexpr OString tok_adieresis = "adieresis"_ostr;
+constexpr OString tok_agrave = "agrave"_ostr;
+constexpr OString tok_aring = "aring"_ostr;
+constexpr OString tok_atilde = "atilde"_ostr;
+constexpr OString tok_ccedilla = "ccedilla"_ostr;
+constexpr OString tok_eacute = "eacute"_ostr;
+constexpr OString tok_ecircumflex = "ecircumflex"_ostr;
+constexpr OString tok_edieresis = "edieresis"_ostr;
+constexpr OString tok_egrave = "egrave"_ostr;
+constexpr OString tok_iacute = "iacute"_ostr;
+constexpr OString tok_icircumflex = "icircumflex"_ostr;
+constexpr OString tok_idieresis = "idieresis"_ostr;
+constexpr OString tok_igrave = "igrave"_ostr;
+constexpr OString tok_ntilde = "ntilde"_ostr;
+constexpr OString tok_oacute = "oacute"_ostr;
+constexpr OString tok_ocircumflex = "ocircumflex"_ostr;
+constexpr OString tok_odieresis = "odieresis"_ostr;
+constexpr OString tok_ograve = "ograve"_ostr;
+constexpr OString tok_otilde = "otilde"_ostr;
+constexpr OString tok_scaron = "scaron"_ostr;
+constexpr OString tok_uacute = "uacute"_ostr;
+constexpr OString tok_ucircumflex = "ucircumflex"_ostr;
+constexpr OString tok_udieresis = "udieresis"_ostr;
+constexpr OString tok_ugrave = "ugrave"_ostr;
+constexpr OString tok_yacute = "yacute"_ostr;
+constexpr OString tok_ydieresis = "ydieresis"_ostr;
+constexpr OString tok_zcaron = "zcaron"_ostr;
+constexpr OString tok_exclamsmall = "exclamsmall"_ostr;
+constexpr OString tok_Hungarumlautsmall = "Hungarumlautsmall"_ostr;
+constexpr OString tok_dollaroldstyle = "dollaroldstyle"_ostr;
+constexpr OString tok_dollarsuperior = "dollarsuperior"_ostr;
+constexpr OString tok_ampersandsmall = "ampersandsmall"_ostr;
+constexpr OString tok_Acutesmall = "Acutesmall"_ostr;
+constexpr OString tok_parenleftsuperior = "parenleftsuperior"_ostr;
+constexpr OString tok_parenrightsuperior = "parenrightsuperior"_ostr;
+constexpr OString tok_twodotenleader = "twodotenleader"_ostr;
+constexpr OString tok_onedotenleader = "onedotenleader"_ostr;
+constexpr OString tok_zerooldstyle = "zerooldstyle"_ostr;
+constexpr OString tok_oneoldstyle = "oneoldstyle"_ostr;
+constexpr OString tok_twooldstyle = "twooldstyle"_ostr;
+constexpr OString tok_threeoldstyle = "threeoldstyle"_ostr;
+constexpr OString tok_fouroldstyle = "fouroldstyle"_ostr;
+constexpr OString tok_fiveoldstyle = "fiveoldstyle"_ostr;
+constexpr OString tok_sixoldstyle = "sixoldstyle"_ostr;
+constexpr OString tok_sevenoldstyle = "sevenoldstyle"_ostr;
+constexpr OString tok_eightoldstyle = "eightoldstyle"_ostr;
+constexpr OString tok_nineoldstile = "nineoldstile"_ostr;
+constexpr OString tok_commasuperior = "commasuperior"_ostr;
+constexpr OString tok_threequartersemdash = "threequartersemdash"_ostr;
+constexpr OString tok_periodsuperior = "periodsuperior"_ostr;
+constexpr OString tok_questionsmall = "questionsmall"_ostr;
+constexpr OString tok_asuperior = "asuperior"_ostr;
+constexpr OString tok_bsuperior = "bsuperior"_ostr;
+constexpr OString tok_centsuperior = "centsuperior"_ostr;
+constexpr OString tok_dsuperior = "dsuperior"_ostr;
+constexpr OString tok_esuperior = "esuperior"_ostr;
+constexpr OString tok_isuperior = "isuperior"_ostr;
+constexpr OString tok_lsuperior = "lsuperior"_ostr;
+constexpr OString tok_msuperior = "msuperior"_ostr;
+constexpr OString tok_nsuperior = "nsuperior"_ostr;
+constexpr OString tok_osuperior = "osuperior"_ostr;
+constexpr OString tok_rsuperior = "rsuperior"_ostr;
+constexpr OString tok_ssuperior = "ssuperior"_ostr;
+constexpr OString tok_tsuperior = "tsuperior"_ostr;
+constexpr OString tok_ff = "ff"_ostr;
+constexpr OString tok_ffi = "ffi"_ostr;
+constexpr OString tok_ffl = "ffl"_ostr;
+constexpr OString tok_parenleftinferior = "parenleftinferior"_ostr;
+constexpr OString tok_parenrightinferior = "parenrightinferior"_ostr;
+constexpr OString tok_Circumflexsmall = "Circumflexsmall"_ostr;
+constexpr OString tok_hyphensuperior = "hyphensuperior"_ostr;
+constexpr OString tok_Gravesmall = "Gravesmall"_ostr;
+constexpr OString tok_Asmall = "Asmall"_ostr;
+constexpr OString tok_Bsmall = "Bsmall"_ostr;
+constexpr OString tok_Csmall = "Csmall"_ostr;
+constexpr OString tok_Dsmall = "Dsmall"_ostr;
+constexpr OString tok_Esmall = "Esmall"_ostr;
+constexpr OString tok_Fsmall = "Fsmall"_ostr;
+constexpr OString tok_Gsmall = "Gsmall"_ostr;
+constexpr OString tok_Hsmall = "Hsmall"_ostr;
+constexpr OString tok_Ismall = "Ismall"_ostr;
+constexpr OString tok_Jsmall = "Jsmall"_ostr;
+constexpr OString tok_Ksmall = "Ksmall"_ostr;
+constexpr OString tok_Lsmall = "Lsmall"_ostr;
+constexpr OString tok_Msmall = "Msmall"_ostr;
+constexpr OString tok_Nsmall = "Nsmall"_ostr;
+constexpr OString tok_Osmall = "Osmall"_ostr;
+constexpr OString tok_Psmall = "Psmall"_ostr;
+constexpr OString tok_Qsmall = "Qsmall"_ostr;
+constexpr OString tok_Rsmall = "Rsmall"_ostr;
+constexpr OString tok_Ssmall = "Ssmall"_ostr;
+constexpr OString tok_Tsmall = "Tsmall"_ostr;
+constexpr OString tok_Usmall = "Usmall"_ostr;
+constexpr OString tok_Vsmall = "Vsmall"_ostr;
+constexpr OString tok_Wsmall = "Wsmall"_ostr;
+constexpr OString tok_Xsmall = "Xsmall"_ostr;
+constexpr OString tok_Ysmall = "Ysmall"_ostr;
+constexpr OString tok_Zsmall = "Zsmall"_ostr;
+constexpr OString tok_colonmonetary = "colonmonetary"_ostr;
+constexpr OString tok_onefitted = "onefitted"_ostr;
+constexpr OString tok_rupia = "rupia"_ostr;
+constexpr OString tok_Tildesmall = "Tildesmall"_ostr;
+constexpr OString tok_exclamdownsmall = "exclamdownsmall"_ostr;
+constexpr OString tok_centoldstyle = "centoldstyle"_ostr;
+constexpr OString tok_Lslashsmall = "Lslashsmall"_ostr;
+constexpr OString tok_Scaronsmall = "Scaronsmall"_ostr;
+constexpr OString tok_Zcaronsmall = "Zcaronsmall"_ostr;
+constexpr OString tok_Dieresissmall = "Dieresissmall"_ostr;
+constexpr OString tok_Brevesmall = "Brevesmall"_ostr;
+constexpr OString tok_Caronsmall = "Caronsmall"_ostr;
+constexpr OString tok_Dotaccentsmall = "Dotaccentsmall"_ostr;
+constexpr OString tok_Macronsmall = "Macronsmall"_ostr;
+constexpr OString tok_figuredash = "figuredash"_ostr;
+constexpr OString tok_hypheninferior = "hypheninferior"_ostr;
+constexpr OString tok_Ogoneksmall = "Ogoneksmall"_ostr;
+constexpr OString tok_Ringsmall = "Ringsmall"_ostr;
+constexpr OString tok_Cedillasmall = "Cedillasmall"_ostr;
+constexpr OString tok_questiondownsmall = "questiondownsmall"_ostr;
+constexpr OString tok_oneeight = "oneeight"_ostr;
+constexpr OString tok_threeeights = "threeeights"_ostr;
+constexpr OString tok_fiveeights = "fiveeights"_ostr;
+constexpr OString tok_seveneights = "seveneights"_ostr;
+constexpr OString tok_onethird = "onethird"_ostr;
+constexpr OString tok_twothirds = "twothirds"_ostr;
+constexpr OString tok_zerosuperior = "zerosuperior"_ostr;
+constexpr OString tok_foursuperior = "foursuperior"_ostr;
+constexpr OString tok_fivesuperior = "fivesuperior"_ostr;
+constexpr OString tok_sixsuperior = "sixsuperior"_ostr;
+constexpr OString tok_sevensuperior = "sevensuperior"_ostr;
+constexpr OString tok_eightsuperior = "eightsuperior"_ostr;
+constexpr OString tok_ninesuperior = "ninesuperior"_ostr;
+constexpr OString tok_zeroinferior = "zeroinferior"_ostr;
+constexpr OString tok_oneinferior = "oneinferior"_ostr;
+constexpr OString tok_twoinferior = "twoinferior"_ostr;
+constexpr OString tok_threeinferior = "threeinferior"_ostr;
+constexpr OString tok_fourinferior = "fourinferior"_ostr;
+constexpr OString tok_fiveinferior = "fiveinferior"_ostr;
+constexpr OString tok_sixinferior = "sixinferior"_ostr;
+constexpr OString tok_seveninferior = "seveninferior"_ostr;
+constexpr OString tok_eightinferior = "eightinferior"_ostr;
+constexpr OString tok_nineinferior = "nineinferior"_ostr;
+constexpr OString tok_centinferior = "centinferior"_ostr;
+constexpr OString tok_dollarinferior = "dollarinferior"_ostr;
+constexpr OString tok_periodinferior = "periodinferior"_ostr;
+constexpr OString tok_commainferior = "commainferior"_ostr;
+constexpr OString tok_Agravesmall = "Agravesmall"_ostr;
+constexpr OString tok_Aacutesmall = "Aacutesmall"_ostr;
+constexpr OString tok_Acircumflexsmall = "Acircumflexsmall"_ostr;
+constexpr OString tok_Atildesmall = "Atildesmall"_ostr;
+constexpr OString tok_Adieresissmall = "Adieresissmall"_ostr;
+constexpr OString tok_Aringsmall = "Aringsmall"_ostr;
+constexpr OString tok_AEsmall = "AEsmall"_ostr;
+constexpr OString tok_Ccedillasmall = "Ccedillasmall"_ostr;
+constexpr OString tok_Egravesmall = "Egravesmall"_ostr;
+constexpr OString tok_Eacutesmall = "Eacutesmall"_ostr;
+constexpr OString tok_Ecircumflexsmall = "Ecircumflexsmall"_ostr;
+constexpr OString tok_Edieresissmall = "Edieresissmall"_ostr;
+constexpr OString tok_Igravesmall = "Igravesmall"_ostr;
+constexpr OString tok_Iacutesmall = "Iacutesmall"_ostr;
+constexpr OString tok_Icircumflexsmall = "Icircumflexsmall"_ostr;
+constexpr OString tok_Idieresissmall = "Idieresissmall"_ostr;
+constexpr OString tok_Ethsmall = "Ethsmall"_ostr;
+constexpr OString tok_Ntildesmall = "Ntildesmall"_ostr;
+constexpr OString tok_Ogravesmall = "Ogravesmall"_ostr;
+constexpr OString tok_Oacutesmall = "Oacutesmall"_ostr;
+constexpr OString tok_Ocircumflexsmall = "Ocircumflexsmall"_ostr;
+constexpr OString tok_Otildesmall = "Otildesmall"_ostr;
+constexpr OString tok_Odieressissmall = "Odieressissmall"_ostr;
+constexpr OString tok_OEsmall = "OEsmall"_ostr;
+constexpr OString tok_Oslashsmall = "Oslashsmall"_ostr;
+constexpr OString tok_Ugravesmall = "Ugravesmall"_ostr;
+constexpr OString tok_Uacutesmall = "Uacutesmall"_ostr;
+constexpr OString tok_Ucircumflexsmall = "Ucircumflexsmall"_ostr;
+constexpr OString tok_Udieresissmall = "Udieresissmall"_ostr;
+constexpr OString tok_Yacutesmall = "Yacutesmall"_ostr;
+constexpr OString tok_Thornsmall = "Thornsmall"_ostr;
+constexpr OString tok_Ydieresissmall = "Ydieresissmall"_ostr;
+constexpr OString tok_001_000 = "001.000"_ostr;
+constexpr OString tok_001_001 = "001.001"_ostr;
+constexpr OString tok_001_002 = "001.002"_ostr;
+constexpr OString tok_001_003 = "001.003"_ostr;
+constexpr OString tok_Black = "Black"_ostr;
+constexpr OString tok_Bold = "Bold"_ostr;
+constexpr OString tok_Book = "Book"_ostr;
+constexpr OString tok_Light = "Light"_ostr;
+constexpr OString tok_Medium = "Medium"_ostr;
+constexpr OString tok_Regular = "Regular"_ostr;
+constexpr OString tok_Roman = "Roman"_ostr;
+constexpr OString tok_Semibold = "Semibold"_ostr;
+
+constexpr OString pStringIds[] = {
+/*0*/ tok_notdef, tok_space, tok_exclam, tok_quotedbl,
+ tok_numbersign, tok_dollar, tok_percent, tok_ampersand,
+ tok_quoteright, tok_parenleft, tok_parenright, tok_asterisk,
+ tok_plus, tok_comma, tok_hyphen, tok_period,
+/*16*/ tok_slash, tok_zero, tok_one, tok_two,
+ tok_three, tok_four, tok_five, tok_six,
+ tok_seven, tok_eight, tok_nine, tok_colon,
+ tok_semicolon, tok_less, tok_equal, tok_greater,
+/*32*/ tok_question, tok_at, tok_A, tok_B,
+ tok_C, tok_D, tok_E, tok_F,
+ tok_G, tok_H, tok_I, tok_J,
+ tok_K, tok_L, tok_M, tok_N,
+/*48*/ tok_O, tok_P, tok_Q, tok_R,
+ tok_S, tok_T, tok_U, tok_V,
+ tok_W, tok_X, tok_Y, tok_Z,
+ tok_bracketleft, tok_backslash, tok_bracketright, tok_asciicircum,
+/*64*/ tok_underscore, tok_quoteleft, tok_a, tok_b,
+ tok_c, tok_d, tok_e, tok_f,
+ tok_g, tok_h, tok_i, tok_j,
+ tok_k, tok_l, tok_m, tok_n,
+/*80*/ tok_o, tok_p, tok_q, tok_r,
+ tok_s, tok_t, tok_u, tok_v,
+ tok_w, tok_x, tok_y, tok_z,
+ tok_braceleft, tok_bar, tok_braceright, tok_asciitilde,
+/*96*/ tok_exclamdown, tok_cent, tok_sterlin, tok_fraction,
+ tok_yen, tok_florin, tok_section, tok_currency,
+ tok_quotesingle, tok_quotedblleft, tok_guillemotleft, tok_guilsinglleft,
+ tok_guilsinglright, tok_fi, tok_fl, tok_endash,
+/*112*/ tok_dagger, tok_daggerdbl, tok_periodcentered, tok_paragraph,
+ tok_bullet, tok_quotesinglbase, tok_quotedblbase, tok_quotedblright,
+ tok_guillemotright, tok_ellipsis, tok_perthousand, tok_questiondown,
+ tok_grave, tok_acute, tok_circumflex, tok_tilde,
+/*128*/ tok_macron, tok_breve, tok_dotaccent, tok_dieresis,
+ tok_ring, tok_cedilla, tok_hungarumlaut, tok_ogonek,
+ tok_caron, tok_emdash, tok_AE, tok_ordfeminine,
+ tok_Lslash, tok_Oslash, tok_OE, tok_ordmasculine,
+/*144*/ tok_ae, tok_dotlessi, tok_lslash, tok_oslash,
+ tok_oe, tok_germandbls, tok_onesuperior, tok_logicalnot,
+ tok_mu, tok_trademark, tok_Eth, tok_onehalf,
+ tok_plusminus, tok_Thorn, tok_onequarter, tok_divide,
+/*160*/ tok_brokenbar, tok_degree, tok_thorn, tok_threequarters,
+ tok_twosuperior, tok_registered, tok_minus, tok_eth,
+ tok_multiply, tok_threesuperior, tok_copyright, tok_Aacute,
+ tok_Acircumflex, tok_Adieresis, tok_Agrave, tok_Aring,
+/*176*/ tok_Atilde, tok_Ccedilla, tok_Eacute, tok_Ecircumflex,
+ tok_Edieresis, tok_Egrave, tok_Iacute, tok_Icircumflex,
+ tok_Idieresis, tok_Igrave, tok_Ntilde, tok_Oacute,
+ tok_Ocircumflex, tok_Odieresis, tok_Ograve, tok_Otilde,
+/*192*/ tok_Scaron, tok_Uacute, tok_Ucircumflex, tok_Udieresis,
+ tok_Ugrave, tok_Yacute, tok_Ydieresis, tok_Zcaron,
+ tok_aacute, tok_acircumflex, tok_adieresis, tok_agrave,
+ tok_aring, tok_atilde, tok_ccedilla, tok_eacute,
+/*208*/ tok_ecircumflex, tok_edieresis, tok_egrave, tok_iacute,
+ tok_icircumflex, tok_idieresis, tok_igrave, tok_ntilde,
+ tok_oacute, tok_ocircumflex, tok_odieresis, tok_ograve,
+ tok_otilde, tok_scaron, tok_uacute, tok_ucircumflex,
+/*224*/ tok_udieresis, tok_ugrave, tok_yacute, tok_ydieresis,
+ tok_zcaron, tok_exclamsmall, tok_Hungarumlautsmall,tok_dollaroldstyle,
+ tok_dollarsuperior, tok_ampersandsmall, tok_Acutesmall, tok_parenleftsuperior,
+ tok_parenrightsuperior,tok_twodotenleader, tok_onedotenleader, tok_zerooldstyle,
+/*240*/ tok_oneoldstyle, tok_twooldstyle, tok_threeoldstyle, tok_fouroldstyle,
+ tok_fiveoldstyle, tok_sixoldstyle, tok_sevenoldstyle, tok_eightoldstyle,
+ tok_nineoldstile, tok_commasuperior, tok_threequartersemdash,tok_periodsuperior,
+ tok_questionsmall, tok_asuperior, tok_bsuperior, tok_centsuperior,
+/*256*/ tok_dsuperior, tok_esuperior, tok_isuperior, tok_lsuperior,
+ tok_msuperior, tok_nsuperior, tok_osuperior, tok_rsuperior,
+ tok_ssuperior, tok_tsuperior, tok_ff, tok_ffi,
+ tok_ffl, tok_parenleftinferior,tok_parenrightinferior,tok_Circumflexsmall,
+/*272*/ tok_hyphensuperior,tok_Gravesmall, tok_Asmall, tok_Bsmall,
+ tok_Csmall, tok_Dsmall, tok_Esmall, tok_Fsmall,
+ tok_Gsmall, tok_Hsmall, tok_Ismall, tok_Jsmall,
+ tok_Ksmall, tok_Lsmall, tok_Msmall, tok_Nsmall,
+/*288*/ tok_Osmall, tok_Psmall, tok_Qsmall, tok_Rsmall,
+ tok_Ssmall, tok_Tsmall, tok_Usmall, tok_Vsmall,
+ tok_Wsmall, tok_Xsmall, tok_Ysmall, tok_Zsmall,
+ tok_colonmonetary, tok_onefitted, tok_rupia, tok_Tildesmall,
+/*304*/ tok_exclamdownsmall,tok_centoldstyle, tok_Lslashsmall, tok_Scaronsmall,
+ tok_Zcaronsmall, tok_Dieresissmall, tok_Brevesmall, tok_Caronsmall,
+ tok_Dotaccentsmall, tok_Macronsmall, tok_figuredash, tok_hypheninferior,
+ tok_Ogoneksmall, tok_Ringsmall, tok_Cedillasmall, tok_questiondownsmall,
+/*320*/ tok_oneeight, tok_threeeights, tok_fiveeights, tok_seveneights,
+ tok_onethird, tok_twothirds, tok_zerosuperior, tok_foursuperior,
+ tok_fivesuperior, tok_sixsuperior, tok_sevensuperior, tok_eightsuperior,
+ tok_ninesuperior, tok_zeroinferior, tok_oneinferior, tok_twoinferior,
+/*336*/ tok_threeinferior,tok_fourinferior, tok_fiveinferior, tok_sixinferior,
+ tok_seveninferior, tok_eightinferior, tok_nineinferior, tok_centinferior,
+ tok_dollarinferior, tok_periodinferior, tok_commainferior, tok_Agravesmall,
+ tok_Aacutesmall, tok_Acircumflexsmall, tok_Atildesmall, tok_Adieresissmall,
+/*352*/ tok_Aringsmall, tok_AEsmall, tok_Ccedillasmall, tok_Egravesmall,
+ tok_Eacutesmall, tok_Ecircumflexsmall, tok_Edieresissmall, tok_Igravesmall,
+ tok_Iacutesmall, tok_Icircumflexsmall, tok_Idieresissmall, tok_Ethsmall,
+ tok_Ntildesmall, tok_Ogravesmall, tok_Oacutesmall, tok_Ocircumflexsmall,
+/*368*/ tok_Otildesmall, tok_Odieressissmall, tok_OEsmall, tok_Oslashsmall,
+ tok_Ugravesmall, tok_Uacutesmall, tok_Ucircumflexsmall, tok_Udieresissmall,
+ tok_Yacutesmall, tok_Thornsmall, tok_Ydieresissmall, tok_001_000,
+ tok_001_001, tok_001_002, tok_001_003, tok_Black,
+/*384*/ tok_Bold, tok_Book, tok_Light, tok_Medium,
+ tok_Regular, tok_Roman, tok_Semibold
+};
+
+// TOP DICT keywords (also covers PRIV DICT keywords)
+static const char* pDictOps[] = {
+ "sVersion", "sNotice", "sFullName", "sFamilyName",
+ "sWeight", "aFontBBox", "dBlueValues", "dOtherBlues",
+ "dFamilyBlues", "dFamilyOtherBlues", "nStdHW", "nStdVW",
+ "xESC", "nUniqueID", "aXUID", "nCharset",
+ "nEncoding", "nCharStrings", "PPrivate", "nSubrs",
+ "nDefaultWidthX", "nNominalWidthX", nullptr, nullptr,
+ nullptr, nullptr, nullptr, nullptr,
+ "shortint", "longint", "BCD", nullptr
+};
+
+// TOP DICT escapes (also covers PRIV DICT escapes)
+static const char* pDictEscs[] = {
+ "sCopyright", "bIsFixedPitch", "nItalicAngle", "nUnderlinePosition",
+ "nUnderlineThickness", "nPaintType", "tCharstringType", "aFontMatrix",
+ "nStrokeWidth", "nBlueScale", "nBlueShift", "nBlueFuzz",
+ "dStemSnapH", "dStemSnapV", "bForceBold", nullptr,
+ nullptr, "nLanguageGroup", "nExpansionFactor", "nInitialRandomSeed",
+ "nSyntheticBase", "sPostScript", "sBaseFontName", "dBaseFontBlend",
+ nullptr, nullptr, nullptr, nullptr,
+ nullptr, nullptr, "rROS", "nCIDFontVersion",
+ "nCIDFontRevision", "nCIDFontType", "nCIDCount", "nUIDBase",
+ "nFDArray", "nFDSelect", "sFontName"
+};
+
+static const char* pStandardEncoding[] = {
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", "space", "exclam", "quotedbl",
+ "numbersign", "dollar", "percent", "ampersand",
+ "quoteright", "parenleft", "parenright", "asterisk", "plus",
+ "comma", "hyphen", "period", "slash", "zero", "one", "two",
+ "three", "four", "five", "six", "seven", "eight", "nine",
+ "colon", "semicolon", "less", "equal", "greater",
+ "question", "at", "A", "B", "C", "D", "E", "F", "G", "H",
+ "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
+ "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
+ "bracketright", "asciicircum", "underscore", "quoteleft",
+ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
+ "y", "z", "braceleft", "bar", "braceright", "asciitilde",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", "exclamdown",
+ "cent", "sterling", "fraction", "yen", "florin", "section",
+ "currency", "quotesingle", "quotedblleft", "guillemotleft",
+ "guilsinglleft", "guilsinglright", "fi", "fl", ".notdef",
+ "endash", "dagger", "daggerdbl", "periodcentered",
+ ".notdef", "paragraph", "bullet", "quotesinglbase",
+ "quotedblbase", "quotedblright", "guillemotright",
+ "ellipsis", "perthousand", ".notdef", "questiondown",
+ ".notdef", "grave", "acute", "circumflex", "tilde",
+ "macron", "breve", "dotaccent", "dieresis", ".notdef",
+ "ring", "cedilla", ".notdef", "hungarumlaut", "ogonek",
+ "caron", "emdash", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef",
+ ".notdef", ".notdef", ".notdef", "AE", ".notdef",
+ "ordfeminine", ".notdef", ".notdef", ".notdef", ".notdef",
+ "Lslash", "Oslash", "OE", "ordmasculine", ".notdef",
+ ".notdef", ".notdef", ".notdef", ".notdef", "ae", ".notdef",
+ ".notdef", ".notdef", "dotlessi", ".notdef", ".notdef",
+ "lslash", "oslash", "oe", "germandbls", ".notdef",
+ ".notdef", ".notdef", ".notdef"
+};
+
+namespace {
+
+namespace TYPE1OP
+{
+ enum OPS
+ {
+ HSTEM=1, VSTEM=3, VMOVETO=4, RLINETO=5,
+ HLINETO=6, VLINETO=7, RCURVETO=8, CLOSEPATH=9,
+ CALLSUBR=10, RETURN=11, T1ESC=12, HSBW=13,
+ ENDCHAR=14, RMOVETO=21, HMOVETO=22, VHCURVETO=30,
+ HVCURVETO=31
+ };
+
+ enum ESCS
+ {
+ DOTSECTION=0, VSTEM3=1, HSTEM3=2, SEAC=6,
+ SBW=7, ABS=9, ADD=10, SUB=11,
+ DIV=12, CALLOTHERSUBR=16, POP=17, SETCURRENTPOINT=33
+ };
+}
+
+namespace TYPE2OP
+{
+ enum OPS
+ {
+ HSTEM=1, VSTEM=3, VMOVETO=4, RLINETO=5,
+ HLINETO=6, VLINETO=7, RCURVETO=8, CALLSUBR=10,
+ RETURN=11, T2ESC=12, ENDCHAR=14, HSTEMHM=18,
+ HINTMASK=19, CNTRMASK=20, RMOVETO=21, HMOVETO=22,
+ VSTEMHM=23, RCURVELINE=24, RLINECURVE=25, VVCURVETO=26,
+ HHCURVETO=27, SHORTINT=28, CALLGSUBR=29, VHCURVETO=30,
+ HVCURVETO=31
+ };
+
+ enum ESCS
+ {
+ AND=3, OR=4, NOT=5, ABS=9,
+ ADD=10, SUB=11, DIV=12, NEG=14,
+ EQ=15, DROP=18, PUT=20, GET=21,
+ IFELSE=22, RANDOM=23, MUL=24, SQRT=26,
+ DUP=27, EXCH=28, INDEX=29, ROLL=30,
+ HFLEX=34, FLEX=35, HFLEX1=36, FLEX1=37
+ };
+}
+
+struct CffGlobal
+{
+ explicit CffGlobal();
+
+ int mnNameIdxBase;
+ int mnStringIdxBase;
+ bool mbCIDFont;
+ int mnCharStrBase;
+ int mnCharStrCount;
+ int mnCharsetBase;
+ int mnGlobalSubrBase;
+ int mnGlobalSubrCount;
+ int mnGlobalSubrBias;
+ int mnFDSelectBase;
+ int mnFontDictBase;
+ int mnFDAryCount;
+
+ std::vector<ValType> maFontBBox;
+ std::vector<ValType> maFontMatrix;
+
+ int mnFontNameSID;
+ int mnFullNameSID;
+};
+
+struct CffLocal
+{
+ explicit CffLocal();
+
+ int mnPrivDictBase;
+ int mnPrivDictSize;
+ int mnLocalSubrOffs;
+ int mnLocalSubrBase;
+ int mnLocalSubrBias;
+
+ ValType maNominalWidth;
+ ValType maDefaultWidth;
+
+ // ATM hinting related values
+ ValType maStemStdHW;
+ ValType maStemStdVW;
+ std::vector<ValType> maStemSnapH;
+ std::vector<ValType> maStemSnapV;
+ std::vector<ValType> maBlueValues;
+ std::vector<ValType> maOtherBlues;
+ std::vector<ValType> maFamilyBlues;
+ std::vector<ValType> maFamilyOtherBlues;
+ RealType mfBlueScale;
+ RealType mfBlueShift;
+ RealType mfBlueFuzz;
+ RealType mfExpFactor;
+ int mnLangGroup;
+ bool mbForceBold;
+};
+
+const int MAX_T1OPS_SIZE = 81920; // TODO: use dynamic value
+
+struct CharString
+{
+ int nLen;
+ U8 aOps[MAX_T1OPS_SIZE];
+ int nCffGlyphId;
+};
+
+
+class CffSubsetterContext
+: private CffGlobal
+{
+public:
+ static const int NMAXSTACK = 48; // see CFF.appendixB
+ static const int NMAXHINTS = 2*96; // see CFF.appendixB
+ static const int NMAXTRANS = 32; // see CFF.appendixB
+
+ explicit CffSubsetterContext( const U8* pBasePtr, int nBaseLen);
+
+ bool initialCffRead();
+ void emitAsType1( class Type1Emitter&,
+ const sal_GlyphId* pGlyphIds, const U8* pEncoding,
+ int nGlyphCount, FontSubsetInfo& );
+
+private:
+ void convertCharStrings(const sal_GlyphId* pGlyphIds, int nGlyphCount,
+ std::vector<CharString>& rCharStrings);
+ int convert2Type1Ops( CffLocal*, const U8* pType2Ops, int nType2Len, U8* pType1Ops);
+ void convertOneTypeOp();
+ void convertOneTypeEsc();
+ void callType2Subr( bool bGlobal, int nSubrNumber);
+ sal_Int32 getReadOfs() const { return static_cast<sal_Int32>(mpReadPtr - mpBasePtr);}
+
+ const U8* mpBasePtr;
+ const U8* mpBaseEnd;
+
+ const U8* mpReadPtr;
+ const U8* mpReadEnd;
+
+ U8* mpWritePtr;
+ bool mbNeedClose;
+ bool mbIgnoreHints;
+ sal_Int32 mnCntrMask;
+
+ int seekIndexData( int nIndexBase, int nDataIndex);
+ void seekIndexEnd( int nIndexBase);
+
+ CffLocal maCffLocal[256];
+ CffLocal* mpCffLocal;
+
+ void readDictOp();
+ RealType readRealVal();
+ OString getString( int nStringID);
+ int getFDSelect( int nGlyphIndex) const;
+ int getGlyphSID( int nGlyphIndex) const;
+ OString getGlyphName( int nGlyphIndex);
+ bool getBaseAccent(ValType aBase, ValType aAccent, int* nBase, int* nAccent);
+
+ void read2push();
+ void writeType1Val( ValType);
+ void writeTypeOp( int nTypeOp);
+ void writeTypeEsc( int nTypeOp);
+ void writeCurveTo( int nStackPos, int nIX1, int nIY1, int nIX2, int nIY2, int nIX3, int nIY3);
+ void pop2MultiWrite( int nArgsPerTypo, int nTypeOp, int nTypeXor=0);
+ void popAll2Write( int nTypeOp);
+
+public: // TODO: is public really needed?
+ // accessing the value stack
+ // TODO: add more checks
+ void push( ValType nVal) { mnValStack[ mnStackIdx++] = nVal;}
+ ValType popVal() { return ((mnStackIdx>0) ? mnValStack[ --mnStackIdx] : 0);}
+ ValType getVal( int nIndex) const { return mnValStack[ nIndex];}
+ int popInt();
+ int size() const { return mnStackIdx;}
+ void clear() { mnStackIdx = 0;}
+
+ // accessing the charstring hints
+ void addHints( bool bVerticalHints);
+
+ // accessing other charstring specifics
+ void updateWidth( bool bUseFirstVal);
+
+private:
+ // typeop execution context
+ int mnStackIdx;
+ ValType mnValStack[ NMAXSTACK+4];
+ ValType mnTransVals[ NMAXTRANS];
+
+ int mnHintSize;
+ int mnHorzHintSize;
+ ValType mnHintStack[ NMAXHINTS];
+
+ ValType maCharWidth;
+
+ bool mbDoSeac;
+ std::vector<sal_GlyphId> maExtraGlyphIds;
+};
+
+}
+
+CffSubsetterContext::CffSubsetterContext( const U8* pBasePtr, int nBaseLen)
+ : mpBasePtr( pBasePtr)
+ , mpBaseEnd( pBasePtr+nBaseLen)
+ , mpReadPtr(nullptr)
+ , mpReadEnd(nullptr)
+ , mpWritePtr(nullptr)
+ , mbNeedClose(false)
+ , mbIgnoreHints(false)
+ , mnCntrMask(0)
+ , mnStackIdx(0)
+ , mnValStack{}
+ , mnTransVals{}
+ , mnHintSize(0)
+ , mnHorzHintSize(0)
+ , mnHintStack{}
+ , maCharWidth(-1)
+ , mbDoSeac(true)
+{
+// setCharStringType( 1);
+ // TODO: new CffLocal[ mnFDAryCount];
+ mpCffLocal = &maCffLocal[0];
+}
+
+inline int CffSubsetterContext::popInt()
+{
+ const ValType aVal = popVal();
+ const int nInt = static_cast<int>(aVal);
+ assert( nInt == aVal);
+ return nInt;
+}
+
+inline void CffSubsetterContext::updateWidth( bool bUseFirstVal)
+{
+ // the first value is not a hint but the charwidth
+ if( maCharWidth>0 )
+ return;
+
+ if( bUseFirstVal) {
+ maCharWidth = mpCffLocal->maNominalWidth + mnValStack[0];
+ // remove bottom stack entry
+ --mnStackIdx;
+ for( int i = 0; i < mnStackIdx; ++i)
+ mnValStack[ i] = mnValStack[ i+1];
+ } else {
+ maCharWidth = mpCffLocal->maDefaultWidth;
+ }
+}
+
+void CffSubsetterContext::addHints( bool bVerticalHints)
+{
+ // the first charstring value may a charwidth instead of a charwidth
+ updateWidth( (mnStackIdx & 1) != 0);
+ // return early (e.g. no implicit hints for hintmask)
+ if( !mnStackIdx)
+ return;
+
+ // copy the remaining values to the hint arrays
+ // assert( (mnStackIdx & 1) == 0); // depends on called subrs
+ if( mnStackIdx & 1) --mnStackIdx;//#######
+ // TODO: if( !bSubr) assert( mnStackIdx >= 2);
+
+ assert( (mnHintSize + mnStackIdx) <= 2*NMAXHINTS);
+
+ ValType nHintOfs = 0;
+ for( int i = 0; i < mnStackIdx; ++i) {
+ nHintOfs += mnValStack[ i ];
+ mnHintStack[ mnHintSize++] = nHintOfs;
+ }
+
+ if( !bVerticalHints)
+ mnHorzHintSize = mnHintSize;
+
+ // clear all values from the stack
+ mnStackIdx = 0;
+}
+
+void CffSubsetterContext::readDictOp()
+{
+ const U8 c = *mpReadPtr;
+ if( c <= 21 ) {
+ int nOpId = *(mpReadPtr++);
+ const char* pCmdName = nullptr;
+ if( nOpId != 12)
+ pCmdName = pDictOps[nOpId];
+ else {
+ const U8 nExtId = *(mpReadPtr++);
+ if (nExtId < 39)
+ pCmdName = pDictEscs[nExtId];
+ nOpId = 900 + nExtId;
+ }
+
+ if (!pCmdName) // skip reserved operators
+ return;
+
+ //TODO: if( nStackIdx > 0)
+ int nInt = 0;
+ switch( *pCmdName) {
+ default: SAL_WARN("vcl.fonts", "unsupported DictOp.type='" << *pCmdName << "'."); break;
+ case 'b': // bool
+ nInt = popInt();
+ switch( nOpId) {
+ case 915: mpCffLocal->mbForceBold = nInt; break; // "ForceBold"
+ default: break; // TODO: handle more boolean dictops?
+ }
+ break;
+ case 'n': { // dict-op number
+ ValType nVal = popVal();
+ nInt = static_cast<int>(nVal);
+ switch( nOpId) {
+ case 10: mpCffLocal->maStemStdHW = nVal; break; // "StdHW"
+ case 11: mpCffLocal->maStemStdVW = nVal; break; // "StdVW"
+ case 15: mnCharsetBase = nInt; break; // "charset"
+ case 16: break; // "nEncoding"
+ case 17: mnCharStrBase = nInt; break; // "nCharStrings"
+ case 19: mpCffLocal->mnLocalSubrOffs = nInt; break;// "nSubrs"
+ case 20: mpCffLocal->maDefaultWidth = nVal; break; // "defaultWidthX"
+ case 21: mpCffLocal->maNominalWidth = nVal; break; // "nominalWidthX"
+ case 909: mpCffLocal->mfBlueScale = nVal; break; // "BlueScale"
+ case 910: mpCffLocal->mfBlueShift = nVal; break; // "BlueShift"
+ case 911: mpCffLocal->mfBlueFuzz = nVal; break; // "BlueFuzz"
+ case 912: mpCffLocal->mfExpFactor = nVal; break; // "ExpansionFactor"
+ case 917: mpCffLocal->mnLangGroup = nInt; break; // "LanguageGroup"
+ case 936: mnFontDictBase = nInt; break; // "nFDArray"
+ case 937: mnFDSelectBase = nInt; break; // "nFDSelect"
+ default: break; // TODO: handle more numeric dictops?
+ }
+ } break;
+ case 'a': { // array
+ switch( nOpId) {
+ case 5: maFontBBox.clear(); break; // "FontBBox"
+ case 907: maFontMatrix.clear(); break; // "FontMatrix"
+ default: break; // TODO: reset other arrays?
+ }
+ for( int i = 0; i < size(); ++i ) {
+ ValType nVal = getVal(i);
+ switch( nOpId) {
+ case 5: maFontBBox.push_back( nVal); break; // "FontBBox"
+ case 907: maFontMatrix.push_back( nVal); break; // "FontMatrix"
+ default: break; // TODO: handle more array dictops?
+ }
+ }
+ clear();
+ } break;
+ case 'd': { // delta array
+ ValType nVal = 0;
+ for( int i = 0; i < size(); ++i ) {
+ nVal += getVal(i);
+ switch( nOpId) {
+ case 6: mpCffLocal->maBlueValues.push_back( nVal); break; // "BlueValues"
+ case 7: mpCffLocal->maOtherBlues.push_back( nVal); break; // "OtherBlues"
+ case 8: mpCffLocal->maFamilyBlues.push_back( nVal); break; // "FamilyBlues"
+ case 9: mpCffLocal->maFamilyOtherBlues.push_back( nVal); break;// "FamilyOtherBlues"
+ case 912: mpCffLocal->maStemSnapH.push_back( nVal); break; // "StemSnapH"
+ case 913: mpCffLocal->maStemSnapV.push_back( nVal); break; // "StemSnapV"
+ default: break; // TODO: handle more delta-array dictops?
+ }
+ }
+ clear();
+ } break;
+ case 's': // stringid (SID)
+ nInt = popInt();
+ switch( nOpId ) {
+ case 2: mnFullNameSID = nInt; break; // "FullName"
+ case 3: break; // "FamilyName"
+ case 938: mnFontNameSID = nInt; break; // "FontName"
+ default: break; // TODO: handle more string dictops?
+ }
+ break;
+ case 'P': // private dict
+ mpCffLocal->mnPrivDictBase = popInt();
+ mpCffLocal->mnPrivDictSize = popInt();
+ break;
+ case 'r': { // ROS operands
+ popInt(); // TODO: use sid1
+ popInt(); // TODO: use sid2
+ popVal();
+ mbCIDFont = true;
+ } break;
+ case 't': // CharstringType
+ popInt();
+ break;
+ }
+ } else if( (c >= 32) || (c == 28) ) {
+// --mpReadPtr;
+ read2push();
+ } else if( c == 29 ) { // longint
+ ++mpReadPtr; // skip 29
+ sal_Int32 nS32 = mpReadPtr[0] << 24;
+ nS32 += mpReadPtr[1] << 16;
+ nS32 += mpReadPtr[2] << 8;
+ nS32 += mpReadPtr[3] << 0;
+ mpReadPtr += 4;
+ ValType nVal = static_cast<ValType>(nS32);
+ push( nVal );
+ } else if( c == 30) { // real number
+ ++mpReadPtr; // skip 30
+ const RealType fReal = readRealVal();
+ // push value onto stack
+ ValType nVal = fReal;
+ push( nVal);
+ }
+}
+
+void CffSubsetterContext::read2push()
+{
+ ValType aVal = 0;
+
+ const U8*& p = mpReadPtr;
+ const U8 c = *p;
+ if( c == 28 ) {
+ sal_Int16 nS16 = (p[1] << 8) + p[2];
+ aVal = nS16;
+ p += 3;
+ } else if( c <= 246 ) { // -107..+107
+ aVal = static_cast<ValType>(p[0] - 139);
+ p += 1;
+ } else if( c <= 250 ) { // +108..+1131
+ aVal = static_cast<ValType>(((p[0] << 8) + p[1]) - 63124);
+ p += 2;
+ } else if( c <= 254 ) { // -108..-1131
+ aVal = static_cast<ValType>(64148 - ((p[0] << 8) + p[1]));
+ p += 2;
+ } else /*if( c == 255)*/ { // Fixed16.16
+ int nS32 = (p[1] << 24) + (p[2] << 16) + (p[3] << 8) + p[4];
+ if( (sizeof(nS32) != 2) && (nS32 & (1U<<31)))
+ nS32 |= (~0U) << 31; // assuming 2s complement
+ aVal = static_cast<ValType>(nS32 * (1.0 / 0x10000));
+ p += 5;
+ }
+
+ push( aVal);
+}
+
+void CffSubsetterContext::writeType1Val( ValType aVal)
+{
+ U8* pOut = mpWritePtr;
+
+ // tdf#126242
+ // Type2 has 16.16 fixed numbers, but Type1 does not. To represent values
+ // with fractions we multiply it by a factor then use “div” operator to
+ // divide it back and keep the fractions.
+ // Code Adapted from:
+ // https://github.com/fontforge/fontforge/blob/f152f12e567ea5bd737a2907c318ae26cfaabd08/fontforge/splinesave.c#L378
+ int nDiv = 0;
+ aVal = rint(aVal * 1024) / 1024;
+ if (aVal != floor(aVal))
+ {
+ if (aVal == rint(aVal * 64) / 64)
+ nDiv = 64;
+ else
+ nDiv = 1024;
+ aVal *= nDiv;
+ }
+
+ int nInt = static_cast<int>(rint(aVal));
+ if (nDiv && floor(nInt) / nDiv == floor(nInt / nDiv))
+ {
+ nInt = rint(nInt / nDiv);
+ nDiv = 0;
+ }
+
+ if( (nInt >= -107) && (nInt <= +107)) {
+ *(pOut++) = static_cast<U8>(nInt + 139); // -107..+107
+ } else if( (nInt >= -1131) && (nInt <= +1131)) {
+ if( nInt >= 0)
+ nInt += 63124; // +108..+1131
+ else
+ nInt = 64148 - nInt; // -108..-1131
+ *(pOut++) = static_cast<U8>(nInt >> 8);
+ *(pOut++) = static_cast<U8>(nInt);
+ } else {
+ // numtype==255 means int32 for Type1, but 16.16 for Type2 charstrings!!!
+ *(pOut++) = 255;
+ *(pOut++) = static_cast<U8>(nInt >> 24);
+ *(pOut++) = static_cast<U8>(nInt >> 16);
+ *(pOut++) = static_cast<U8>(nInt >> 8);
+ *(pOut++) = static_cast<U8>(nInt);
+ }
+
+ mpWritePtr = pOut;
+
+ if (nDiv)
+ {
+ writeType1Val(nDiv);
+ writeTypeEsc(TYPE1OP::DIV);
+ }
+}
+
+inline void CffSubsetterContext::writeTypeOp( int nTypeOp)
+{
+ *(mpWritePtr++) = static_cast<U8>(nTypeOp);
+}
+
+inline void CffSubsetterContext::writeTypeEsc( int nTypeEsc)
+{
+ *(mpWritePtr++) = TYPE1OP::T1ESC;
+ *(mpWritePtr++) = static_cast<U8>(nTypeEsc);
+}
+
+void CffSubsetterContext::pop2MultiWrite( int nArgsPerTypo, int nTypeOp, int nTypeXor)
+{
+ for( int i = 0; i < mnStackIdx;) {
+ for( int j = 0; j < nArgsPerTypo; ++j) {
+ const ValType aVal = mnValStack[i+j];
+ writeType1Val( aVal);
+ }
+ i += nArgsPerTypo;
+ writeTypeOp( nTypeOp);
+ nTypeOp ^= nTypeXor; // for toggling vlineto/hlineto
+ }
+ clear();
+}
+
+void CffSubsetterContext::popAll2Write( int nTypeOp)
+{
+ // pop in reverse order, then write
+ for( int i = 0; i < mnStackIdx; ++i) {
+ const ValType aVal = mnValStack[i];
+ writeType1Val( aVal);
+ }
+ clear();
+ writeTypeOp( nTypeOp);
+}
+
+void CffSubsetterContext::writeCurveTo( int nStackPos,
+ int nIX1, int nIY1, int nIX2, int nIY2, int nIX3, int nIY3)
+{
+ // get the values from the stack
+ const ValType nDX1 = nIX1 ? mnValStack[ nStackPos+nIX1 ] : 0;
+ const ValType nDY1 = nIY1 ? mnValStack[ nStackPos+nIY1 ] : 0;
+ const ValType nDX2 = nIX2 ? mnValStack[ nStackPos+nIX2 ] : 0;
+ const ValType nDY2 = nIY2 ? mnValStack[ nStackPos+nIY2 ] : 0;
+ const ValType nDX3 = nIX3 ? mnValStack[ nStackPos+nIX3 ] : 0;
+ const ValType nDY3 = nIY3 ? mnValStack[ nStackPos+nIY3 ] : 0;
+
+ // emit the curveto operator and operands
+ // TODO: determine the most efficient curveto operator
+ // TODO: depending on type1op or type2op target
+ writeType1Val( nDX1 );
+ writeType1Val( nDY1 );
+ writeType1Val( nDX2 );
+ writeType1Val( nDY2 );
+ writeType1Val( nDX3 );
+ writeType1Val( nDY3 );
+ writeTypeOp( TYPE1OP::RCURVETO );
+}
+
+void CffSubsetterContext::convertOneTypeOp()
+{
+ const int nType2Op = *(mpReadPtr++);
+
+ int i, nInt; // prevent WAE for declarations inside switch cases
+ // convert each T2op
+ switch( nType2Op) {
+ case TYPE2OP::T2ESC:
+ convertOneTypeEsc();
+ break;
+ case TYPE2OP::HSTEM:
+ case TYPE2OP::VSTEM:
+ addHints( nType2Op == TYPE2OP::VSTEM );
+ for( i = 0; i < mnHintSize; i+=2 ) {
+ writeType1Val( mnHintStack[i]);
+ writeType1Val( mnHintStack[i+1] - mnHintStack[i]);
+ writeTypeOp( nType2Op );
+ }
+ break;
+ case TYPE2OP::HSTEMHM:
+ case TYPE2OP::VSTEMHM:
+ addHints( nType2Op == TYPE2OP::VSTEMHM);
+ break;
+ case TYPE2OP::CNTRMASK:
+ // TODO: replace cntrmask with vstem3/hstem3
+ addHints( true);
+ {
+ U8 nMaskBit = 0;
+ U8 nMaskByte = 0;
+ for( i = 0; i < mnHintSize; i+=2, nMaskBit>>=1) {
+ if( !nMaskBit) {
+ nMaskByte = *(mpReadPtr++);
+ nMaskBit = 0x80;
+ }
+ if( !(nMaskByte & nMaskBit))
+ continue;
+ if( i >= 8*int(sizeof(mnCntrMask)))
+ mbIgnoreHints = true;
+ if( mbIgnoreHints)
+ continue;
+ mnCntrMask |= (1U << i);
+ }
+ }
+ break;
+ case TYPE2OP::HINTMASK:
+ addHints( true);
+ {
+ sal_Int32 nHintMask = 0;
+ int nCntrBits[2] = {0,0};
+ U8 nMaskBit = 0;
+ U8 nMaskByte = 0;
+ int const MASK_BITS = 8*sizeof(nHintMask);
+ for( i = 0; i < mnHintSize; i+=2, nMaskBit>>=1) {
+ if( !nMaskBit) {
+ nMaskByte = *(mpReadPtr++);
+ nMaskBit = 0x80;
+ }
+ if( !(nMaskByte & nMaskBit))
+ continue;
+ if( i >= MASK_BITS)
+ mbIgnoreHints = true;
+ if( mbIgnoreHints)
+ continue;
+ nHintMask |= (1U << i);
+ nCntrBits[ i < mnHorzHintSize] += (mnCntrMask >> i) & 1;
+ }
+
+ mbIgnoreHints |= (nCntrBits[0] && (nCntrBits[0] != 3));
+ mbIgnoreHints |= (nCntrBits[1] && (nCntrBits[1] != 3));
+ if( mbIgnoreHints)
+ break;
+
+ for( i = 0; i < mnHintSize; i+=2) {
+ if(i >= MASK_BITS || !(nHintMask & (1U << i)))
+ continue;
+ writeType1Val( mnHintStack[i]);
+ writeType1Val( mnHintStack[i+1] - mnHintStack[i]);
+ const bool bHorz = (i < mnHorzHintSize);
+ if( !nCntrBits[ bHorz])
+ writeTypeOp( bHorz ? TYPE1OP::HSTEM : TYPE1OP::VSTEM);
+ else if( !--nCntrBits[ bHorz])
+ writeTypeEsc( bHorz ? TYPE1OP::HSTEM3 : TYPE1OP::VSTEM3);
+ }
+ }
+ break;
+ case TYPE2OP::CALLSUBR:
+ case TYPE2OP::CALLGSUBR:
+ {
+ nInt = popInt();
+ const bool bGlobal = (nType2Op == TYPE2OP::CALLGSUBR);
+ callType2Subr( bGlobal, nInt);
+ }
+ break;
+ case TYPE2OP::RETURN:
+ // TODO: check that we are in a subroutine
+ return;
+ case TYPE2OP::VMOVETO:
+ case TYPE2OP::HMOVETO:
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() > 1);
+ mbNeedClose = true;
+ pop2MultiWrite( 1, nType2Op);
+ break;
+ case TYPE2OP::VLINETO:
+ case TYPE2OP::HLINETO:
+ pop2MultiWrite( 1, nType2Op,
+ TYPE1OP::VLINETO ^ TYPE1OP::HLINETO);
+ break;
+ case TYPE2OP::RMOVETO:
+ // TODO: convert rmoveto to vlineto/hlineto if possible
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() > 2);
+ mbNeedClose = true;
+ pop2MultiWrite( 2, nType2Op);
+ break;
+ case TYPE2OP::RLINETO:
+ // TODO: convert rlineto to vlineto/hlineto if possible
+ pop2MultiWrite( 2, nType2Op);
+ break;
+ case TYPE2OP::RCURVETO:
+ // TODO: convert rcurveto to vh/hv/hh/vv-curveto if possible
+ pop2MultiWrite( 6, nType2Op);
+ break;
+ case TYPE2OP::RCURVELINE:
+ i = 0;
+ while( (i += 6) <= mnStackIdx)
+ writeCurveTo( i, -6, -5, -4, -3, -2, -1 );
+ i -= 6;
+ while( (i += 2) <= mnStackIdx) {
+ writeType1Val( mnValStack[i-2]);
+ writeType1Val( mnValStack[i-1]);
+ writeTypeOp( TYPE2OP::RLINETO);
+ }
+ clear();
+ break;
+ case TYPE2OP::RLINECURVE:
+ i = 0;
+ while( (i += 2) <= mnStackIdx-6) {
+ writeType1Val( mnValStack[i-2]);
+ writeType1Val( mnValStack[i-1]);
+ writeTypeOp( TYPE2OP::RLINETO);
+ }
+ i -= 2;
+ while( (i += 6) <= mnStackIdx)
+ writeCurveTo( i, -6, -5, -4, -3, -2, -1 );
+ clear();
+ break;
+ case TYPE2OP::VHCURVETO:
+ case TYPE2OP::HVCURVETO:
+ {
+ bool bVert = (nType2Op == TYPE2OP::VHCURVETO);
+ i = 0;
+ nInt = 0;
+ if( mnStackIdx & 1 )
+ nInt = static_cast<int>(mnValStack[ --mnStackIdx ]);
+ while( (i += 4) <= mnStackIdx) {
+ // TODO: use writeCurveTo()
+ if( bVert ) writeType1Val( 0 );
+ writeType1Val( mnValStack[i-4] );
+ if( !bVert ) writeType1Val( 0);
+ writeType1Val( mnValStack[i-3] );
+ writeType1Val( mnValStack[i-2] );
+ if( !bVert ) writeType1Val( static_cast<ValType>((i==mnStackIdx) ? nInt : 0) );
+ writeType1Val( mnValStack[i-1] );
+ if( bVert ) writeType1Val( static_cast<ValType>((i==mnStackIdx) ? nInt : 0) );
+ bVert = !bVert;
+ writeTypeOp( TYPE2OP::RCURVETO);
+ }
+ }
+ clear();
+ break;
+ case TYPE2OP::HHCURVETO:
+ i = (mnStackIdx & 1);
+ while( (i += 4) <= mnStackIdx) {
+ if( i != 5)
+ writeCurveTo( i, -4, 0, -3, -2, -1, 0);
+ else
+ writeCurveTo( i, -4, -5, -3, -2, -1, 0);
+ }
+ clear();
+ break;
+ case TYPE2OP::VVCURVETO:
+ i = (mnStackIdx & 1);
+ while( (i += 4) <= mnStackIdx) {
+ if( i != 5)
+ writeCurveTo( i, 0, -4, -3, -2, 0, -1);
+ else
+ writeCurveTo( i, -5, -4, -3, -2, 0, -1);
+ }
+ clear();
+ break;
+ case TYPE2OP::ENDCHAR:
+ if (size() >= 4 && mbDoSeac)
+ {
+ // Deprecated seac-like use of endchar (Adobe Technical Note #5177,
+ // Appendix C).
+ auto achar = popVal();
+ auto bchar = popVal();
+ auto ady = popVal();
+ auto adx = popVal();
+ int nBase = {}, nAccent = {};
+ if (getBaseAccent(bchar, achar, &nBase, &nAccent))
+ {
+ maExtraGlyphIds.push_back(nBase);
+ maExtraGlyphIds.push_back(nAccent);
+ writeType1Val(0); // TODO accent sb
+ writeType1Val(adx);
+ writeType1Val(ady);
+ writeType1Val(bchar);
+ writeType1Val(achar);
+ writeTypeEsc(TYPE1OP::SEAC);
+ }
+ }
+ if( mbNeedClose)
+ writeTypeOp( TYPE1OP::CLOSEPATH);
+ else
+ updateWidth( size() >= 1);
+ // mbNeedClose = true;
+ writeTypeOp( TYPE1OP::ENDCHAR);
+ break;
+ default:
+ if( ((nType2Op >= 32) && (nType2Op <= 255)) || (nType2Op == 28)) {
+ --mpReadPtr;
+ read2push();
+ } else {
+ popAll2Write( nType2Op);
+ assert(false && "TODO?");
+ }
+ break;
+ }
+}
+
+void CffSubsetterContext::convertOneTypeEsc()
+{
+ const int nType2Esc = *(mpReadPtr++);
+ ValType* pTop = &mnValStack[ mnStackIdx-1];
+ // convert each T2op
+ switch( nType2Esc) {
+ case TYPE2OP::AND:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = static_cast<ValType>(static_cast<int>(pTop[0]) & static_cast<int>(pTop[-1]));
+ --mnStackIdx;
+ break;
+ case TYPE2OP::OR:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = static_cast<ValType>(static_cast<int>(pTop[0]) | static_cast<int>(pTop[-1]));
+ --mnStackIdx;
+ break;
+ case TYPE2OP::NOT:
+ assert( mnStackIdx >= 1 );
+ pTop[0] = ValType(pTop[0] == 0);
+ break;
+ case TYPE2OP::ABS:
+ assert( mnStackIdx >= 1 );
+ if( pTop[0] >= 0)
+ break;
+ [[fallthrough]];
+ case TYPE2OP::NEG:
+ assert( mnStackIdx >= 1 );
+ pTop[0] = -pTop[0];
+ break;
+ case TYPE2OP::ADD:
+ assert( mnStackIdx >= 2 );
+ pTop[0] += pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::SUB:
+ assert( mnStackIdx >= 2 );
+ pTop[0] -= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::MUL:
+ assert( mnStackIdx >= 2 );
+ if( pTop[-1])
+ pTop[0] *= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::DIV:
+ assert( mnStackIdx >= 2 );
+ if( pTop[-1])
+ pTop[0] /= pTop[-1];
+ --mnStackIdx;
+ break;
+ case TYPE2OP::EQ:
+ assert( mnStackIdx >= 2 );
+ pTop[0] = ValType(pTop[0] == pTop[-1]);
+ --mnStackIdx;
+ break;
+ case TYPE2OP::DROP:
+ assert( mnStackIdx >= 1 );
+ --mnStackIdx;
+ break;
+ case TYPE2OP::PUT: {
+ assert( mnStackIdx >= 2 );
+ const int nIdx = static_cast<int>(pTop[0]);
+ assert( nIdx >= 0 );
+ assert( nIdx < NMAXTRANS );
+ mnTransVals[ nIdx] = pTop[-1];
+ mnStackIdx -= 2;
+ break;
+ }
+ case TYPE2OP::GET: {
+ assert( mnStackIdx >= 1 );
+ const int nIdx = static_cast<int>(pTop[0]);
+ assert( nIdx >= 0 );
+ assert( nIdx < NMAXTRANS );
+ pTop[0] = mnTransVals[ nIdx ];
+ break;
+ }
+ case TYPE2OP::IFELSE: {
+ assert( mnStackIdx >= 4 );
+ if( pTop[-1] > pTop[0] )
+ pTop[-3] = pTop[-2];
+ mnStackIdx -= 3;
+ break;
+ }
+ case TYPE2OP::RANDOM:
+ pTop[+1] = 1234; // TODO
+ ++mnStackIdx;
+ break;
+ case TYPE2OP::SQRT:
+ // TODO: implement
+ break;
+ case TYPE2OP::DUP:
+ assert( mnStackIdx >= 1 );
+ pTop[+1] = pTop[0];
+ ++mnStackIdx;
+ break;
+ case TYPE2OP::EXCH: {
+ assert( mnStackIdx >= 2 );
+ const ValType nVal = pTop[0];
+ pTop[0] = pTop[-1];
+ pTop[-1] = nVal;
+ break;
+ }
+ case TYPE2OP::INDEX: {
+ assert( mnStackIdx >= 1 );
+ const int nVal = static_cast<int>(pTop[0]);
+ assert( nVal >= 0 );
+ assert( nVal < mnStackIdx-1 );
+ pTop[0] = pTop[-1-nVal];
+ break;
+ }
+ case TYPE2OP::ROLL: {
+ assert( mnStackIdx >= 1 );
+ const int nNum = static_cast<int>(pTop[0]);
+ assert( nNum >= 0);
+ assert( nNum < mnStackIdx-2 );
+ (void)nNum; // TODO: implement
+ // TODO: implement: const int nOfs = static_cast<int>(pTop[-1]);
+ mnStackIdx -= 2;
+ break;
+ }
+ case TYPE2OP::HFLEX1: {
+ assert( mnStackIdx == 9);
+
+ writeCurveTo( mnStackIdx, -9, -8, -7, -6, -5, 0);
+ writeCurveTo( mnStackIdx, -4, 0, -3, -2, -1, 0);
+ // TODO: emulate hflex1 using othersubr call
+
+ mnStackIdx -= 9;
+ }
+ break;
+ case TYPE2OP::HFLEX: {
+ assert( mnStackIdx == 7);
+ ValType* pX = &mnValStack[ mnStackIdx];
+
+ pX[+1] = -pX[-5]; // temp: +dy5==-dy2
+ writeCurveTo( mnStackIdx, -7, 0, -6, -5, -4, 0);
+ writeCurveTo( mnStackIdx, -3, 0, -2, +1, -1, 0);
+ // TODO: emulate hflex using othersubr call
+
+ mnStackIdx -= 7;
+ }
+ break;
+ case TYPE2OP::FLEX: {
+ assert( mnStackIdx == 13 );
+ writeCurveTo( mnStackIdx, -13, -12, -11, -10, -9, -8 );
+ writeCurveTo( mnStackIdx, -7, -6, -5, -4, -3, -2 );
+ // ignoring ValType nFlexDepth = mnValStack[ mnStackIdx-1 ];
+ mnStackIdx -= 13;
+ }
+ break;
+ case TYPE2OP::FLEX1: {
+ assert( mnStackIdx == 11 );
+ // write the first part of the flex1-hinted curve
+ writeCurveTo( mnStackIdx, -11, -10, -9, -8, -7, -6 );
+
+ // determine if nD6 is horizontal or vertical
+ const int i = mnStackIdx;
+ ValType nDeltaX = mnValStack[i-11] + mnValStack[i-9] + mnValStack[i-7] + mnValStack[i-5] + mnValStack[i-3];
+ if( nDeltaX < 0 ) nDeltaX = -nDeltaX;
+ ValType nDeltaY = mnValStack[i-10] + mnValStack[i-8] + mnValStack[i-6] + mnValStack[i-4] + mnValStack[i-2];
+ if( nDeltaY < 0 ) nDeltaY = -nDeltaY;
+ const bool bVertD6 = (nDeltaY > nDeltaX);
+
+ // write the second part of the flex1-hinted curve
+ if( !bVertD6 )
+ writeCurveTo( mnStackIdx, -5, -4, -3, -2, -1, 0);
+ else
+ writeCurveTo( mnStackIdx, -5, -4, -3, -2, 0, -1);
+ mnStackIdx -= 11;
+ }
+ break;
+ default:
+ SAL_WARN("vcl.fonts", "unhandled type2esc " << nType2Esc);
+ assert( false);
+ break;
+ }
+}
+
+void CffSubsetterContext::callType2Subr( bool bGlobal, int nSubrNumber)
+{
+ const U8* const pOldReadPtr = mpReadPtr;
+ const U8* const pOldReadEnd = mpReadEnd;
+
+ if( bGlobal ) {
+ nSubrNumber += mnGlobalSubrBias;
+ seekIndexData( mnGlobalSubrBase, nSubrNumber);
+ } else {
+ nSubrNumber += mpCffLocal->mnLocalSubrBias;
+ seekIndexData( mpCffLocal->mnLocalSubrBase, nSubrNumber);
+ }
+
+ while( mpReadPtr < mpReadEnd)
+ convertOneTypeOp();
+
+ mpReadPtr = pOldReadPtr;
+ mpReadEnd = pOldReadEnd;
+}
+
+int CffSubsetterContext::convert2Type1Ops( CffLocal* pCffLocal, const U8* const pT2Ops, int nT2Len, U8* const pT1Ops)
+{
+ mpCffLocal = pCffLocal;
+
+ // prepare the charstring conversion
+ mpWritePtr = pT1Ops;
+ U8 aType1Ops[ MAX_T1OPS_SIZE];
+ if( !pT1Ops)
+ mpWritePtr = aType1Ops;
+ *const_cast<U8**>(&pT1Ops) = mpWritePtr;
+
+ // prepend random seed for T1crypt
+ *(mpWritePtr++) = 0x48;
+ *(mpWritePtr++) = 0x44;
+ *(mpWritePtr++) = 0x55;
+ *(mpWritePtr++) = ' ';
+
+ // convert the Type2 charstring to Type1
+ mpReadPtr = pT2Ops;
+ mpReadEnd = pT2Ops + nT2Len;
+ // prepend "hsbw" or "sbw"
+ // TODO: only emit hsbw when charwidth is known
+ writeType1Val(0); // TODO: aSubsetterContext.getLeftSideBearing();
+ U8* pCharWidthPtr=mpWritePtr; // need to overwrite that later
+ // pad out 5 bytes for the char width with default val 1000 (to be
+ // filled with the actual value below)
+ *(mpWritePtr++) = 255;
+ *(mpWritePtr++) = static_cast<U8>(0);
+ *(mpWritePtr++) = static_cast<U8>(0);
+ *(mpWritePtr++) = static_cast<U8>(250);
+ *(mpWritePtr++) = static_cast<U8>(124);
+ writeTypeOp(TYPE1OP::HSBW);
+ mbNeedClose = false;
+ mbIgnoreHints = false;
+ mnHintSize=mnHorzHintSize=mnStackIdx=0; maCharWidth=-1;//#######
+ mnCntrMask = 0;
+ while( mpReadPtr < mpReadEnd)
+ convertOneTypeOp();
+ if( maCharWidth != -1 )
+ {
+ // overwrite earlier charWidth value, which we only now have
+ // parsed out of mpReadPtr buffer (by way of
+ // convertOneTypeOp()s above)
+ const int nInt = static_cast<int>(maCharWidth);
+ *(pCharWidthPtr++) = 255;
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 24);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 16);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt >> 8);
+ *(pCharWidthPtr++) = static_cast<U8>(nInt);
+ }
+
+ const int nType1Len = mpWritePtr - pT1Ops;
+
+ // encrypt the Type1 charstring
+ unsigned nRDCryptR = 4330; // TODO: mnRDCryptSeed;
+ for( U8* p = pT1Ops; p < mpWritePtr; ++p) {
+ *p ^= (nRDCryptR >> 8);
+ nRDCryptR = (*p + nRDCryptR) * 52845 + 22719;
+ }
+
+ return nType1Len;
+}
+
+RealType CffSubsetterContext::readRealVal()
+{
+ // TODO: more thorough number validity test
+ bool bComma = false;
+ int nExpVal = 0;
+ int nExpSign = 0;
+ S64 nNumber = 0;
+ RealType fReal = +1.0;
+ for(;;){
+ const U8 c = *(mpReadPtr++); // read nibbles
+ // parse high nibble
+ const U8 nH = c >> 4U;
+ if( nH <= 9) {
+ nNumber = nNumber * 10 + nH;
+ --nExpVal;
+ } else if( nH == 10) { // comma
+ nExpVal = 0;
+ bComma = true;
+ } else if( nH == 11) { // +exp
+ fReal *= nNumber;
+ nExpSign = +1;
+ nNumber = 0;
+ } else if( nH == 12) { // -exp
+ fReal *= nNumber;
+ nExpSign = -1;
+ nNumber = 0;
+ } else if( nH == 13) { // reserved
+ // TODO: ignore or error?
+ } else if( nH == 14) // minus
+ fReal = -fReal;
+ else if( nH == 15) // end
+ break;
+ // parse low nibble
+ const U8 nL = c & 0x0F;
+ if( nL <= 9) {
+ nNumber = nNumber * 10 + nL;
+ --nExpVal;
+ } else if( nL == 10) { // comma
+ nExpVal = 0;
+ bComma = true;
+ } else if( nL == 11) { // +exp
+ fReal *= nNumber;
+ nNumber = 0;
+ nExpSign = +1;
+ } else if( nL == 12) { // -exp
+ fReal *= nNumber;
+ nNumber = 0;
+ nExpSign = -1;
+ } else if( nL == 13) { // reserved
+ // TODO: ignore or error?
+ } else if( nL == 14) // minus
+ fReal = -fReal;
+ else if( nL == 15) // end
+ break;
+ }
+
+ // merge exponents
+ if( !bComma)
+ nExpVal = 0;
+ if( !nExpSign) { fReal *= nNumber;}
+ else if( nExpSign > 0) { nExpVal += static_cast<int>(nNumber);}
+ else if( nExpSign < 0) { nExpVal -= static_cast<int>(nNumber);}
+
+ // apply exponents
+ if( !nExpVal) { /*nothing to apply*/}
+ else if( nExpVal > 0) { while( --nExpVal >= 0) fReal *= 10.0;}
+ else if( nExpVal < 0) { while( ++nExpVal <= 0) fReal /= 10.0;}
+ return fReal;
+}
+
+// prepare to access an element inside a CFF/CID index table
+int CffSubsetterContext::seekIndexData( int nIndexBase, int nDataIndex)
+{
+ assert( (nIndexBase > 0) && (mpBasePtr + nIndexBase + 3 <= mpBaseEnd));
+ if( nDataIndex < 0)
+ return -1;
+ mpReadPtr = mpBasePtr + nIndexBase;
+ const int nDataCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if( nDataIndex >= nDataCount)
+ return -1;
+ const int nDataOfsSz = mpReadPtr[2];
+ mpReadPtr += 3 + (nDataOfsSz * nDataIndex);
+ int nOfs1 = 0;
+ switch( nDataOfsSz) {
+ default: SAL_WARN("vcl.fonts", "\tINVALID nDataOfsSz=" << nDataOfsSz); return -1;
+ case 1: nOfs1 = mpReadPtr[0]; break;
+ case 2: nOfs1 = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nOfs1 = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2]; break;
+ case 4: nOfs1 = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+ mpReadPtr += nDataOfsSz;
+
+ int nOfs2 = 0;
+ switch( nDataOfsSz) {
+ case 1: nOfs2 = mpReadPtr[0]; break;
+ case 2: nOfs2 = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nOfs2 = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2]; break;
+ case 4: nOfs2 = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+
+ mpReadPtr = mpBasePtr + (nIndexBase + 2) + nDataOfsSz * (nDataCount + 1) + nOfs1;
+ mpReadEnd = mpReadPtr + (nOfs2 - nOfs1);
+ assert( nOfs1 >= 0);
+ assert( nOfs2 >= nOfs1);
+ assert( mpReadPtr <= mpBaseEnd);
+ assert( mpReadEnd <= mpBaseEnd);
+ return (nOfs2 - nOfs1);
+}
+
+// skip over a CFF/CID index table
+void CffSubsetterContext::seekIndexEnd( int nIndexBase)
+{
+ assert( (nIndexBase > 0) && (mpBasePtr + nIndexBase + 3 <= mpBaseEnd));
+ mpReadPtr = mpBasePtr + nIndexBase;
+ const int nDataCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ const int nDataOfsSz = mpReadPtr[2];
+ mpReadPtr += 3 + nDataOfsSz * nDataCount;
+ assert( mpReadPtr <= mpBaseEnd);
+ int nEndOfs = 0;
+ switch( nDataOfsSz) {
+ default: SAL_WARN("vcl.fonts", "\tINVALID nDataOfsSz=" << nDataOfsSz); return;
+ case 1: nEndOfs = mpReadPtr[0]; break;
+ case 2: nEndOfs = (mpReadPtr[0]<<8) + mpReadPtr[1]; break;
+ case 3: nEndOfs = (mpReadPtr[0]<<16) + (mpReadPtr[1]<<8) + mpReadPtr[2];break;
+ case 4: nEndOfs = (mpReadPtr[0]<<24) + (mpReadPtr[1]<<16) + (mpReadPtr[2]<<8) + mpReadPtr[3]; break;
+ }
+ mpReadPtr += nDataOfsSz;
+ mpReadPtr += nEndOfs - 1;
+ mpReadEnd = mpBaseEnd;
+ assert( nEndOfs >= 0);
+ assert( mpReadEnd <= mpBaseEnd);
+}
+
+// initialize FONTDICT specific values
+CffLocal::CffLocal()
+: mnPrivDictBase( 0)
+, mnPrivDictSize( 0)
+, mnLocalSubrOffs( 0)
+, mnLocalSubrBase( 0)
+, mnLocalSubrBias( 0)
+, maNominalWidth( 0)
+, maDefaultWidth( 0)
+, maStemStdHW( 0)
+, maStemStdVW( 0)
+, mfBlueScale( 0.0)
+, mfBlueShift( 0.0)
+, mfBlueFuzz( 0.0)
+, mfExpFactor( 0.0)
+, mnLangGroup( 0)
+, mbForceBold( false)
+{
+}
+
+CffGlobal::CffGlobal()
+: mnNameIdxBase( 0)
+, mnStringIdxBase( 0)
+, mbCIDFont( false)
+, mnCharStrBase( 0)
+, mnCharStrCount( 0)
+, mnCharsetBase( 0)
+, mnGlobalSubrBase( 0)
+, mnGlobalSubrCount( 0)
+, mnGlobalSubrBias( 0)
+, mnFDSelectBase( 0)
+, mnFontDictBase( 0)
+, mnFDAryCount( 1)
+, mnFontNameSID( 0)
+, mnFullNameSID( 0)
+{
+}
+
+bool CffSubsetterContext::initialCffRead()
+{
+ // get the CFFHeader
+ mpReadPtr = mpBasePtr;
+ const U8 nVerMajor = *(mpReadPtr++);
+ const U8 nVerMinor = *(mpReadPtr++);
+ const U8 nHeaderSize = *(mpReadPtr++);
+ const U8 nOffsetSize = *(mpReadPtr++);
+ // TODO: is the version number useful for anything else?
+ assert( (nVerMajor == 1) && (nVerMinor == 0));
+ (void)(nVerMajor + nVerMinor + nOffsetSize); // avoid compiler warnings
+
+ // prepare access to the NameIndex
+ mnNameIdxBase = nHeaderSize;
+ mpReadPtr = mpBasePtr + nHeaderSize;
+ seekIndexEnd( mnNameIdxBase);
+
+ // get the TopDict index
+ const sal_Int32 nTopDictBase = getReadOfs();
+ const int nTopDictCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if( nTopDictCount) {
+ for( int i = 0; i < nTopDictCount; ++i) {
+ seekIndexData( nTopDictBase, i);
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ assert( mpReadPtr == mpReadEnd);
+ }
+ }
+
+ // prepare access to the String index
+ mnStringIdxBase = getReadOfs();
+ seekIndexEnd( mnStringIdxBase);
+
+ // prepare access to the GlobalSubr index
+ mnGlobalSubrBase = getReadOfs();
+ mnGlobalSubrCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ mnGlobalSubrBias = (mnGlobalSubrCount<1240)?107:(mnGlobalSubrCount<33900)?1131:32768;
+ // skip past the last GlobalSubr entry
+// seekIndexEnd( mnGlobalSubrBase);
+
+ // get/skip the Encodings (we got mnEncodingBase from TOPDICT)
+// seekEncodingsEnd( mnEncodingBase);
+ // get/skip the Charsets (we got mnCharsetBase from TOPDICT)
+// seekCharsetsEnd( mnCharStrBase);
+ // get/skip FDSelect (CID only) data
+
+ // prepare access to the CharStrings index (we got the base from TOPDICT)
+ mpReadPtr = mpBasePtr + mnCharStrBase;
+ mnCharStrCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+// seekIndexEnd( mnCharStrBase);
+
+ // read the FDArray index (CID only)
+ if( mbCIDFont) {
+// assert( mnFontDictBase == tellRel());
+ mpReadPtr = mpBasePtr + mnFontDictBase;
+ mnFDAryCount = (mpReadPtr[0]<<8) + mpReadPtr[1];
+ if (o3tl::make_unsigned(mnFDAryCount) >= SAL_N_ELEMENTS(maCffLocal))
+ {
+ SAL_INFO("vcl.fonts", "CffSubsetterContext: too many CFF in font");
+ return false;
+ }
+
+ // read FDArray details to get access to the PRIVDICTs
+ for( int i = 0; i < mnFDAryCount; ++i) {
+ mpCffLocal = &maCffLocal[i];
+ seekIndexData( mnFontDictBase, i);
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ assert( mpReadPtr == mpReadEnd);
+ }
+ }
+
+ for( int i = 0; i < mnFDAryCount; ++i) {
+ mpCffLocal = &maCffLocal[i];
+
+ // get the PrivateDict index
+ // (we got mnPrivDictSize and mnPrivDictBase from TOPDICT or FDArray)
+ if( mpCffLocal->mnPrivDictSize != 0) {
+ assert( mpCffLocal->mnPrivDictSize > 0);
+ // get the PrivDict data
+ mpReadPtr = mpBasePtr + mpCffLocal->mnPrivDictBase;
+ mpReadEnd = mpReadPtr + mpCffLocal->mnPrivDictSize;
+ assert( mpReadEnd <= mpBaseEnd);
+ // read PrivDict details
+ while( mpReadPtr < mpReadEnd)
+ readDictOp();
+ }
+
+ // prepare access to the LocalSubrs (we got mnLocalSubrOffs from PRIVDICT)
+ if( mpCffLocal->mnLocalSubrOffs) {
+ // read LocalSubrs summary
+ mpCffLocal->mnLocalSubrBase = mpCffLocal->mnPrivDictBase + mpCffLocal->mnLocalSubrOffs;
+ mpReadPtr = mpBasePtr + mpCffLocal->mnLocalSubrBase;
+ const int nSubrCount = (mpReadPtr[0] << 8) + mpReadPtr[1];
+ mpCffLocal->mnLocalSubrBias = (nSubrCount<1240)?107:(nSubrCount<33900)?1131:32768;
+// seekIndexEnd( mpCffLocal->mnLocalSubrBase);
+ }
+ }
+
+ // ignore the Notices info
+
+ return true;
+}
+
+// get a cstring from a StringID
+OString CffSubsetterContext::getString( int nStringID)
+{
+ // get a standard string if possible
+ const static int nStdStrings = SAL_N_ELEMENTS(pStringIds);
+ if( (nStringID >= 0) && (nStringID < nStdStrings))
+ return pStringIds[ nStringID];
+
+ // else get the string from the StringIndex table
+ comphelper::ValueRestorationGuard pReadPtr(mpReadPtr);
+ comphelper::ValueRestorationGuard pReadEnd(mpReadEnd);
+ nStringID -= nStdStrings;
+ int nLen = seekIndexData( mnStringIdxBase, nStringID);
+ // assert( nLen >= 0);
+ // TODO: just return the undecorated name
+ if( nLen < 0) {
+ return "name[" + OString::number(nStringID) + "].notfound!";
+ } else {
+ const int nMaxLen = 2560 - 1;
+ if( nLen >= nMaxLen)
+ nLen = nMaxLen; // TODO: still needed?
+ return OString(reinterpret_cast<char const *>(mpReadPtr), nLen);
+ }
+}
+
+// access a CID's FDSelect table
+int CffSubsetterContext::getFDSelect( int nGlyphIndex) const
+{
+ assert( nGlyphIndex >= 0);
+ assert( nGlyphIndex < mnCharStrCount);
+ if( !mbCIDFont)
+ return 0;
+
+ const U8* pReadPtr = mpBasePtr + mnFDSelectBase;
+ const U8 nFDSelFormat = *(pReadPtr++);
+ switch( nFDSelFormat) {
+ case 0: { // FDSELECT format 0
+ pReadPtr += nGlyphIndex;
+ const U8 nFDIdx = *(pReadPtr++);
+ return nFDIdx;
+ } //break;
+ case 3: { // FDSELECT format 3
+ const U16 nRangeCount = (pReadPtr[0]<<8) + pReadPtr[1];
+ assert( nRangeCount > 0);
+ assert( nRangeCount <= mnCharStrCount);
+ U16 nPrev = (pReadPtr[2]<<8) + pReadPtr[3];
+ assert( nPrev == 0);
+ (void)nPrev;
+ pReadPtr += 4;
+ // TODO? binary search
+ for( int i = 0; i < nRangeCount; ++i) {
+ const U8 nFDIdx = pReadPtr[0];
+ const U16 nNext = (pReadPtr[1]<<8) + pReadPtr[2];
+ assert( nPrev < nNext);
+ if( nGlyphIndex < nNext)
+ return nFDIdx;
+ pReadPtr += 3;
+ nPrev = nNext;
+ }
+ } break;
+ default: // invalid FDselect format
+ SAL_WARN("vcl.fonts", "invalid CFF.FdselType=" << nFDSelFormat);
+ break;
+ }
+
+ assert( false);
+ return -1;
+}
+
+int CffSubsetterContext::getGlyphSID( int nGlyphIndex) const
+{
+ if( nGlyphIndex == 0)
+ return 0; // ".notdef"
+ assert( nGlyphIndex >= 0);
+ assert( nGlyphIndex < mnCharStrCount);
+ if( (nGlyphIndex < 0) || (nGlyphIndex >= mnCharStrCount))
+ return -1;
+
+ // get the SID/CID from the Charset table
+ const U8* pReadPtr = mpBasePtr + mnCharsetBase;
+ const U8 nCSetFormat = *(pReadPtr++);
+ int nGlyphsToSkip = nGlyphIndex - 1;
+ switch( nCSetFormat) {
+ case 0: // charset format 0
+ pReadPtr += 2 * nGlyphsToSkip;
+ nGlyphsToSkip = 0;
+ break;
+ case 1: // charset format 1
+ while( nGlyphsToSkip >= 0) {
+ const int nLeft = pReadPtr[2];
+ if( nGlyphsToSkip <= nLeft)
+ break;
+ nGlyphsToSkip -= nLeft + 1;
+ pReadPtr += 3;
+ }
+ break;
+ case 2: // charset format 2
+ while( nGlyphsToSkip >= 0) {
+ const int nLeft = (pReadPtr[2]<<8) + pReadPtr[3];
+ if( nGlyphsToSkip <= nLeft)
+ break;
+ nGlyphsToSkip -= nLeft + 1;
+ pReadPtr += 4;
+ }
+ break;
+ default:
+ SAL_WARN("vcl.fonts", "ILLEGAL CFF-Charset format " << nCSetFormat);
+ return -2;
+ }
+
+ int nSID = (pReadPtr[0]<<8) + pReadPtr[1];
+ nSID += nGlyphsToSkip;
+ // NOTE: for CID-fonts the resulting SID is interpreted as CID
+ return nSID;
+}
+
+// NOTE: the result becomes invalid with the next call to this method
+OString CffSubsetterContext::getGlyphName( int nGlyphIndex)
+{
+ // the first glyph is always the .notdef glyph
+ if( nGlyphIndex == 0)
+ return tok_notdef;
+
+ // get the glyph specific name
+ const int nSID = getGlyphSID( nGlyphIndex);
+ if( nSID < 0) // default glyph name
+ {
+ char aDefaultGlyphName[64];
+ o3tl::sprintf( aDefaultGlyphName, "gly%03d", nGlyphIndex);
+ return aDefaultGlyphName;
+ }
+ else if( mbCIDFont) // default glyph name in CIDs
+ {
+ char aDefaultGlyphName[64];
+ o3tl::sprintf( aDefaultGlyphName, "cid%03d", nSID);
+ return aDefaultGlyphName;
+ }
+ else { // glyph name from string table
+ auto const pSidName = getString( nSID);
+ // check validity of glyph name
+ const char* p = pSidName.getStr();
+ while( (*p >= '0') && (*p <= 'z')) ++p;
+ if( (p >= pSidName.getStr()+1) && (*p == '\0'))
+ return pSidName;
+ // if needed invent a fallback name
+ char aDefaultGlyphName[64];
+ o3tl::sprintf( aDefaultGlyphName, "bad%03d", nSID);
+ return aDefaultGlyphName;
+ }
+}
+
+bool CffSubsetterContext::getBaseAccent(ValType aBase, ValType aAccent, int* nBase, int* nAccent)
+{
+ bool bBase = false, bAccent = false;
+ for (int i = 0; i < mnCharStrCount; i++)
+ {
+ OString pGlyphName = getGlyphName(i);
+ if (pGlyphName == pStandardEncoding[int(aBase)])
+ {
+ *nBase = i;
+ bBase = true;
+ }
+ if (pGlyphName == pStandardEncoding[int(aAccent)])
+ {
+ *nAccent = i;
+ bAccent = true;
+ }
+ if (bBase && bAccent)
+ return true;
+ }
+ return false;
+}
+
+namespace {
+
+class Type1Emitter
+{
+public:
+ explicit Type1Emitter( SvStream* pOutFile, bool bPfbSubset);
+ ~Type1Emitter();
+ void setSubsetName( const char* );
+
+ size_t emitRawData( const char* pData, size_t nLength) const;
+ void emitAllRaw();
+ void emitAllHex();
+ void emitAllCrypted();
+ int tellPos() const;
+ void updateLen( int nTellPos, size_t nLength);
+ void emitValVector( const char* pLineHead, const char* pLineTail, const std::vector<ValType>&);
+private:
+ SvStream* mpFileOut;
+ unsigned mnEECryptR;
+public:
+ OStringBuffer maBuffer;
+
+ char maSubsetName[256];
+ bool mbPfbSubset;
+ int mnHexLineCol;
+};
+
+}
+
+Type1Emitter::Type1Emitter( SvStream* pOutFile, bool bPfbSubset)
+: mpFileOut( pOutFile)
+, mnEECryptR( 55665) // default eexec seed, TODO: mnEECryptSeed
+, mbPfbSubset( bPfbSubset)
+, mnHexLineCol( 0)
+{
+ maSubsetName[0] = '\0';
+}
+
+Type1Emitter::~Type1Emitter()
+{
+ if( !mpFileOut)
+ return;
+ mpFileOut = nullptr;
+}
+
+void Type1Emitter::setSubsetName( const char* pSubsetName)
+{
+ maSubsetName[0] = '\0';
+ if( pSubsetName)
+ strncpy( maSubsetName, pSubsetName, sizeof(maSubsetName) - 1);
+ maSubsetName[sizeof(maSubsetName)-1] = '\0';
+}
+
+int Type1Emitter::tellPos() const
+{
+ int nTellPos = mpFileOut->Tell();
+ return nTellPos;
+}
+
+void Type1Emitter::updateLen( int nTellPos, size_t nLength)
+{
+ // update PFB segment header length
+ U8 cData[4];
+ cData[0] = static_cast<U8>(nLength >> 0);
+ cData[1] = static_cast<U8>(nLength >> 8);
+ cData[2] = static_cast<U8>(nLength >> 16);
+ cData[3] = static_cast<U8>(nLength >> 24);
+ const tools::Long nCurrPos = mpFileOut->Tell();
+ if (nCurrPos < 0)
+ return;
+ if (mpFileOut->Seek(nTellPos) != static_cast<sal_uInt64>(nTellPos))
+ return;
+ mpFileOut->WriteBytes(cData, sizeof(cData));
+ mpFileOut->Seek(nCurrPos);
+}
+
+inline size_t Type1Emitter::emitRawData(const char* pData, size_t nLength) const
+{
+ return mpFileOut->WriteBytes( pData, nLength );
+}
+
+inline void Type1Emitter::emitAllRaw()
+{
+ // writeout raw data
+ emitRawData( maBuffer.getStr(), maBuffer.getLength());
+ // reset the raw buffer
+ maBuffer.setLength(0);
+}
+
+inline void Type1Emitter::emitAllHex()
+{
+ auto const end = maBuffer.getStr() + maBuffer.getLength();
+ for( const char* p = maBuffer.getStr(); p < end;) {
+ // convert binary chunk to hex
+ char aHexBuf[0x4000];
+ char* pOut = aHexBuf;
+ while( (p < end) && (pOut < aHexBuf+sizeof(aHexBuf)-4)) {
+ // convert each byte to hex
+ char cNibble = (static_cast<unsigned char>(*p) >> 4) & 0x0F;
+ cNibble += (cNibble < 10) ? '0' : 'A'-10;
+ *(pOut++) = cNibble;
+ cNibble = *(p++) & 0x0F;
+ cNibble += (cNibble < 10) ? '0' : 'A'-10;
+ *(pOut++) = cNibble;
+ // limit the line length
+ if( (++mnHexLineCol & 0x3F) == 0)
+ *(pOut++) = '\n';
+ }
+ // writeout hex-converted chunk
+ emitRawData( aHexBuf, pOut-aHexBuf);
+ }
+ // reset the raw buffer
+ maBuffer.setLength(0);
+}
+
+void Type1Emitter::emitAllCrypted()
+{
+ // apply t1crypt
+ for( sal_Int32 i = 0; i < maBuffer.getLength(); ++i) {
+ maBuffer[i] ^= (mnEECryptR >> 8);
+ mnEECryptR = (static_cast<U8>(maBuffer[i]) + mnEECryptR) * 52845 + 22719;
+ }
+
+ // emit the t1crypt result
+ if( mbPfbSubset)
+ emitAllRaw();
+ else
+ emitAllHex();
+}
+
+// #i110387# quick-and-dirty double->ascii conversion
+// also strip off trailing zeros in fraction while we are at it
+static OString dbl2str( double fVal)
+{
+ return rtl::math::doubleToString(fVal, rtl_math_StringFormat_G, 6, '.', true);
+}
+
+void Type1Emitter::emitValVector( const char* pLineHead, const char* pLineTail,
+ const std::vector<ValType>& rVector)
+{
+ // ignore empty vectors
+ if( rVector.empty())
+ return;
+
+ // emit the line head
+ maBuffer.append( pLineHead);
+ // emit the vector values
+ std::vector<ValType>::value_type aVal = 0;
+ for( std::vector<ValType>::const_iterator it = rVector.begin();;) {
+ aVal = *it;
+ if( ++it == rVector.end() )
+ break;
+ maBuffer.append(dbl2str( aVal));
+ maBuffer.append(' ');
+ }
+ // emit the last value
+ maBuffer.append(dbl2str( aVal));
+ // emit the line tail
+ maBuffer.append( pLineTail);
+}
+
+void CffSubsetterContext::convertCharStrings(const sal_GlyphId* pGlyphIds, int nGlyphCount,
+ std::vector<CharString>& rCharStrings)
+{
+ // If we are doing extra glyphs used for seac operator, check for already
+ // converted glyphs.
+ bool bCheckDuplicates = !rCharStrings.empty();
+ rCharStrings.reserve(rCharStrings.size() + nGlyphCount);
+ for (int i = 0; i < nGlyphCount; ++i)
+ {
+ const int nCffGlyphId = pGlyphIds[i];
+ assert((nCffGlyphId >= 0) && (nCffGlyphId < mnCharStrCount));
+
+ if (!bCheckDuplicates)
+ {
+ const auto& it
+ = std::find_if(rCharStrings.begin(), rCharStrings.end(),
+ [&](const CharString& c) { return c.nCffGlyphId == nCffGlyphId; });
+ if (it != rCharStrings.end())
+ continue;
+ }
+
+ // get privdict context matching to the glyph
+ const int nFDSelect = getFDSelect(nCffGlyphId);
+ if (nFDSelect < 0)
+ continue;
+ mpCffLocal = &maCffLocal[nFDSelect];
+
+ // convert the Type2op charstring to its Type1op counterpart
+ const int nT2Len = seekIndexData(mnCharStrBase, nCffGlyphId);
+ assert(nT2Len > 0);
+
+ CharString aCharString;
+ const int nT1Len = convert2Type1Ops(mpCffLocal, mpReadPtr, nT2Len, aCharString.aOps);
+ aCharString.nLen = nT1Len;
+ aCharString.nCffGlyphId = nCffGlyphId;
+
+ rCharStrings.push_back(aCharString);
+ }
+}
+
+void CffSubsetterContext::emitAsType1( Type1Emitter& rEmitter,
+ const sal_GlyphId* pReqGlyphIds, const U8* pReqEncoding,
+ int nGlyphCount, FontSubsetInfo& rFSInfo)
+{
+ // prepare some fontdirectory details
+ static const int nUniqueIdBase = 4100000; // using private-interchange UniqueIds
+ static int nUniqueId = nUniqueIdBase;
+ ++nUniqueId;
+
+ char* pFontName = rEmitter.maSubsetName;
+ if( !*pFontName ) {
+ if( mnFontNameSID) {
+ // get the fontname directly if available
+ strncpy(
+ pFontName, getString( mnFontNameSID).getStr(), sizeof(rEmitter.maSubsetName) - 1);
+ pFontName[sizeof(rEmitter.maSubsetName) - 1] = 0;
+ } else if( mnFullNameSID) {
+ // approximate fontname as fullname-whitespace
+ auto const str = getString( mnFullNameSID);
+ const char* pI = str.getStr();
+ char* pO = pFontName;
+ const char* pLimit = pFontName + sizeof(rEmitter.maSubsetName) - 1;
+ while( pO < pLimit) {
+ const char c = *(pI++);
+ if( c != ' ')
+ *(pO++) = c;
+ if( !c)
+ break;
+ }
+ *pO = '\0';
+ } else {
+ // fallback name of last resort
+ strncpy( pFontName, "DummyName", sizeof(rEmitter.maSubsetName));
+ }
+ }
+ const char* pFullName = pFontName;
+ const char* pFamilyName = pFontName;
+
+ // create a PFB+Type1 header
+ if( rEmitter.mbPfbSubset ) {
+ static const char aPfbHeader[] = "\x80\x01\x00\x00\x00\x00";
+ rEmitter.emitRawData( aPfbHeader, sizeof(aPfbHeader)-1);
+ }
+
+ rEmitter.maBuffer.append(
+ "%!FontType1-1.0: " + OString::Concat(rEmitter.maSubsetName) + " 001.003\n");
+ // emit TOPDICT
+ rEmitter.maBuffer.append(
+ "11 dict begin\n" // TODO: dynamic entry count for TOPDICT
+ "/FontType 1 def\n"
+ "/PaintType 0 def\n");
+ rEmitter.maBuffer.append( "/FontName /" + OString::Concat(rEmitter.maSubsetName) + " def\n");
+ rEmitter.maBuffer.append( "/UniqueID " + OString::number(nUniqueId) + " def\n");
+ // emit FontMatrix
+ if( maFontMatrix.size() == 6)
+ rEmitter.emitValVector( "/FontMatrix [", "]readonly def\n", maFontMatrix);
+ else // emit default FontMatrix if needed
+ rEmitter.maBuffer.append( "/FontMatrix [0.001 0 0 0.001 0 0]readonly def\n");
+
+ // emit FontBBox
+ ValType fXFactor = 1.0;
+ ValType fYFactor = 1.0;
+ if( maFontMatrix.size() >= 4) {
+ fXFactor = 1000.0F * maFontMatrix[0];
+ fYFactor = 1000.0F * maFontMatrix[3];
+ }
+
+ auto aFontBBox = maFontBBox;
+ if (rFSInfo.m_bFilled)
+ aFontBBox = {
+ rFSInfo.m_aFontBBox.Left() / fXFactor, rFSInfo.m_aFontBBox.Top() / fYFactor,
+ rFSInfo.m_aFontBBox.Right() / fXFactor, (rFSInfo.m_aFontBBox.Bottom() + 1) / fYFactor
+ };
+ else if (aFontBBox.size() != 4)
+ aFontBBox = { 0, 0, 999, 999 }; // emit default FontBBox if needed
+ rEmitter.emitValVector( "/FontBBox {", "}readonly def\n", aFontBBox);
+ // emit FONTINFO into TOPDICT
+ rEmitter.maBuffer.append(
+ "/FontInfo 2 dict dup begin\n" // TODO: check fontinfo entry count
+ " /FullName (" + OString::Concat(pFullName) + ") readonly def\n"
+ " /FamilyName (" + pFamilyName + ") readonly def\n"
+ "end readonly def\n");
+
+ rEmitter.maBuffer.append(
+ "/Encoding 256 array\n"
+ "0 1 255 {1 index exch /.notdef put} for\n");
+ for( int i = 1; (i < nGlyphCount) && (i < 256); ++i) {
+ OString pGlyphName = getGlyphName( pReqGlyphIds[i]);
+ rEmitter.maBuffer.append(
+ "dup " + OString::number(pReqEncoding[i]) + " /" + pGlyphName + " put\n");
+ }
+ rEmitter.maBuffer.append( "readonly def\n");
+ rEmitter.maBuffer.append(
+ // TODO: more topdict entries
+ "currentdict end\n"
+ "currentfile eexec\n");
+
+ // emit PFB header
+ rEmitter.emitAllRaw();
+ if( rEmitter.mbPfbSubset) {
+ // update PFB header segment
+ const int nPfbHeaderLen = rEmitter.tellPos() - 6;
+ rEmitter.updateLen( 2, nPfbHeaderLen);
+
+ // prepare start of eexec segment
+ rEmitter.emitRawData( "\x80\x02\x00\x00\x00\x00", 6); // segment start
+ }
+ const int nEExecSegTell = rEmitter.tellPos();
+
+ // which always starts with a privdict
+ // count the privdict entries
+ int nPrivEntryCount = 9;
+ // emit blue hints only if non-default values
+ nPrivEntryCount += int(!mpCffLocal->maOtherBlues.empty());
+ nPrivEntryCount += int(!mpCffLocal->maFamilyBlues.empty());
+ nPrivEntryCount += int(!mpCffLocal->maFamilyOtherBlues.empty());
+ nPrivEntryCount += int(mpCffLocal->mfBlueScale != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mfBlueShift != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mfBlueFuzz != 0.0);
+ // emit stem hints only if non-default values
+ nPrivEntryCount += int(mpCffLocal->maStemStdHW != 0);
+ nPrivEntryCount += int(mpCffLocal->maStemStdVW != 0);
+ nPrivEntryCount += int(!mpCffLocal->maStemSnapH.empty());
+ nPrivEntryCount += int(!mpCffLocal->maStemSnapV.empty());
+ // emit other hints only if non-default values
+ nPrivEntryCount += int(mpCffLocal->mfExpFactor != 0.0);
+ nPrivEntryCount += int(mpCffLocal->mnLangGroup != 0);
+ nPrivEntryCount += int(mpCffLocal->mnLangGroup == 1);
+ nPrivEntryCount += int(mpCffLocal->mbForceBold);
+ // emit the privdict header
+ rEmitter.maBuffer.append(
+ "\110\104\125 "
+ "dup\n/Private " + OString::number(nPrivEntryCount) + " dict dup begin\n"
+ "/RD{string currentfile exch readstring pop}executeonly def\n"
+ "/ND{noaccess def}executeonly def\n"
+ "/NP{noaccess put}executeonly def\n"
+ "/MinFeature{16 16}ND\n"
+ "/password 5839 def\n"); // TODO: mnRDCryptSeed?
+
+ // emit blue hint related privdict entries
+ if( !mpCffLocal->maBlueValues.empty())
+ rEmitter.emitValVector( "/BlueValues [", "]ND\n", mpCffLocal->maBlueValues);
+ else
+ rEmitter.maBuffer.append( "/BlueValues []ND\n"); // default to empty BlueValues
+ rEmitter.emitValVector( "/OtherBlues [", "]ND\n", mpCffLocal->maOtherBlues);
+ rEmitter.emitValVector( "/FamilyBlues [", "]ND\n", mpCffLocal->maFamilyBlues);
+ rEmitter.emitValVector( "/FamilyOtherBlues [", "]ND\n", mpCffLocal->maFamilyOtherBlues);
+
+ if( mpCffLocal->mfBlueScale) {
+ rEmitter.maBuffer.append( "/BlueScale ");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->mfBlueScale));
+ rEmitter.maBuffer.append( " def\n");
+ }
+ if( mpCffLocal->mfBlueShift) { // default BlueShift==7
+ rEmitter.maBuffer.append( "/BlueShift ");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->mfBlueShift));
+ rEmitter.maBuffer.append( " def\n");
+ }
+ if( mpCffLocal->mfBlueFuzz) { // default BlueFuzz==1
+ rEmitter.maBuffer.append( "/BlueFuzz ");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->mfBlueFuzz));
+ rEmitter.maBuffer.append( " def\n");
+ }
+
+ // emit stem hint related privdict entries
+ if( mpCffLocal->maStemStdHW) {
+ rEmitter.maBuffer.append( "/StdHW [");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->maStemStdHW));
+ rEmitter.maBuffer.append( "] def\n");
+ }
+ if( mpCffLocal->maStemStdVW) {
+ rEmitter.maBuffer.append( "/StdVW [");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->maStemStdVW));
+ rEmitter.maBuffer.append( "] def\n");
+ }
+ rEmitter.emitValVector( "/StemSnapH [", "]ND\n", mpCffLocal->maStemSnapH);
+ rEmitter.emitValVector( "/StemSnapV [", "]ND\n", mpCffLocal->maStemSnapV);
+
+ // emit other hints
+ if( mpCffLocal->mbForceBold)
+ rEmitter.maBuffer.append( "/ForceBold true def\n");
+ if( mpCffLocal->mnLangGroup != 0)
+ rEmitter.maBuffer.append(
+ "/LanguageGroup " + OString::number(mpCffLocal->mnLangGroup) + " def\n");
+ if( mpCffLocal->mnLangGroup == 1) // compatibility with ancient printers
+ rEmitter.maBuffer.append( "/RndStemUp false def\n");
+ if( mpCffLocal->mfExpFactor) {
+ rEmitter.maBuffer.append( "/ExpansionFactor ");
+ rEmitter.maBuffer.append(dbl2str( mpCffLocal->mfExpFactor));
+ rEmitter.maBuffer.append( " def\n");
+ }
+
+ // emit remaining privdict entries
+ rEmitter.maBuffer.append( "/UniqueID " + OString::number(nUniqueId) + " def\n");
+ // TODO?: more privdict entries?
+
+ rEmitter.maBuffer.append(
+ "/OtherSubrs\n"
+ "% Dummy code for faking flex hints\n"
+ "[ {} {} {} {systemdict /internaldict known not {pop 3}\n"
+ "{1183615869 systemdict /internaldict get exec\n"
+ "dup /startlock known\n"
+ "{/startlock get exec}\n"
+ "{dup /strtlck known\n"
+ "{/strtlck get exec}\n"
+ "{pop 3}\nifelse}\nifelse}\nifelse\n} executeonly\n"
+ "] ND\n");
+
+ // emit used GlobalSubr charstrings
+ // these are the just the default subrs
+ // TODO: do we need them as the flex hints are resolved differently?
+ rEmitter.maBuffer.append(
+ "/Subrs 5 array\n"
+ "dup 0 15 RD \x5F\x3D\x6B\xAC\x3C\xBD\x74\x3D\x3E\x17\xA0\x86\x58\x08\x85 NP\n"
+ "dup 1 9 RD \x5F\x3D\x6B\xD8\xA6\xB5\x68\xB6\xA2 NP\n"
+ "dup 2 9 RD \x5F\x3D\x6B\xAC\x39\x46\xB9\x43\xF9 NP\n"
+ "dup 3 5 RD \x5F\x3D\x6B\xAC\xB9 NP\n"
+ "dup 4 12 RD \x5F\x3D\x6B\xAC\x3E\x5D\x48\x54\x62\x76\x39\x03 NP\n"
+ "ND\n");
+
+ // TODO: emit more GlobalSubr charstrings?
+ // TODO: emit used LocalSubr charstrings?
+
+ // emit the CharStrings for the requested glyphs
+ std::vector<CharString> aCharStrings;
+ mbDoSeac = true;
+ convertCharStrings(pReqGlyphIds, nGlyphCount, aCharStrings);
+
+ // The previous convertCharStrings might collect extra glyphs used in seac
+ // operator, convert them as well
+ if (!maExtraGlyphIds.empty())
+ {
+ mbDoSeac = false;
+ convertCharStrings(maExtraGlyphIds.data(), maExtraGlyphIds.size(), aCharStrings);
+ }
+ rEmitter.maBuffer.append(
+ "2 index /CharStrings " + OString::number(aCharStrings.size()) + " dict dup begin\n");
+ rEmitter.emitAllCrypted();
+ for (const auto& rCharString : aCharStrings)
+ {
+ // get the glyph name
+ OString pGlyphName = getGlyphName(rCharString.nCffGlyphId);
+ // emit the encrypted Type1op charstring
+ rEmitter.maBuffer.append(
+ "/" + pGlyphName + " " + OString::number(rCharString.nLen) + " RD ");
+ rEmitter.maBuffer.append(
+ reinterpret_cast<char const *>(rCharString.aOps), rCharString.nLen);
+ rEmitter.maBuffer.append( " ND\n");
+ rEmitter.emitAllCrypted();
+ // provide individual glyphwidths if requested
+ }
+ rEmitter.maBuffer.append( "end end\nreadonly put\nput\n");
+ rEmitter.maBuffer.append( "dup/FontName get exch definefont pop\n");
+ rEmitter.maBuffer.append( "mark currentfile closefile\n");
+ rEmitter.emitAllCrypted();
+
+ // mark stop of eexec encryption
+ if( rEmitter.mbPfbSubset) {
+ const int nEExecLen = rEmitter.tellPos() - nEExecSegTell;
+ rEmitter.updateLen( nEExecSegTell-4, nEExecLen);
+ }
+
+ // create PFB footer
+ static const char aPfxFooter[] = "\x80\x01\x14\x02\x00\x00\n" // TODO: check segment len
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "0000000000000000000000000000000000000000000000000000000000000000\n"
+ "cleartomark\n"
+ "\x80\x03";
+ if( rEmitter.mbPfbSubset)
+ rEmitter.emitRawData( aPfxFooter, sizeof(aPfxFooter)-1);
+ else
+ rEmitter.emitRawData( aPfxFooter+6, sizeof(aPfxFooter)-9);
+
+ // provide details to the subset requesters, TODO: move into own method?
+ // note: Top and Bottom are flipped between Type1 and VCL
+ // note: the rest of VCL expects the details below to be scaled like for an emUnits==1000 font
+
+ rFSInfo.m_nFontType = rEmitter.mbPfbSubset ? FontType::TYPE1_PFB : FontType::TYPE1_PFA;
+
+ if (rFSInfo.m_bFilled)
+ return;
+
+ rFSInfo.m_aFontBBox = { Point(static_cast<sal_Int32>(aFontBBox[0] * fXFactor),
+ static_cast<sal_Int32>(aFontBBox[1] * fYFactor)),
+ Point(static_cast<sal_Int32>(aFontBBox[2] * fXFactor),
+ static_cast<sal_Int32>(aFontBBox[3] * fYFactor)) };
+ // PDF-Spec says the values below mean the ink bounds!
+ // TODO: use better approximations for these ink bounds
+ rFSInfo.m_nAscent = +rFSInfo.m_aFontBBox.Bottom(); // for capital letters
+ rFSInfo.m_nDescent = -rFSInfo.m_aFontBBox.Top(); // for all letters
+ rFSInfo.m_nCapHeight = rFSInfo.m_nAscent; // for top-flat capital letters
+
+ rFSInfo.m_aPSName = OUString( rEmitter.maSubsetName, strlen(rEmitter.maSubsetName), RTL_TEXTENCODING_UTF8 );
+}
+
+bool FontSubsetInfo::CreateFontSubsetFromCff()
+{
+ CffSubsetterContext aCff( mpInFontBytes, mnInByteLength);
+ bool bRC = aCff.initialCffRead();
+ if (!bRC)
+ return bRC;
+
+ // emit Type1 subset from the CFF input
+ // TODO: also support CFF->CFF subsetting (when PDF-export and PS-printing need it)
+ const bool bPfbSubset(mnReqFontTypeMask & FontType::TYPE1_PFB);
+ Type1Emitter aType1Emitter( mpOutFile, bPfbSubset);
+ aType1Emitter.setSubsetName( mpReqFontName);
+ aCff.emitAsType1( aType1Emitter,
+ mpReqGlyphIds, mpReqEncodedIds,
+ mnReqGlyphCount, *this);
+ return true;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/fontsubset.cxx b/vcl/source/fontsubset/fontsubset.cxx
new file mode 100644
index 0000000000..2a45a1194e
--- /dev/null
+++ b/vcl/source/fontsubset/fontsubset.cxx
@@ -0,0 +1,94 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+
+#include <fontsubset.hxx>
+#include <sft.hxx>
+
+FontSubsetInfo::FontSubsetInfo()
+ : m_nAscent( 0)
+ , m_nDescent( 0)
+ , m_nCapHeight( 0)
+ , m_nFontType( FontType::NO_FONT)
+ , m_bFilled(false)
+ , mpInFontBytes( nullptr)
+ , mnInByteLength( 0)
+ , meInFontType( FontType::NO_FONT)
+ , mnReqFontTypeMask( FontType::NO_FONT )
+ , mpOutFile(nullptr)
+ , mpReqFontName(nullptr)
+ , mpReqGlyphIds(nullptr)
+ , mpReqEncodedIds(nullptr)
+ , mnReqGlyphCount(0)
+{
+}
+
+FontSubsetInfo::~FontSubsetInfo()
+{
+}
+
+// prepare subsetting for fonts where the input font file is mapped
+void FontSubsetInfo::LoadFont(
+ FontType eInFontType,
+ const unsigned char* pInFontBytes, int nInByteLength)
+{
+ meInFontType = eInFontType;
+ mpInFontBytes = pInFontBytes;
+ mnInByteLength = nInByteLength;
+}
+
+bool FontSubsetInfo::CreateFontSubset(
+ FontType nReqFontTypeMask,
+ SvStream* pOutFile, const char* pReqFontName,
+ const sal_GlyphId* pReqGlyphIds, const sal_uInt8* pReqEncodedIds, int nReqGlyphCount)
+{
+ // prepare request details needed by all underlying subsetters
+ mnReqFontTypeMask = nReqFontTypeMask;
+ mpOutFile = pOutFile;
+ mpReqFontName = pReqFontName;
+ mpReqGlyphIds = pReqGlyphIds;
+ mpReqEncodedIds = pReqEncodedIds;
+ mnReqGlyphCount = nReqGlyphCount;
+
+ OString aPSName = m_aPSName.toUtf8();
+ if (!mpReqFontName)
+ mpReqFontName = aPSName.getStr();
+
+ // TODO: move the glyphid/encid/notdef reshuffling from the callers to here
+
+ // dispatch to underlying subsetters
+ bool bOK = false;
+
+ // TODO: better match available input-type to possible subset-types
+ switch( meInFontType) {
+ case FontType::CFF_FONT:
+ bOK = CreateFontSubsetFromCff();
+ break;
+ default:
+ OSL_FAIL( "unhandled type in CreateFontSubset()");
+ break;
+ }
+
+ return bOK;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/sft.cxx b/vcl/source/fontsubset/sft.cxx
new file mode 100644
index 0000000000..1c8c2f6b5f
--- /dev/null
+++ b/vcl/source/fontsubset/sft.cxx
@@ -0,0 +1,1847 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*
+ * Sun Font Tools
+ *
+ * Author: Alexander Gelfenbain
+ *
+ */
+
+#include <assert.h>
+
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#ifdef UNX
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+#include <sft.hxx>
+#include <impfontcharmap.hxx>
+#ifdef SYSTEM_LIBFIXMATH
+#include <libfixmath/fix16.hpp>
+#else
+#include <tools/fix16.hxx>
+#endif
+#include "ttcr.hxx"
+#include "xlat.hxx"
+#include <rtl/crc.h>
+#include <rtl/ustring.hxx>
+#include <rtl/ustrbuf.hxx>
+#include <sal/log.hxx>
+#include <o3tl/safeint.hxx>
+#include <osl/endian.h>
+#include <osl/thread.h>
+#include <unotools/tempfile.hxx>
+#include <fontsubset.hxx>
+#include <algorithm>
+#include <memory>
+
+namespace vcl
+{
+
+namespace {
+
+/*- In horizontal writing mode right sidebearing is calculated using this formula
+ *- rsb = aw - (lsb + xMax - xMin) -*/
+struct TTGlyphMetrics {
+ sal_Int16 xMin;
+ sal_Int16 yMin;
+ sal_Int16 xMax;
+ sal_Int16 yMax;
+ sal_uInt16 aw; /*- Advance Width (horizontal writing mode) */
+ sal_Int16 lsb; /*- Left sidebearing (horizontal writing mode) */
+ sal_uInt16 ah; /*- advance height (vertical writing mode) */
+};
+
+}
+
+/*- Data access methods for data stored in big-endian format */
+static sal_Int16 GetInt16(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_Int16 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+
+ return t;
+}
+
+static sal_uInt16 GetUInt16(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_uInt16 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+
+ return t;
+}
+
+static sal_Int32 GetInt32(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_Int32 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 |
+ (ptr+offset)[2] << 8 | (ptr+offset)[3];
+
+ return t;
+}
+
+static sal_uInt32 GetUInt32(const sal_uInt8 *ptr, size_t offset)
+{
+ sal_uInt32 t;
+ assert(ptr != nullptr);
+
+ t = (ptr+offset)[0] << 24 | (ptr+offset)[1] << 16 |
+ (ptr+offset)[2] << 8 | (ptr+offset)[3];
+
+ return t;
+}
+
+static F16Dot16 fixedMul(F16Dot16 a, F16Dot16 b)
+{
+ return fix16_mul(a, b);
+}
+
+static F16Dot16 fixedDiv(F16Dot16 a, F16Dot16 b)
+{
+ return fix16_div(a, b);
+}
+
+/*- returns a * b / c -*/
+/* XXX provide a real implementation that preserves accuracy */
+static F16Dot16 fixedMulDiv(F16Dot16 a, F16Dot16 b, F16Dot16 c)
+{
+ F16Dot16 res = fixedMul(a, b);
+ return fixedDiv(res, c);
+}
+
+/*- Translate units from TT to PS (standard 1/1000) -*/
+static int XUnits(int unitsPerEm, int n)
+{
+ return (n * 1000) / unitsPerEm;
+}
+
+/* Outline Extraction functions */
+
+/* fills the aw and lsb entries of the TTGlyphMetrics structure from hmtx table -*/
+static void GetMetrics(AbstractTrueTypeFont const *ttf, sal_uInt32 glyphID, TTGlyphMetrics *metrics)
+{
+ sal_uInt32 nSize;
+ const sal_uInt8* table = ttf->table(O_hmtx, nSize);
+
+ metrics->aw = metrics->lsb = metrics->ah = 0;
+ if (!table || !ttf->horzMetricCount())
+ return;
+
+ if (glyphID < ttf->horzMetricCount())
+ {
+ metrics->aw = GetUInt16(table, 4 * glyphID);
+ metrics->lsb = GetInt16(table, 4 * glyphID + 2);
+ }
+ else
+ {
+ metrics->aw = GetUInt16(table, 4 * (ttf->horzMetricCount() - 1));
+ metrics->lsb = GetInt16(table + ttf->horzMetricCount() * 4, (glyphID - ttf->horzMetricCount()) * 2);
+ }
+
+ table = ttf->table(O_vmtx, nSize);
+ if (!table || !ttf->vertMetricCount())
+ return;
+
+ if (glyphID < ttf->vertMetricCount())
+ metrics->ah = GetUInt16(table, 4 * glyphID);
+ else
+ metrics->ah = GetUInt16(table, 4 * (ttf->vertMetricCount() - 1));
+}
+
+static int GetTTGlyphOutline(AbstractTrueTypeFont *, sal_uInt32 , std::vector<ControlPoint>&, TTGlyphMetrics *, std::vector< sal_uInt32 >* );
+
+/* returns the number of control points, allocates the pointArray */
+static int GetSimpleTTOutline(AbstractTrueTypeFont const *ttf, sal_uInt32 glyphID,
+ std::vector<ControlPoint>& pointArray, TTGlyphMetrics *metrics)
+{
+ sal_uInt32 nTableSize;
+ const sal_uInt8* table = ttf->table(O_glyf, nTableSize);
+ sal_uInt8 n;
+ int i, j, z;
+
+ pointArray.clear();
+
+ if (glyphID >= ttf->glyphCount())
+ return 0;
+
+ sal_uInt32 nGlyphOffset = ttf->glyphOffset(glyphID);
+ if (nGlyphOffset > nTableSize)
+ return 0;
+
+ const sal_uInt8* ptr = table + nGlyphOffset;
+ const sal_uInt32 nMaxGlyphSize = nTableSize - nGlyphOffset;
+ constexpr sal_uInt32 nContourOffset = 10;
+ if (nMaxGlyphSize < nContourOffset)
+ return 0;
+
+ const sal_Int16 numberOfContours = GetInt16(ptr, GLYF_numberOfContours_offset);
+ if( numberOfContours <= 0 ) /*- glyph is not simple */
+ return 0;
+
+ const sal_Int32 nMaxContours = (nMaxGlyphSize - nContourOffset)/2;
+ if (numberOfContours > nMaxContours)
+ return 0;
+
+ if (metrics) { /*- GetCompoundTTOutline() calls this function with NULL metrics -*/
+ metrics->xMin = GetInt16(ptr, GLYF_xMin_offset);
+ metrics->yMin = GetInt16(ptr, GLYF_yMin_offset);
+ metrics->xMax = GetInt16(ptr, GLYF_xMax_offset);
+ metrics->yMax = GetInt16(ptr, GLYF_yMax_offset);
+ GetMetrics(ttf, glyphID, metrics);
+ }
+
+ /* determine the last point and be extra safe about it. But probably this code is not needed */
+ sal_uInt16 lastPoint=0;
+ for (i=0; i<numberOfContours; i++)
+ {
+ const sal_uInt16 t = GetUInt16(ptr, nContourOffset + i * 2);
+ if (t > lastPoint)
+ lastPoint = t;
+ }
+
+ sal_uInt32 nInstLenOffset = nContourOffset + numberOfContours * 2;
+ if (nInstLenOffset + 2 > nMaxGlyphSize)
+ return 0;
+ sal_uInt16 instLen = GetUInt16(ptr, nInstLenOffset);
+
+ sal_uInt32 nOffset = nContourOffset + 2 * numberOfContours + 2 + instLen;
+ if (nOffset > nMaxGlyphSize)
+ return 0;
+ const sal_uInt8* p = ptr + nOffset;
+
+ sal_uInt32 nBytesRemaining = nMaxGlyphSize - nOffset;
+ const sal_uInt32 palen = lastPoint+1;
+
+ //at a minimum its one byte per entry
+ if (palen > nBytesRemaining || lastPoint > nBytesRemaining-1)
+ {
+ SAL_WARN("vcl.fonts", "Font " << OUString::createFromAscii(ttf->fileName()) <<
+ "claimed a palen of "
+ << palen << " but max bytes remaining is " << nBytesRemaining);
+ return 0;
+ }
+
+ std::vector<ControlPoint> pa(palen);
+
+ i = 0;
+ while (i <= lastPoint) {
+ if (!nBytesRemaining)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ sal_uInt8 flag = *p++;
+ --nBytesRemaining;
+ pa[i++].flags = static_cast<sal_uInt32>(flag);
+ if (flag & 8) { /*- repeat flag */
+ if (!nBytesRemaining)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ n = *p++;
+ --nBytesRemaining;
+ // coverity[tainted_data : FALSE] - i > lastPoint extra checks the n loop bound
+ for (j=0; j<n; j++) {
+ if (i > lastPoint) { /*- if the font is really broken */
+ return 0;
+ }
+ pa[i++].flags = flag;
+ }
+ }
+ }
+
+ /*- Process the X coordinate */
+ z = 0;
+ for (i = 0; i <= lastPoint; i++) {
+ if (pa[i].flags & 0x02) {
+ if (!nBytesRemaining)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ if (pa[i].flags & 0x10) {
+ z += static_cast<int>(*p++);
+ } else {
+ z -= static_cast<int>(*p++);
+ }
+ --nBytesRemaining;
+ } else if ( !(pa[i].flags & 0x10)) {
+ if (nBytesRemaining < 2)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ z += GetInt16(p, 0);
+ p += 2;
+ nBytesRemaining -= 2;
+ }
+ pa[i].x = static_cast<sal_Int16>(z);
+ }
+
+ /*- Process the Y coordinate */
+ z = 0;
+ for (i = 0; i <= lastPoint; i++) {
+ if (pa[i].flags & 0x04) {
+ if (!nBytesRemaining)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ if (pa[i].flags & 0x20) {
+ z += *p++;
+ } else {
+ z -= *p++;
+ }
+ --nBytesRemaining;
+ } else if ( !(pa[i].flags & 0x20)) {
+ if (nBytesRemaining < 2)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ z += GetInt16(p, 0);
+ p += 2;
+ nBytesRemaining -= 2;
+ }
+ pa[i].y = static_cast<sal_Int16>(z);
+ }
+
+ for (i=0; i<numberOfContours; i++) {
+ sal_uInt16 offset = GetUInt16(ptr, 10 + i * 2);
+ SAL_WARN_IF(offset >= palen, "vcl.fonts", "Font " << OUString::createFromAscii(ttf->fileName()) <<
+ " contour " << i << " claimed an illegal offset of "
+ << offset << " but max offset is " << palen-1);
+ if (offset >= palen)
+ continue;
+ pa[offset].flags |= 0x00008000; /*- set the end contour flag */
+ }
+
+ pointArray = std::move(pa);
+ return lastPoint + 1;
+}
+
+static F16Dot16 fromF2Dot14(sal_Int16 n)
+{
+ // Avoid undefined shift of negative values prior to C++2a:
+ return sal_uInt32(n) << 2;
+}
+
+static int GetCompoundTTOutline(AbstractTrueTypeFont *ttf, sal_uInt32 glyphID, std::vector<ControlPoint>& pointArray,
+ TTGlyphMetrics *metrics, std::vector<sal_uInt32>& glyphlist)
+{
+ sal_uInt16 flags, index;
+ sal_Int16 e, f;
+ sal_uInt32 nTableSize;
+ const sal_uInt8* table = ttf->table(O_glyf, nTableSize);
+ std::vector<ControlPoint> myPoints;
+ std::vector<ControlPoint> nextComponent;
+ int i, np;
+ F16Dot16 a = 0x10000, b = 0, c = 0, d = 0x10000, m, n, abs1, abs2, abs3;
+
+ pointArray.clear();
+
+ if (glyphID >= ttf->glyphCount())
+ return 0;
+
+ sal_uInt32 nGlyphOffset = ttf->glyphOffset(glyphID);
+ if (nGlyphOffset > nTableSize)
+ return 0;
+
+ const sal_uInt8* ptr = table + nGlyphOffset;
+ sal_uInt32 nAvailableBytes = nTableSize - nGlyphOffset;
+
+ if (GLYF_numberOfContours_offset + 2 > nAvailableBytes)
+ return 0;
+
+ if (GetInt16(ptr, GLYF_numberOfContours_offset) != -1) /* number of contours - glyph is not compound */
+ return 0;
+
+ if (metrics) {
+ metrics->xMin = GetInt16(ptr, GLYF_xMin_offset);
+ metrics->yMin = GetInt16(ptr, GLYF_yMin_offset);
+ metrics->xMax = GetInt16(ptr, GLYF_xMax_offset);
+ metrics->yMax = GetInt16(ptr, GLYF_yMax_offset);
+ GetMetrics(ttf, glyphID, metrics);
+ }
+
+ if (nAvailableBytes < 10)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+
+ ptr += 10;
+ nAvailableBytes -= 10;
+
+ do {
+
+ if (nAvailableBytes < 4)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ flags = GetUInt16(ptr, 0);
+ /* printf("flags: 0x%X\n", flags); */
+ index = GetUInt16(ptr, 2);
+ ptr += 4;
+ nAvailableBytes -= 4;
+
+ if( std::find( glyphlist.begin(), glyphlist.end(), index ) != glyphlist.end() )
+ {
+ SAL_WARN("vcl.fonts", "Endless loop found in a compound glyph.");
+
+#if OSL_DEBUG_LEVEL > 1
+ std::ostringstream oss;
+ oss << index << " -> [";
+ for( const auto& rGlyph : glyphlist )
+ {
+ oss << (int) rGlyph << " ";
+ }
+ oss << "]";
+ SAL_INFO("vcl.fonts", oss.str());
+ /**/
+#endif
+ return 0;
+ }
+
+ glyphlist.push_back( index );
+
+ np = GetTTGlyphOutline(ttf, index, nextComponent, nullptr, &glyphlist);
+
+ if( ! glyphlist.empty() )
+ glyphlist.pop_back();
+
+ if (np == 0)
+ {
+ /* XXX that probably indicates a corrupted font */
+ SAL_WARN("vcl.fonts", "An empty compound!");
+ /* assert(!"An empty compound"); */
+ return 0;
+ }
+
+ if ((flags & USE_MY_METRICS) && metrics)
+ GetMetrics(ttf, index, metrics);
+
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ if (nAvailableBytes < 4)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ e = GetInt16(ptr, 0);
+ f = GetInt16(ptr, 2);
+ /* printf("ARG_1_AND_2_ARE_WORDS: %d %d\n", e & 0xFFFF, f & 0xFFFF); */
+ ptr += 4;
+ nAvailableBytes -= 4;
+ } else {
+ if (nAvailableBytes < 2)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ if (flags & ARGS_ARE_XY_VALUES) { /* args are signed */
+ e = static_cast<sal_Int8>(*ptr++);
+ f = static_cast<sal_Int8>(*ptr++);
+ /* printf("ARGS_ARE_XY_VALUES: %d %d\n", e & 0xFF, f & 0xFF); */
+ } else { /* args are unsigned */
+ /* printf("!ARGS_ARE_XY_VALUES\n"); */
+ e = *ptr++;
+ f = *ptr++;
+ }
+ nAvailableBytes -= 2;
+ }
+
+ a = d = 0x10000;
+ b = c = 0;
+
+ if (flags & WE_HAVE_A_SCALE) {
+ if (nAvailableBytes < 2)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ d = a;
+ ptr += 2;
+ nAvailableBytes -= 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ if (nAvailableBytes < 4)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ d = fromF2Dot14(GetInt16(ptr, 2));
+ ptr += 4;
+ nAvailableBytes -= 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ if (nAvailableBytes < 8)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ return 0;
+ }
+ a = fromF2Dot14(GetInt16(ptr, 0));
+ b = fromF2Dot14(GetInt16(ptr, 2));
+ c = fromF2Dot14(GetInt16(ptr, 4));
+ d = fromF2Dot14(GetInt16(ptr, 6));
+ ptr += 8;
+ nAvailableBytes -= 8;
+ }
+
+ abs1 = (a < 0) ? -a : a;
+ abs2 = (b < 0) ? -b : b;
+ m = std::max(abs1, abs2);
+ abs3 = abs1 - abs2;
+ if (abs3 < 0) abs3 = -abs3;
+ if (abs3 <= 33) m *= 2;
+
+ abs1 = (c < 0) ? -c : c;
+ abs2 = (d < 0) ? -d : d;
+ n = std::max(abs1, abs2);
+ abs3 = abs1 - abs2;
+ if (abs3 < 0) abs3 = -abs3;
+ if (abs3 <= 33) n *= 2;
+
+ SAL_WARN_IF(np && (!m || !n), "vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fileName()) <<
+ ": divide by zero");
+
+ if (m != 0 && n != 0) {
+ for (i=0; i<np; i++) {
+ F16Dot16 t;
+ ControlPoint cp;
+ cp.flags = nextComponent[i].flags;
+ const sal_uInt16 x = nextComponent[i].x;
+ const sal_uInt16 y = nextComponent[i].y;
+ t = o3tl::saturating_add(o3tl::saturating_add(fixedMulDiv(a, x << 16, m), fixedMulDiv(c, y << 16, m)), sal_Int32(sal_uInt16(e) << 16));
+ cp.x = static_cast<sal_Int16>(fixedMul(t, m) >> 16);
+ t = o3tl::saturating_add(o3tl::saturating_add(fixedMulDiv(b, x << 16, n), fixedMulDiv(d, y << 16, n)), sal_Int32(sal_uInt16(f) << 16));
+ cp.y = static_cast<sal_Int16>(fixedMul(t, n) >> 16);
+
+ myPoints.push_back( cp );
+ }
+ }
+
+ if (myPoints.size() > SAL_MAX_UINT16) {
+ SAL_WARN("vcl.fonts", "number of points has to be limited to max value GlyphData::npoints can contain, abandon effort");
+ myPoints.clear();
+ break;
+ }
+
+ } while (flags & MORE_COMPONENTS);
+
+ // #i123417# some fonts like IFAOGrec have no outline points in some compound glyphs
+ // so this unlikely but possible scenario should be handled gracefully
+ if( myPoints.empty() )
+ return 0;
+
+ np = myPoints.size();
+
+ pointArray = std::move(myPoints);
+
+ return np;
+}
+
+/* NOTE: GetTTGlyphOutline() returns -1 if the glyphID is incorrect,
+ * but Get{Simple|Compound}GlyphOutline returns 0 in such a case.
+ *
+ * NOTE: glyphlist is the stack of glyphs traversed while constructing
+ * a composite glyph. This is a safeguard against endless recursion
+ * in corrupted fonts.
+ */
+static int GetTTGlyphOutline(AbstractTrueTypeFont *ttf, sal_uInt32 glyphID, std::vector<ControlPoint>& pointArray, TTGlyphMetrics *metrics, std::vector< sal_uInt32 >* glyphlist)
+{
+ sal_uInt32 glyflength;
+ const sal_uInt8 *table = ttf->table(O_glyf, glyflength);
+ sal_Int16 numberOfContours;
+ int res;
+ pointArray.clear();
+
+ if (metrics)
+ memset(metrics, 0, sizeof(TTGlyphMetrics));
+
+ if (glyphID >= ttf->glyphCount())
+ return -1;
+
+ sal_uInt32 nNextOffset = ttf->glyphOffset(glyphID + 1);
+ if (nNextOffset > glyflength)
+ return -1;
+
+ sal_uInt32 nOffset = ttf->glyphOffset(glyphID);
+ if (nOffset > nNextOffset)
+ return -1;
+
+ int length = nNextOffset - nOffset;
+ if (length == 0) { /*- empty glyphs still have hmtx and vmtx metrics values */
+ if (metrics) GetMetrics(ttf, glyphID, metrics);
+ return 0;
+ }
+
+ const sal_uInt8* ptr = table + nOffset;
+ const sal_uInt32 nMaxGlyphSize = glyflength - nOffset;
+
+ if (nMaxGlyphSize < 2)
+ return -1;
+
+ numberOfContours = GetInt16(ptr, 0);
+
+ if (numberOfContours >= 0)
+ {
+ res = GetSimpleTTOutline(ttf, glyphID, pointArray, metrics);
+ }
+ else
+ {
+ std::vector< sal_uInt32 > aPrivList { glyphID };
+ res = GetCompoundTTOutline(ttf, glyphID, pointArray, metrics, glyphlist ? *glyphlist : aPrivList );
+ }
+
+ return res;
+}
+
+/*- Extracts a string from the name table and allocates memory for it -*/
+
+static OString nameExtract( const sal_uInt8* name, int nTableSize, int n, int dbFlag, OUString* ucs2result )
+{
+ OStringBuffer res;
+ const sal_uInt8* ptr = name + GetUInt16(name, 4) + GetUInt16(name + 6, 12 * n + 10);
+ int len = GetUInt16(name+6, 12 * n + 8);
+
+ // sanity check
+ const sal_uInt8* end_table = name+nTableSize;
+ const int available_space = ptr > end_table ? 0 : (end_table - ptr);
+ if( (len <= 0) || len > available_space)
+ {
+ if( ucs2result )
+ ucs2result->clear();
+ return OString();
+ }
+
+ if( ucs2result )
+ ucs2result->clear();
+ if (dbFlag) {
+ res.setLength(len/2);
+ for (int i = 0; i < len/2; i++)
+ {
+ res[i] = *(ptr + i * 2 + 1);
+ SAL_WARN_IF(res[i] == 0, "vcl.fonts", "font name is bogus");
+ }
+ if( ucs2result )
+ {
+ OUStringBuffer buf(len/2);
+ buf.setLength(len/2);
+ for (int i = 0; i < len/2; i++ )
+ {
+ buf[i] = GetUInt16( ptr, 2*i );
+ SAL_WARN_IF(buf[i] == 0, "vcl.fonts", "font name is bogus");
+ }
+ *ucs2result = buf.makeStringAndClear();
+ }
+ } else {
+ res.setLength(len);
+ memcpy(static_cast<void*>(const_cast<char*>(res.getStr())), ptr, len);
+ }
+
+ return res.makeStringAndClear();
+}
+
+static int findname( const sal_uInt8 *name, sal_uInt16 n, sal_uInt16 platformID,
+ sal_uInt16 encodingID, sal_uInt16 languageID, sal_uInt16 nameID )
+{
+ if (n == 0) return -1;
+
+ int l = 0, r = n-1;
+ sal_uInt32 t1, t2;
+ sal_uInt32 m1, m2;
+
+ m1 = (platformID << 16) | encodingID;
+ m2 = (languageID << 16) | nameID;
+
+ do {
+ const int i = (l + r) >> 1;
+ t1 = GetUInt32(name + 6, i * 12 + 0);
+ t2 = GetUInt32(name + 6, i * 12 + 4);
+
+ if (! ((m1 < t1) || ((m1 == t1) && (m2 < t2)))) l = i + 1;
+ if (! ((m1 > t1) || ((m1 == t1) && (m2 > t2)))) r = i - 1;
+ } while (l <= r);
+
+ if (l - r == 2) {
+ return l - 1;
+ }
+
+ return -1;
+}
+
+/* XXX marlett.ttf uses (3, 0, 1033) instead of (3, 1, 1033) and does not have any Apple tables.
+ * Fix: if (3, 1, 1033) is not found - need to check for (3, 0, 1033)
+ *
+ * /d/fonts/ttzh_tw/Big5/Hanyi/ma6b5p uses (1, 0, 19) for English strings, instead of (1, 0, 0)
+ * and does not have (3, 1, 1033)
+ * Fix: if (1, 0, 0) and (3, 1, 1033) are not found need to look for (1, 0, *) - that will
+ * require a change in algorithm
+ *
+ * /d/fonts/fdltest/Korean/h2drrm has unsorted names and an unknown (to me) Mac LanguageID,
+ * but (1, 0, 1042) strings usable
+ * Fix: change algorithm, and use (1, 0, *) if both standard Mac and MS strings are not found
+ */
+
+static void GetNames(AbstractTrueTypeFont *t)
+{
+ sal_uInt32 nTableSize;
+ const sal_uInt8* table = t->table(O_name, nTableSize);
+
+ if (nTableSize < 6)
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "O_name table too small.");
+#endif
+ return;
+ }
+
+ sal_uInt16 n = GetUInt16(table, 2);
+
+ /* simple sanity check for name table entry count */
+ const size_t nMinRecordSize = 12;
+ const size_t nSpaceAvailable = nTableSize - 6;
+ const size_t nMaxRecords = nSpaceAvailable/nMinRecordSize;
+ if (n >= nMaxRecords)
+ n = 0;
+
+ int i, r;
+ bool bPSNameOK = true;
+
+ /* PostScript name: preferred Microsoft */
+ t->psname.clear();
+ if ((r = findname(table, n, 3, 1, 0x0409, 6)) != -1)
+ t->psname = nameExtract(table, nTableSize, r, 1, nullptr);
+ if ( t->psname.isEmpty() && (r = findname(table, n, 1, 0, 0, 6)) != -1)
+ t->psname = nameExtract(table, nTableSize, r, 0, nullptr);
+ if ( t->psname.isEmpty() && (r = findname(table, n, 3, 0, 0x0409, 6)) != -1)
+ {
+ // some symbol fonts like Marlett have a 3,0 name!
+ t->psname = nameExtract(table, nTableSize, r, 1, nullptr);
+ }
+ // for embedded font in Ghostscript PDFs
+ if ( t->psname.isEmpty() && (r = findname(table, n, 2, 2, 0, 6)) != -1)
+ {
+ t->psname = nameExtract(table, nTableSize, r, 0, nullptr);
+ }
+ if ( t->psname.isEmpty() )
+ {
+ if (!t->fileName().empty())
+ {
+ const char* pReverse = t->fileName().data() + t->fileName().length();
+ /* take only last token of filename */
+ while (pReverse != t->fileName().data() && *pReverse != '/') pReverse--;
+ if(*pReverse == '/') pReverse++;
+ int nReverseLen = strlen(pReverse);
+ for (i=nReverseLen - 1; i > 0; i--)
+ {
+ /*- Remove the suffix -*/
+ if (*(pReverse + i) == '.' ) {
+ nReverseLen = i;
+ break;
+ }
+ }
+ t->psname = OString(std::string_view(pReverse, nReverseLen));
+ }
+ else
+ t->psname = "Unknown"_ostr;
+ }
+
+ /* Font family and subfamily names: preferred Apple */
+ t->family.clear();
+ if ((r = findname(table, n, 0, 0, 0, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( t->family.isEmpty() && (r = findname(table, n, 3, 1, 0x0409, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( t->family.isEmpty() && (r = findname(table, n, 1, 0, 0, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 0, nullptr);
+ if ( t->family.isEmpty() && (r = findname(table, n, 3, 1, 0x0411, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( t->family.isEmpty() && (r = findname(table, n, 3, 0, 0x0409, 1)) != -1)
+ t->family = nameExtract(table, nTableSize, r, 1, &t->ufamily);
+ if ( t->family.isEmpty() )
+ t->family = t->psname;
+
+ t->subfamily.clear();
+ t->usubfamily.clear();
+ if ((r = findname(table, n, 1, 0, 0, 2)) != -1)
+ t->subfamily = nameExtract(table, nTableSize, r, 0, &t->usubfamily);
+ if ( t->subfamily.isEmpty() && (r = findname(table, n, 3, 1, 0x0409, 2)) != -1)
+ t->subfamily = nameExtract(table, nTableSize, r, 1, &t->usubfamily);
+
+ /* #i60349# sanity check psname
+ * psname practically has to be 7bit ASCII and should not contain spaces
+ * there is a class of broken fonts which do not fulfill that at all, so let's try
+ * if the family name is 7bit ASCII and take it instead if so
+ */
+ /* check psname */
+ for( i = 0; i < t->psname.getLength() && bPSNameOK; i++ )
+ if( t->psname[ i ] < 33 || (t->psname[ i ] & 0x80) )
+ bPSNameOK = false;
+ if( bPSNameOK )
+ return;
+
+ /* check if family is a suitable replacement */
+ if( t->ufamily.isEmpty() && t->family.isEmpty() )
+ return;
+
+ bool bReplace = true;
+
+ for( i = 0; i < t->ufamily.getLength() && bReplace; i++ )
+ if( t->ufamily[ i ] < 33 || t->ufamily[ i ] > 127 )
+ bReplace = false;
+ if( bReplace )
+ {
+ t->psname = t->family;
+ }
+}
+
+/*- Public functions */
+
+int CountTTCFonts(const char* fname)
+{
+ FILE* fd;
+#ifdef LINUX
+ int nFD;
+ int n;
+ if (sscanf(fname, "/:FD:/%d%n", &nFD, &n) == 1 && fname[n] == '\0')
+ {
+ lseek(nFD, 0, SEEK_SET);
+ int nDupFd = dup(nFD);
+ fd = nDupFd != -1 ? fdopen(nDupFd, "rb") : nullptr;
+ }
+ else
+#endif
+ fd = fopen(fname, "rb");
+
+ if (!fd)
+ return 0;
+
+ int nFonts = 0;
+ sal_uInt8 buffer[12];
+ if (fread(buffer, 1, 12, fd) == 12) {
+ if(GetUInt32(buffer, 0) == T_ttcf )
+ nFonts = GetUInt32(buffer, 8);
+ }
+
+ if (nFonts > 0)
+ {
+ fseek(fd, 0, SEEK_END);
+ sal_uInt64 fileSize = ftell(fd);
+
+ //Feel free to calc the exact max possible number of fonts a file
+ //could contain given its physical size. But this will clamp it to
+ //a sane starting point
+ //http://processingjs.nihongoresources.com/the_smallest_font/
+ //https://github.com/grzegorzrolek/null-ttf
+ const int nMaxFontsPossible = fileSize / 528;
+ if (nFonts > nMaxFontsPossible)
+ {
+ SAL_WARN("vcl.fonts", "font file " << fname <<" claims to have "
+ << nFonts << " fonts, but only "
+ << nMaxFontsPossible << " are possible");
+ nFonts = nMaxFontsPossible;
+ }
+ }
+
+ fclose(fd);
+
+ return nFonts;
+}
+
+#if !defined(_WIN32)
+SFErrCodes OpenTTFontFile(const char* fname, sal_uInt32 facenum, TrueTypeFont** ttf,
+ const FontCharMapRef xCharMap)
+{
+ SFErrCodes ret;
+ int fd = -1;
+ struct stat st;
+
+ if (!fname || !*fname) return SFErrCodes::BadFile;
+
+ *ttf = new TrueTypeFont(fname, xCharMap);
+ if( ! *ttf )
+ return SFErrCodes::Memory;
+
+ if( (*ttf)->fileName().empty() )
+ {
+ ret = SFErrCodes::Memory;
+ goto cleanup;
+ }
+
+ int nFD;
+ int n;
+ if (sscanf(fname, "/:FD:/%d%n", &nFD, &n) == 1 && fname[n] == '\0')
+ {
+ lseek(nFD, 0, SEEK_SET);
+ fd = dup(nFD);
+ }
+ else
+ fd = open(fname, O_RDONLY);
+
+ if (fd == -1) {
+ ret = SFErrCodes::BadFile;
+ goto cleanup;
+ }
+
+ if (fstat(fd, &st) == -1) {
+ ret = SFErrCodes::FileIo;
+ goto cleanup;
+ }
+
+ (*ttf)->fsize = st.st_size;
+
+ /* On Mac OS, most likely will happen if a Mac user renames a font file
+ * to be .ttf when it's really a Mac resource-based font.
+ * Size will be 0, but fonts smaller than 4 bytes would be broken anyway.
+ */
+ if ((*ttf)->fsize == 0) {
+ ret = SFErrCodes::BadFile;
+ goto cleanup;
+ }
+
+ if (((*ttf)->ptr = static_cast<sal_uInt8 *>(mmap(nullptr, (*ttf)->fsize, PROT_READ, MAP_SHARED, fd, 0))) == MAP_FAILED) {
+ ret = SFErrCodes::Memory;
+ goto cleanup;
+ }
+
+ ret = (*ttf)->open(facenum);
+
+cleanup:
+ if (fd != -1) close(fd);
+ if (ret != SFErrCodes::Ok)
+ {
+ delete *ttf;
+ *ttf = nullptr;
+ }
+ return ret;
+}
+#endif
+
+SFErrCodes OpenTTFontBuffer(const void* pBuffer, sal_uInt32 nLen, sal_uInt32 facenum, TrueTypeFont** ttf,
+ const FontCharMapRef xCharMap)
+{
+ *ttf = new TrueTypeFont(nullptr, xCharMap);
+ if( *ttf == nullptr )
+ return SFErrCodes::Memory;
+
+ (*ttf)->fsize = nLen;
+ (*ttf)->ptr = const_cast<sal_uInt8 *>(static_cast<sal_uInt8 const *>(pBuffer));
+
+ SFErrCodes ret = (*ttf)->open(facenum);
+ if (ret != SFErrCodes::Ok)
+ {
+ delete *ttf;
+ *ttf = nullptr;
+ }
+ return ret;
+}
+
+namespace {
+
+bool withinBounds(sal_uInt32 tdoffset, sal_uInt32 moreoffset, sal_uInt32 len, sal_uInt32 available)
+{
+ sal_uInt32 result;
+ if (o3tl::checked_add(tdoffset, moreoffset, result))
+ return false;
+ if (o3tl::checked_add(result, len, result))
+ return false;
+ return result <= available;
+}
+}
+
+AbstractTrueTypeFont::AbstractTrueTypeFont(const char* pFileName, const FontCharMapRef xCharMap)
+ : m_nGlyphs(0xFFFFFFFF)
+ , m_nHorzMetrics(0)
+ , m_nVertMetrics(0)
+ , m_nUnitsPerEm(0)
+ , m_xCharMap(xCharMap)
+ , m_bMicrosoftSymbolEncoded(false)
+{
+ if (pFileName)
+ m_sFileName = pFileName;
+}
+
+AbstractTrueTypeFont::~AbstractTrueTypeFont()
+{
+}
+
+TrueTypeFont::TrueTypeFont(const char* pFileName, const FontCharMapRef xCharMap)
+ : AbstractTrueTypeFont(pFileName, xCharMap)
+ , fsize(-1)
+ , ptr(nullptr)
+ , ntables(0)
+{
+}
+
+TrueTypeFont::~TrueTypeFont()
+{
+#if !defined(_WIN32)
+ if (!fileName().empty())
+ munmap(ptr, fsize);
+#endif
+}
+
+void CloseTTFont(TrueTypeFont* ttf) { delete ttf; }
+
+SFErrCodes AbstractTrueTypeFont::initialize()
+{
+ SFErrCodes ret = indexGlyphData();
+ if (ret != SFErrCodes::Ok)
+ return ret;
+
+ GetNames(this);
+
+ return SFErrCodes::Ok;
+}
+
+sal_uInt32 AbstractTrueTypeFont::glyphOffset(sal_uInt32 glyphID) const
+{
+ if (m_aGlyphOffsets.empty()) // the O_CFF and Bitmap cases
+ return 0;
+ return m_aGlyphOffsets[glyphID];
+}
+
+SFErrCodes AbstractTrueTypeFont::indexGlyphData()
+{
+ if (!(hasTable(O_maxp) && hasTable(O_head) && hasTable(O_name) && hasTable(O_cmap)))
+ return SFErrCodes::TtFormat;
+
+ sal_uInt32 table_size;
+ const sal_uInt8* table = this->table(O_maxp, table_size);
+ m_nGlyphs = table_size >= 6 ? GetUInt16(table, 4) : 0;
+
+ table = this->table(O_head, table_size);
+ if (table_size < HEAD_Length)
+ return SFErrCodes::TtFormat;
+
+ m_nUnitsPerEm = GetUInt16(table, HEAD_unitsPerEm_offset);
+ int indexfmt = GetInt16(table, HEAD_indexToLocFormat_offset);
+
+ if (((indexfmt != 0) && (indexfmt != 1)) || (m_nUnitsPerEm <= 0))
+ return SFErrCodes::TtFormat;
+
+ if (hasTable(O_glyf) && (table = this->table(O_loca, table_size))) /* TTF or TTF-OpenType */
+ {
+ int k = (table_size / (indexfmt ? 4 : 2)) - 1;
+ if (k < static_cast<int>(m_nGlyphs)) /* Hack for broken Chinese fonts */
+ m_nGlyphs = k;
+
+ m_aGlyphOffsets.clear();
+ m_aGlyphOffsets.reserve(m_nGlyphs + 1);
+ for (int i = 0; i <= static_cast<int>(m_nGlyphs); ++i)
+ m_aGlyphOffsets.push_back(indexfmt ? GetUInt32(table, i << 2) : static_cast<sal_uInt32>(GetUInt16(table, i << 1)) << 1);
+ }
+ else if (this->table(O_CFF, table_size)) /* PS-OpenType */
+ {
+ int k = (table_size / 2) - 1; /* set a limit here, presumably much lower than the table size, but establishes some sort of physical bound */
+ if (k < static_cast<int>(m_nGlyphs))
+ m_nGlyphs = k;
+
+ m_aGlyphOffsets.clear();
+ /* TODO: implement to get subsetting */
+ }
+ else {
+ // Bitmap font, accept for now.
+ // TODO: We only need this for fonts with CBDT table since they usually
+ // lack glyf or CFF table, the check should be more specific, or better
+ // non-subsetting code should not be calling this.
+ m_aGlyphOffsets.clear();
+ }
+
+ table = this->table(O_hhea, table_size);
+ m_nHorzMetrics = (table && table_size >= 36) ? GetUInt16(table, 34) : 0;
+
+ table = this->table(O_vhea, table_size);
+ m_nVertMetrics = (table && table_size >= 36) ? GetUInt16(table, 34) : 0;
+
+ if (!m_xCharMap.is())
+ {
+ table = this->table(O_cmap, table_size);
+ m_bMicrosoftSymbolEncoded = HasMicrosoftSymbolCmap(table, table_size);
+ }
+ else
+ m_bMicrosoftSymbolEncoded = m_xCharMap->isMicrosoftSymbolMap();
+
+ return SFErrCodes::Ok;
+}
+
+SFErrCodes TrueTypeFont::open(sal_uInt32 facenum)
+{
+ if (fsize < 4)
+ return SFErrCodes::TtFormat;
+
+ int i;
+ sal_uInt32 length, tag;
+ sal_uInt32 tdoffset = 0; /* offset to TableDirectory in a TTC file. For TTF files is 0 */
+
+ sal_uInt32 TTCTag = GetInt32(ptr, 0);
+
+ if ((TTCTag == 0x00010000) || (TTCTag == T_true)) {
+ tdoffset = 0;
+ } else if (TTCTag == T_otto) { /* PS-OpenType font */
+ tdoffset = 0;
+ } else if (TTCTag == T_ttcf) { /* TrueType collection */
+ if (!withinBounds(12, 4 * facenum, sizeof(sal_uInt32), fsize))
+ return SFErrCodes::FontNo;
+ sal_uInt32 Version = GetUInt32(ptr, 4);
+ if (Version != 0x00010000 && Version != 0x00020000) {
+ return SFErrCodes::TtFormat;
+ }
+ if (facenum >= GetUInt32(ptr, 8))
+ return SFErrCodes::FontNo;
+ tdoffset = GetUInt32(ptr, 12 + 4 * facenum);
+ } else {
+ return SFErrCodes::TtFormat;
+ }
+
+ if (withinBounds(tdoffset, 0, 4 + sizeof(sal_uInt16), fsize))
+ ntables = GetUInt16(ptr + tdoffset, 4);
+
+ if (ntables >= 128 || ntables == 0)
+ return SFErrCodes::TtFormat;
+
+ /* parse the tables */
+ for (i = 0; i < static_cast<int>(ntables); i++)
+ {
+ int nIndex;
+ const sal_uInt32 nStart = tdoffset + 12;
+ const sal_uInt32 nOffset = 16 * i;
+ if (withinBounds(nStart, nOffset, sizeof(sal_uInt32), fsize))
+ tag = GetUInt32(ptr + nStart, nOffset);
+ else
+ tag = static_cast<sal_uInt32>(-1);
+ switch( tag ) {
+ case T_maxp: nIndex = O_maxp; break;
+ case T_glyf: nIndex = O_glyf; break;
+ case T_head: nIndex = O_head; break;
+ case T_loca: nIndex = O_loca; break;
+ case T_name: nIndex = O_name; break;
+ case T_hhea: nIndex = O_hhea; break;
+ case T_hmtx: nIndex = O_hmtx; break;
+ case T_cmap: nIndex = O_cmap; break;
+ case T_vhea: nIndex = O_vhea; break;
+ case T_vmtx: nIndex = O_vmtx; break;
+ case T_OS2 : nIndex = O_OS2; break;
+ case T_post: nIndex = O_post; break;
+ case T_cvt : nIndex = O_cvt; break;
+ case T_prep: nIndex = O_prep; break;
+ case T_fpgm: nIndex = O_fpgm; break;
+ case T_CFF: nIndex = O_CFF; break;
+ default: nIndex = -1; break;
+ }
+
+ if ((nIndex >= 0) && withinBounds(nStart, nOffset, 12 + sizeof(sal_uInt32), fsize))
+ {
+ sal_uInt32 nTableOffset = GetUInt32(ptr + nStart, nOffset + 8);
+ length = GetUInt32(ptr + nStart, nOffset + 12);
+ m_aTableList[nIndex].pData = ptr + nTableOffset;
+ m_aTableList[nIndex].nSize = length;
+ }
+ }
+
+ /* Fixup offsets when only a TTC extract was provided */
+ if (facenum == sal_uInt32(~0))
+ {
+ sal_uInt8* pHead = const_cast<sal_uInt8*>(m_aTableList[O_head].pData);
+ if (!pHead)
+ return SFErrCodes::TtFormat;
+
+ /* limit Head candidate to TTC extract's limits */
+ if (pHead > ptr + (fsize - 54))
+ pHead = ptr + (fsize - 54);
+
+ /* TODO: find better method than searching head table's magic */
+ sal_uInt8* p = nullptr;
+ for (p = pHead + 12; p > ptr; --p)
+ {
+ if( p[0]==0x5F && p[1]==0x0F && p[2]==0x3C && p[3]==0xF5 ) {
+ int nDelta = (pHead + 12) - p;
+ if( nDelta )
+ for( int j = 0; j < NUM_TAGS; ++j )
+ if (hasTable(j))
+ m_aTableList[j].pData -= nDelta;
+ break;
+ }
+ }
+ if (p <= ptr)
+ return SFErrCodes::TtFormat;
+ }
+
+ /* Check the table offsets after TTC correction */
+ for (i=0; i<NUM_TAGS; i++) {
+ /* sanity check: table must lay completely within the file
+ * at this point one could check the checksum of all contained
+ * tables, but this would be quite time intensive.
+ * Try to fix tables, so we can cope with minor problems.
+ */
+
+ if (m_aTableList[i].pData < ptr)
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN_IF(m_aTableList[i].pData, "vcl.fonts", "font file " << fileName()
+ << " has bad table offset "
+ << (sal_uInt8*)m_aTableList[i].pData - ptr
+ << "d (tagnum=" << i << ").");
+#endif
+ m_aTableList[i].nSize = 0;
+ m_aTableList[i].pData = nullptr;
+ }
+ else if (const_cast<sal_uInt8*>(m_aTableList[i].pData) + m_aTableList[i].nSize > ptr + fsize)
+ {
+ sal_PtrDiff nMaxLen = (ptr + fsize) - m_aTableList[i].pData;
+ if( nMaxLen < 0 )
+ nMaxLen = 0;
+ m_aTableList[i].nSize = nMaxLen;
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "font file " << fileName()
+ << " has too big table (tagnum=" << i << ").");
+#endif
+ }
+ }
+
+ /* At this point TrueTypeFont is constructed, now need to verify the font format
+ and read the basic font properties */
+
+ return AbstractTrueTypeFont::initialize();
+}
+
+int GetTTGlyphPoints(AbstractTrueTypeFont *ttf, sal_uInt32 glyphID, std::vector<ControlPoint>& pointArray)
+{
+ return GetTTGlyphOutline(ttf, glyphID, pointArray, nullptr, nullptr);
+}
+
+int GetTTGlyphComponents(AbstractTrueTypeFont *ttf, sal_uInt32 glyphID, std::vector< sal_uInt32 >& glyphlist)
+{
+ int n = 1;
+
+ if (glyphID >= ttf->glyphCount())
+ return 0;
+
+ sal_uInt32 glyflength;
+ const sal_uInt8* glyf = ttf->table(O_glyf, glyflength);
+
+ sal_uInt32 nNextOffset = ttf->glyphOffset(glyphID + 1);
+ if (nNextOffset > glyflength)
+ return 0;
+
+ sal_uInt32 nOffset = ttf->glyphOffset(glyphID);
+ if (nOffset > nNextOffset)
+ return 0;
+
+ if (std::find(glyphlist.begin(), glyphlist.end(), glyphID) != glyphlist.end())
+ {
+ SAL_WARN("vcl.fonts", "Endless loop found in a compound glyph.");
+ return 0;
+ }
+
+ glyphlist.push_back( glyphID );
+
+ // Empty glyph.
+ if (nOffset == nNextOffset)
+ return n;
+
+ const auto* ptr = glyf + nOffset;
+ sal_uInt32 nRemainingData = glyflength - nOffset;
+
+ if (nRemainingData >= 10 && GetInt16(ptr, 0) == -1) {
+ sal_uInt16 flags, index;
+ ptr += 10;
+ nRemainingData -= 10;
+ do {
+ if (nRemainingData < 4)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ flags = GetUInt16(ptr, 0);
+ index = GetUInt16(ptr, 2);
+
+ ptr += 4;
+ nRemainingData -= 4;
+ n += GetTTGlyphComponents(ttf, index, glyphlist);
+
+ sal_uInt32 nAdvance;
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ nAdvance = 4;
+ } else {
+ nAdvance = 2;
+ }
+
+ if (flags & WE_HAVE_A_SCALE) {
+ nAdvance += 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ nAdvance += 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ nAdvance += 8;
+ }
+ if (nRemainingData < nAdvance)
+ {
+ SAL_WARN("vcl.fonts", "short read");
+ break;
+ }
+ ptr += nAdvance;
+ nRemainingData -= nAdvance;
+ } while (flags & MORE_COMPONENTS);
+ }
+
+ return n;
+}
+
+SFErrCodes CreateTTFromTTGlyphs(AbstractTrueTypeFont *ttf,
+ std::vector<sal_uInt8>& rOutBuffer,
+ sal_uInt16 const *glyphArray,
+ sal_uInt8 const *encoding,
+ int nGlyphs)
+{
+ std::unique_ptr<TrueTypeTableGeneric> cvt, prep, fpgm, os2;
+ std::unique_ptr<TrueTypeTableName> name;
+ std::unique_ptr<TrueTypeTableMaxp> maxp;
+ std::unique_ptr<TrueTypeTableHhea> hhea;
+ std::unique_ptr<TrueTypeTableHead> head;
+ std::unique_ptr<TrueTypeTableGlyf> glyf;
+ std::unique_ptr<TrueTypeTableCmap> cmap;
+ std::unique_ptr<TrueTypeTablePost> post;
+ int i;
+ SFErrCodes res;
+
+ TrueTypeCreator ttcr(T_true);
+
+ /** name **/
+
+ std::vector<NameRecord> names;
+ GetTTNameRecords(ttf, names);
+ name.reset(new TrueTypeTableName(std::move(names)));
+
+ /** maxp **/
+ sal_uInt32 nTableSize;
+ const sal_uInt8* p = ttf->table(O_maxp, nTableSize);
+ maxp.reset(new TrueTypeTableMaxp(p, nTableSize));
+
+ /** hhea **/
+ p = ttf->table(O_hhea, nTableSize);
+ if (p && nTableSize >= HHEA_caretSlopeRun_offset + 2)
+ hhea.reset(new TrueTypeTableHhea(GetInt16(p, HHEA_ascender_offset), GetInt16(p, HHEA_descender_offset), GetInt16(p, HHEA_lineGap_offset), GetInt16(p, HHEA_caretSlopeRise_offset), GetInt16(p, HHEA_caretSlopeRun_offset)));
+ else
+ hhea.reset(new TrueTypeTableHhea(0, 0, 0, 0, 0));
+
+ /** head **/
+
+ p = ttf->table(O_head, nTableSize);
+ assert(p != nullptr);
+ head.reset(new TrueTypeTableHead(GetInt32(p, HEAD_fontRevision_offset),
+ GetUInt16(p, HEAD_flags_offset),
+ GetUInt16(p, HEAD_unitsPerEm_offset),
+ p+HEAD_created_offset,
+ GetUInt16(p, HEAD_macStyle_offset),
+ GetUInt16(p, HEAD_lowestRecPPEM_offset),
+ GetInt16(p, HEAD_fontDirectionHint_offset)));
+
+ /** glyf **/
+
+ glyf.reset(new TrueTypeTableGlyf());
+ std::unique_ptr<sal_uInt32[]> gID(new sal_uInt32[nGlyphs]);
+
+ for (i = 0; i < nGlyphs; i++) {
+ gID[i] = glyf->glyfAdd(GetTTRawGlyphData(ttf, glyphArray[i]), ttf);
+ }
+
+ /** cmap **/
+ cmap.reset(new TrueTypeTableCmap());
+
+ for (i=0; i < nGlyphs; i++) {
+ cmap->cmapAdd(0x010000, encoding[i], gID[i]);
+ }
+
+ /** cvt **/
+ if ((p = ttf->table(O_cvt, nTableSize)) != nullptr)
+ cvt.reset(new TrueTypeTableGeneric(T_cvt, nTableSize, p));
+
+ /** prep **/
+ if ((p = ttf->table(O_prep, nTableSize)) != nullptr)
+ prep.reset(new TrueTypeTableGeneric(T_prep, nTableSize, p));
+
+ /** fpgm **/
+ if ((p = ttf->table(O_fpgm, nTableSize)) != nullptr)
+ fpgm.reset(new TrueTypeTableGeneric(T_fpgm, nTableSize, p));
+
+ /** post **/
+ if ((p = ttf->table(O_post, nTableSize)) != nullptr)
+ {
+ sal_Int32 nItalic = (POST_italicAngle_offset + 4 < nTableSize) ?
+ GetInt32(p, POST_italicAngle_offset) : 0;
+ sal_Int16 nPosition = (POST_underlinePosition_offset + 2 < nTableSize) ?
+ GetInt16(p, POST_underlinePosition_offset) : 0;
+ sal_Int16 nThickness = (POST_underlineThickness_offset + 2 < nTableSize) ?
+ GetInt16(p, POST_underlineThickness_offset) : 0;
+ sal_uInt32 nFixedPitch = (POST_isFixedPitch_offset + 4 < nTableSize) ?
+ GetUInt32(p, POST_isFixedPitch_offset) : 0;
+
+ post.reset(new TrueTypeTablePost(0x00030000,
+ nItalic, nPosition,
+ nThickness, nFixedPitch));
+ }
+ else
+ post.reset(new TrueTypeTablePost(0x00030000, 0, 0, 0, 0));
+
+ ttcr.AddTable(std::move(name)); ttcr.AddTable(std::move(maxp)); ttcr.AddTable(std::move(hhea));
+ ttcr.AddTable(std::move(head)); ttcr.AddTable(std::move(glyf)); ttcr.AddTable(std::move(cmap));
+ ttcr.AddTable(std::move(cvt)); ttcr.AddTable(std::move(prep)); ttcr.AddTable(std::move(fpgm));
+ ttcr.AddTable(std::move(post)); ttcr.AddTable(std::move(os2));
+
+ res = ttcr.StreamToMemory(rOutBuffer);
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN_IF(res != SFErrCodes::Ok, "vcl.fonts", "StreamToMemory: error code: "
+ << (int) res << ".");
+#endif
+
+ return res;
+}
+
+namespace
+{
+void FillFontSubsetInfo(AbstractTrueTypeFont* ttf, FontSubsetInfo& rInfo)
+{
+ TTGlobalFontInfo aTTInfo;
+ GetTTGlobalFontInfo(ttf, &aTTInfo);
+
+ rInfo.m_aPSName = OUString::fromUtf8(aTTInfo.psname);
+ rInfo.m_nFontType = FontType::SFNT_TTF;
+ rInfo.m_aFontBBox
+ = tools::Rectangle(Point(aTTInfo.xMin, aTTInfo.yMin), Point(aTTInfo.xMax, aTTInfo.yMax));
+ rInfo.m_nCapHeight = aTTInfo.yMax; // Well ...
+ rInfo.m_nAscent = aTTInfo.winAscent;
+ rInfo.m_nDescent = aTTInfo.winDescent;
+
+ // mac fonts usually do not have an OS2-table
+ // => get valid ascent/descent values from other tables
+ if (!rInfo.m_nAscent)
+ rInfo.m_nAscent = +aTTInfo.typoAscender;
+ if (!rInfo.m_nAscent)
+ rInfo.m_nAscent = +aTTInfo.ascender;
+ if (!rInfo.m_nDescent)
+ rInfo.m_nDescent = +aTTInfo.typoDescender;
+ if (!rInfo.m_nDescent)
+ rInfo.m_nDescent = -aTTInfo.descender;
+
+ rInfo.m_bFilled = true;
+}
+
+bool CreateCFFfontSubset(const unsigned char* pFontBytes, int nByteLength,
+ std::vector<sal_uInt8>& rOutBuffer, const sal_GlyphId* pGlyphIds,
+ const sal_uInt8* pEncoding, int nGlyphCount, FontSubsetInfo& rInfo)
+{
+ utl::TempFileFast aTempFile;
+ SvStream* pStream = aTempFile.GetStream(StreamMode::READWRITE);
+
+ rInfo.LoadFont(FontType::CFF_FONT, pFontBytes, nByteLength);
+ bool bRet = rInfo.CreateFontSubset(FontType::TYPE1_PFB, pStream, nullptr, pGlyphIds, pEncoding,
+ nGlyphCount);
+
+ if (bRet)
+ {
+ rOutBuffer.resize(pStream->TellEnd());
+ pStream->Seek(0);
+ auto nRead = pStream->ReadBytes(rOutBuffer.data(), rOutBuffer.size());
+ if (nRead != rOutBuffer.size())
+ {
+ rOutBuffer.clear();
+ return false;
+ }
+ }
+
+ return bRet;
+}
+}
+
+bool CreateTTFfontSubset(vcl::AbstractTrueTypeFont& rTTF, std::vector<sal_uInt8>& rOutBuffer,
+ const sal_GlyphId* pGlyphIds, const sal_uInt8* pEncoding,
+ const int nOrigGlyphCount, FontSubsetInfo& rInfo)
+{
+ // Get details about the subset font.
+ FillFontSubsetInfo(&rTTF, rInfo);
+
+ // Shortcut for CFF-subsetting.
+ sal_uInt32 nCFF;
+ const sal_uInt8* pCFF = rTTF.table(O_CFF, nCFF);
+ if (nCFF)
+ return CreateCFFfontSubset(pCFF, nCFF, rOutBuffer, pGlyphIds, pEncoding,
+ nOrigGlyphCount, rInfo);
+
+ // Multiple questions:
+ // - Why is there a glyph limit?
+ // MacOS used to handle 257 glyphs...
+ // Also the much more complex PrintFontManager variant has this limit.
+ // Also the very first implementation has the limit in
+ // commit 8789ed701e98031f2a1657ea0dfd6f7a0b050992
+ // - Why doesn't the PrintFontManager care about the fake glyph? It
+ // is used on all unx platforms to create the subset font.
+ // - Should the SAL_WARN actually be asserts, like on MacOS?
+ if (nOrigGlyphCount > 256)
+ {
+ SAL_WARN("vcl.fonts", "too many glyphs for subsetting");
+ return false;
+ }
+
+ int nGlyphCount = nOrigGlyphCount;
+ sal_uInt16 aShortIDs[256];
+ sal_uInt8 aTempEncs[256];
+
+ // handle the undefined / first font glyph
+ int nNotDef = -1, i;
+ for (i = 0; i < nGlyphCount; ++i)
+ {
+ aTempEncs[i] = pEncoding[i];
+ aShortIDs[i] = static_cast<sal_uInt16>(pGlyphIds[i]);
+ if (!aShortIDs[i])
+ if (nNotDef < 0)
+ nNotDef = i;
+ }
+
+ // nNotDef glyph must be in pos 0 => swap glyphids
+ if (nNotDef != 0)
+ {
+ if (nNotDef < 0)
+ {
+ if (nGlyphCount == 256)
+ {
+ SAL_WARN("vcl.fonts", "too many glyphs for subsetting");
+ return false;
+ }
+ nNotDef = nGlyphCount++;
+ }
+
+ aShortIDs[nNotDef] = aShortIDs[0];
+ aTempEncs[nNotDef] = aTempEncs[0];
+ aShortIDs[0] = 0;
+ aTempEncs[0] = 0;
+ }
+
+ // write subset into destination file
+ return (CreateTTFromTTGlyphs(&rTTF, rOutBuffer, aShortIDs, aTempEncs, nGlyphCount)
+ == vcl::SFErrCodes::Ok);
+}
+
+bool GetTTGlobalFontHeadInfo(const AbstractTrueTypeFont *ttf, int& xMin, int& yMin, int& xMax, int& yMax, sal_uInt16& macStyle)
+{
+ sal_uInt32 table_size;
+ const sal_uInt8* table = ttf->table(O_head, table_size);
+ if (table_size < 46)
+ return false;
+
+ const int UPEm = ttf->unitsPerEm();
+ if (UPEm == 0)
+ return false;
+ xMin = XUnits(UPEm, GetInt16(table, HEAD_xMin_offset));
+ yMin = XUnits(UPEm, GetInt16(table, HEAD_yMin_offset));
+ xMax = XUnits(UPEm, GetInt16(table, HEAD_xMax_offset));
+ yMax = XUnits(UPEm, GetInt16(table, HEAD_yMax_offset));
+ macStyle = GetUInt16(table, HEAD_macStyle_offset);
+ return true;
+}
+
+void GetTTGlobalFontInfo(AbstractTrueTypeFont *ttf, TTGlobalFontInfo *info)
+{
+ int UPEm = ttf->unitsPerEm();
+
+ info->family = ttf->family;
+ info->ufamily = ttf->ufamily;
+ info->subfamily = ttf->subfamily;
+ info->usubfamily = ttf->usubfamily;
+ info->psname = ttf->psname;
+ info->microsoftSymbolEncoded = ttf->IsMicrosoftSymbolEncoded();
+
+ sal_uInt32 table_size;
+ const sal_uInt8* table = ttf->table(O_OS2, table_size);
+ if (table_size >= 42)
+ {
+ info->weight = GetUInt16(table, OS2_usWeightClass_offset);
+ info->width = GetUInt16(table, OS2_usWidthClass_offset);
+
+ if (table_size >= OS2_V0_length && UPEm != 0) {
+ info->typoAscender = XUnits(UPEm,GetInt16(table, OS2_typoAscender_offset));
+ info->typoDescender = XUnits(UPEm, GetInt16(table, OS2_typoDescender_offset));
+ info->typoLineGap = XUnits(UPEm, GetInt16(table, OS2_typoLineGap_offset));
+ info->winAscent = XUnits(UPEm, GetUInt16(table, OS2_winAscent_offset));
+ info->winDescent = XUnits(UPEm, GetUInt16(table, OS2_winDescent_offset));
+ /* sanity check; some fonts treat winDescent as signed
+ * violating the standard */
+ if( info->winDescent > 5*UPEm )
+ info->winDescent = XUnits(UPEm, GetInt16(table, OS2_winDescent_offset));
+ }
+ memcpy(info->panose, table + OS2_panose_offset, OS2_panoseNbBytes_offset);
+ info->typeFlags = GetUInt16( table, OS2_fsType_offset );
+ }
+
+ table = ttf->table(O_post, table_size);
+ if (table_size >= 12 + sizeof(sal_uInt32))
+ {
+ info->pitch = GetUInt32(table, POST_isFixedPitch_offset);
+ info->italicAngle = GetInt32(table, POST_italicAngle_offset);
+ }
+
+ GetTTGlobalFontHeadInfo(ttf, info->xMin, info->yMin, info->xMax, info->yMax, info->macStyle);
+
+ table = ttf->table(O_hhea, table_size);
+ if (table_size >= 10 && UPEm != 0)
+ {
+ info->ascender = XUnits(UPEm, GetInt16(table, HHEA_ascender_offset));
+ info->descender = XUnits(UPEm, GetInt16(table, HHEA_descender_offset));
+ info->linegap = XUnits(UPEm, GetInt16(table, HHEA_lineGap_offset));
+ }
+}
+
+std::unique_ptr<GlyphData> GetTTRawGlyphData(AbstractTrueTypeFont *ttf, sal_uInt32 glyphID)
+{
+ if (glyphID >= ttf->glyphCount())
+ return nullptr;
+
+ sal_uInt32 hmtxlength;
+ const sal_uInt8* hmtx = ttf->table(O_hmtx, hmtxlength);
+
+ if (!hmtxlength)
+ return nullptr;
+
+ sal_uInt32 glyflength;
+ const sal_uInt8* glyf = ttf->table(O_glyf, glyflength);
+ int n;
+
+ /* #127161# check the glyph offsets */
+ sal_uInt32 nNextOffset = ttf->glyphOffset(glyphID + 1);
+ if (nNextOffset > glyflength)
+ return nullptr;
+
+ sal_uInt32 nOffset = ttf->glyphOffset(glyphID);
+ if (nOffset > nNextOffset)
+ return nullptr;
+
+ sal_uInt32 length = nNextOffset - nOffset;
+
+ std::unique_ptr<GlyphData> d(new GlyphData);
+
+ if (length > 0) {
+ const sal_uInt8* srcptr = glyf + ttf->glyphOffset(glyphID);
+ const size_t nChunkLen = ((length + 1) & ~1);
+ d->ptr.reset(new sal_uInt8[nChunkLen]);
+ memcpy(d->ptr.get(), srcptr, length);
+ memset(d->ptr.get() + length, 0, nChunkLen - length);
+ d->compflag = (GetInt16( srcptr, 0 ) < 0);
+ } else {
+ d->ptr = nullptr;
+ d->compflag = false;
+ }
+
+ d->glyphID = glyphID;
+ d->nbytes = static_cast<sal_uInt16>((length + 1) & ~1);
+
+ /* now calculate npoints and ncontours */
+ std::vector<ControlPoint> cp;
+ n = GetTTGlyphPoints(ttf, glyphID, cp);
+ if (n > 0)
+ {
+ int m = 0;
+ for (int i = 0; i < n; i++)
+ {
+ if (cp[i].flags & 0x8000)
+ m++;
+ }
+ d->npoints = static_cast<sal_uInt16>(n);
+ d->ncontours = static_cast<sal_uInt16>(m);
+ } else {
+ d->npoints = 0;
+ d->ncontours = 0;
+ }
+
+ /* get advance width and left sidebearing */
+ sal_uInt32 nAwOffset;
+ sal_uInt32 nLsboffset;
+ if (glyphID < ttf->horzMetricCount()) {
+ nAwOffset = 4 * glyphID;
+ nLsboffset = 4 * glyphID + 2;
+ } else {
+ nAwOffset = 4 * (ttf->horzMetricCount() - 1);
+ nLsboffset = (ttf->horzMetricCount() * 4) + ((glyphID - ttf->horzMetricCount()) * 2);
+ }
+
+ if (nAwOffset + 2 <= hmtxlength)
+ d->aw = GetUInt16(hmtx, nAwOffset);
+ else
+ {
+ SAL_WARN("vcl.fonts", "hmtx offset " << nAwOffset << " not available");
+ d->aw = 0;
+ }
+ if (nLsboffset + 2 <= hmtxlength)
+ d->lsb = GetInt16(hmtx, nLsboffset);
+ else
+ {
+ SAL_WARN("vcl.fonts", "hmtx offset " << nLsboffset << " not available");
+ d->lsb = 0;
+ }
+
+ return d;
+}
+
+void GetTTNameRecords(AbstractTrueTypeFont const *ttf, std::vector<NameRecord>& nr)
+{
+ sal_uInt32 nTableSize;
+ const sal_uInt8* table = ttf->table(O_name, nTableSize);
+
+ nr.clear();
+
+ if (nTableSize < 6)
+ {
+#if OSL_DEBUG_LEVEL > 1
+ SAL_WARN("vcl.fonts", "O_name table too small.");
+#endif
+ return;
+ }
+
+ sal_uInt16 n = GetUInt16(table, 2);
+ sal_uInt32 nStrBase = GetUInt16(table, 4);
+ int i;
+
+ if (n == 0) return;
+
+ const sal_uInt32 remaining_table_size = nTableSize-6;
+ const sal_uInt32 nMinRecordSize = 12;
+ const sal_uInt32 nMaxRecords = remaining_table_size / nMinRecordSize;
+ if (n > nMaxRecords)
+ {
+ SAL_WARN("vcl.fonts", "Parsing error in " << OUString::createFromAscii(ttf->fileName()) <<
+ ": " << nMaxRecords << " max possible entries, but " <<
+ n << " claimed, truncating");
+ n = nMaxRecords;
+ }
+
+ nr.resize(n);
+
+ for (i = 0; i < n; i++) {
+ sal_uInt32 nLargestFixedOffsetPos = 6 + 10 + 12 * i;
+ sal_uInt32 nMinSize = nLargestFixedOffsetPos + sizeof(sal_uInt16);
+ if (nMinSize > nTableSize)
+ {
+ SAL_WARN( "vcl.fonts", "Font " << OUString::createFromAscii(ttf->fileName()) << " claimed to have "
+ << n << " name records, but only space for " << i);
+ break;
+ }
+
+ nr[i].platformID = GetUInt16(table, 6 + 0 + 12 * i);
+ nr[i].encodingID = GetUInt16(table, 6 + 2 + 12 * i);
+ nr[i].languageID = LanguageType(GetUInt16(table, 6 + 4 + 12 * i));
+ nr[i].nameID = GetUInt16(table, 6 + 6 + 12 * i);
+ sal_uInt16 slen = GetUInt16(table, 6 + 8 + 12 * i);
+ sal_uInt32 nStrOffset = GetUInt16(table, nLargestFixedOffsetPos);
+ if (slen) {
+ if (nStrBase + nStrOffset + slen >= nTableSize)
+ continue;
+
+ const sal_uInt32 rec_string = nStrBase + nStrOffset;
+ const size_t available_space = rec_string > nTableSize ? 0 : (nTableSize - rec_string);
+ if (slen <= available_space)
+ {
+ nr[i].sptr.resize(slen);
+ memcpy(nr[i].sptr.data(), table + rec_string, slen);
+ }
+ }
+ // some fonts have 3.0 names => fix them to 3.1
+ if( (nr[i].platformID == 3) && (nr[i].encodingID == 0) )
+ nr[i].encodingID = 1;
+ }
+}
+
+template<size_t N> static void
+append(std::bitset<N> & rSet, size_t const nOffset, sal_uInt32 const nValue)
+{
+ for (size_t i = 0; i < 32; ++i)
+ {
+ rSet.set(nOffset + i, (nValue & (1U << i)) != 0);
+ }
+}
+
+bool getTTCoverage(
+ std::optional<std::bitset<UnicodeCoverage::MAX_UC_ENUM>> &rUnicodeRange,
+ std::optional<std::bitset<CodePageCoverage::MAX_CP_ENUM>> &rCodePageRange,
+ const unsigned char* pTable, size_t nLength)
+{
+ bool bRet = false;
+ // parse OS/2 header
+ if (nLength >= OS2_Legacy_length)
+ {
+ rUnicodeRange = std::bitset<UnicodeCoverage::MAX_UC_ENUM>();
+ append(*rUnicodeRange, 0, GetUInt32(pTable, OS2_ulUnicodeRange1_offset));
+ append(*rUnicodeRange, 32, GetUInt32(pTable, OS2_ulUnicodeRange2_offset));
+ append(*rUnicodeRange, 64, GetUInt32(pTable, OS2_ulUnicodeRange3_offset));
+ append(*rUnicodeRange, 96, GetUInt32(pTable, OS2_ulUnicodeRange4_offset));
+ bRet = true;
+ if (nLength >= OS2_V1_length)
+ {
+ rCodePageRange = std::bitset<CodePageCoverage::MAX_CP_ENUM>();
+ append(*rCodePageRange, 0, GetUInt32(pTable, OS2_ulCodePageRange1_offset));
+ append(*rCodePageRange, 32, GetUInt32(pTable, OS2_ulCodePageRange2_offset));
+ }
+ }
+ return bRet;
+}
+
+} // namespace vcl
+
+int TestFontSubset(const void* data, sal_uInt32 size)
+{
+ int nResult = -1;
+ vcl::TrueTypeFont* pTTF = nullptr;
+ if (OpenTTFontBuffer(data, size, 0, &pTTF) == vcl::SFErrCodes::Ok)
+ {
+ vcl::TTGlobalFontInfo aInfo;
+ GetTTGlobalFontInfo(pTTF, &aInfo);
+
+ sal_uInt16 aGlyphIds[ 256 ] = {};
+ sal_uInt8 aEncoding[ 256 ] = {};
+
+ for (sal_uInt16 c = 32; c < 256; ++c)
+ {
+ aEncoding[c] = c;
+ aGlyphIds[c] = c - 31;
+ }
+
+ std::vector<sal_uInt8> aBuffer;
+ CreateTTFromTTGlyphs(pTTF, aBuffer, aGlyphIds, aEncoding, 256);
+
+
+ // cleanup
+ CloseTTFont( pTTF );
+ // success
+ nResult = 0;
+ }
+
+ return nResult;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/ttcr.cxx b/vcl/source/fontsubset/ttcr.cxx
new file mode 100644
index 0000000000..84a0375c80
--- /dev/null
+++ b/vcl/source/fontsubset/ttcr.cxx
@@ -0,0 +1,1136 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*
+ * TrueTypeCreator method implementation
+ */
+
+#include <iomanip>
+#include <assert.h>
+
+#include <sal/log.hxx>
+
+#include "ttcr.hxx"
+#include <string.h>
+
+namespace vcl
+{
+
+/*
+ * Private Data Types
+ */
+
+struct TableEntry {
+ sal_uInt32 tag;
+ sal_uInt32 length;
+ sal_uInt8 *data;
+};
+
+/*- Data access macros for data stored in big-endian or little-endian format */
+static sal_Int16 GetInt16( const sal_uInt8* ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+ sal_Int16 t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+ return t;
+}
+
+static sal_uInt16 GetUInt16( const sal_uInt8* ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+ sal_uInt16 t = (ptr+offset)[0] << 8 | (ptr+offset)[1];
+ return t;
+}
+
+static void PutInt16(sal_Int16 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static void PutUInt16(sal_uInt16 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static void PutUInt32(sal_uInt32 val, sal_uInt8 *ptr, sal_uInt32 offset)
+{
+ assert(ptr != nullptr);
+
+ ptr[offset] = static_cast<sal_uInt8>((val >> 24) & 0xFF);
+ ptr[offset+1] = static_cast<sal_uInt8>((val >> 16) & 0xFF);
+ ptr[offset+2] = static_cast<sal_uInt8>((val >> 8) & 0xFF);
+ ptr[offset+3] = static_cast<sal_uInt8>(val & 0xFF);
+}
+
+static int TableEntryCompareF(const void *l, const void *r)
+{
+ sal_uInt32 const ltag(static_cast<TableEntry const*>(l)->tag);
+ sal_uInt32 const rtag(static_cast<TableEntry const*>(r)->tag);
+ return (ltag == rtag) ? 0 : (ltag < rtag) ? -1 : 1;
+}
+
+namespace {
+struct NameRecordCompareF
+{
+ bool operator()(const NameRecord& l, const NameRecord& r) const
+ {
+ if (l.platformID != r.platformID) {
+ return l.platformID < r.platformID;
+ } else if (l.encodingID != r.encodingID) {
+ return l.encodingID < r.encodingID;
+ } else if (l.languageID != r.languageID) {
+ return l.languageID < r.languageID;
+ } else if (l.nameID != r.nameID) {
+ return l.nameID < r.nameID;
+ }
+ return false;
+ }
+};
+}
+
+static sal_uInt32 CheckSum(sal_uInt32 *ptr, sal_uInt32 length)
+{
+ sal_uInt32 sum = 0;
+ sal_uInt32 *endptr = ptr + ((length + 3) & sal_uInt32(~3)) / 4;
+
+ while (ptr < endptr) sum += *ptr++;
+
+ return sum;
+}
+
+/*
+ * Public functions
+ */
+
+TrueTypeCreator::TrueTypeCreator(sal_uInt32 _tag)
+{
+ this->m_tag = _tag;
+}
+
+void TrueTypeCreator::AddTable(std::unique_ptr<TrueTypeTable> table)
+{
+ if (table != nullptr) {
+ this->m_tables.push_back(std::move(table));
+ }
+}
+
+void TrueTypeCreator::RemoveTable(sal_uInt32 tableTag)
+{
+ for (auto it = this->m_tables.begin(); it != this->m_tables.end(); )
+ {
+ if ((*it)->m_tag == tableTag)
+ {
+ it = this->m_tables.erase(it);
+ }
+ else
+ ++it;
+ }
+}
+
+SFErrCodes TrueTypeCreator::StreamToMemory(std::vector<sal_uInt8>& rOutBuffer)
+{
+ sal_uInt16 searchRange=1, entrySelector=0, rangeShift;
+ sal_uInt32 s, offset, checkSumAdjustment = 0;
+ sal_uInt32 *p;
+ sal_uInt8 *head = nullptr; /* saved pointer to the head table data for checkSumAdjustment calculation */
+
+ if (this->m_tables.empty())
+ return SFErrCodes::TtFormat;
+
+ ProcessTables();
+
+ /* ProcessTables() adds 'loca' and 'hmtx' */
+
+ sal_uInt16 numTables = this->m_tables.size();
+
+ std::unique_ptr<TableEntry[]> te(new TableEntry[numTables]);
+
+ int teIdx = 0;
+ for (auto const & e : this->m_tables)
+ {
+ e->GetRawData(&te[teIdx]);
+ ++teIdx;
+ }
+
+ qsort(te.get(), numTables, sizeof(TableEntry), TableEntryCompareF);
+
+ do {
+ searchRange *= 2;
+ entrySelector++;
+ } while (searchRange <= numTables);
+
+ searchRange *= 8;
+ entrySelector--;
+ rangeShift = numTables * 16 - searchRange;
+
+ s = offset = 12 + 16 * numTables;
+
+ for (int i = 0; i < numTables; ++i) {
+ s += (te[i].length + 3) & sal_uInt32(~3);
+ /* if ((te[i].length & 3) != 0) s += (4 - (te[i].length & 3)) & 3; */
+ }
+
+ rOutBuffer.resize(s);
+ sal_uInt8* ttf = rOutBuffer.data();
+
+ /* Offset Table */
+ PutUInt32(this->m_tag, ttf, 0);
+ PutUInt16(numTables, ttf, 4);
+ PutUInt16(searchRange, ttf, 6);
+ PutUInt16(entrySelector, ttf, 8);
+ PutUInt16(rangeShift, ttf, 10);
+
+ /* Table Directory */
+ for (int i = 0; i < numTables; ++i) {
+ PutUInt32(te[i].tag, ttf + 12, 16 * i);
+ PutUInt32(CheckSum(reinterpret_cast<sal_uInt32 *>(te[i].data), te[i].length), ttf + 12, 16 * i + 4);
+ PutUInt32(offset, ttf + 12, 16 * i + 8);
+ PutUInt32(te[i].length, ttf + 12, 16 * i + 12);
+
+ if (te[i].tag == T_head) {
+ head = ttf + offset;
+ }
+
+ memcpy(ttf+offset, te[i].data, (te[i].length + 3) & sal_uInt32(~3) );
+ offset += (te[i].length + 3) & sal_uInt32(~3);
+ /* if ((te[i].length & 3) != 0) offset += (4 - (te[i].length & 3)) & 3; */
+ }
+
+ te.reset();
+
+ p = reinterpret_cast<sal_uInt32 *>(ttf);
+ for (int i = 0; i < static_cast<int>(s) / 4; ++i) checkSumAdjustment += p[i];
+ PutUInt32(0xB1B0AFBA - checkSumAdjustment, head, 8);
+
+ return SFErrCodes::Ok;
+}
+
+/*
+ * TrueTypeTable private methods
+ */
+
+/* Table data points to
+ * --------------------------------------------
+ * generic tdata_generic struct
+ * 'head' HEAD_Length bytes of memory
+ * 'hhea' HHEA_Length bytes of memory
+ * 'loca' tdata_loca struct
+ * 'maxp' MAXP_Version1Length bytes of memory
+ * 'glyf' list of GlyphData structs (defined in sft.h)
+ * 'name' list of NameRecord structs (defined in sft.h)
+ * 'post' tdata_post struct
+ *
+ */
+
+#define CMAP_SUBTABLE_INIT 10
+#define CMAP_SUBTABLE_INCR 10
+
+namespace {
+
+struct CmapSubTable {
+ sal_uInt32 id; /* subtable ID (platform/encoding ID) */
+ std::vector<std::pair<sal_uInt32, sal_uInt32>> mappings; /* character to glyph mapping array */
+};
+
+}
+
+struct table_cmap {
+ sal_uInt32 n; /* number of used CMAP sub-tables */
+ sal_uInt32 m; /* number of allocated CMAP sub-tables */
+ std::unique_ptr<CmapSubTable[]> s; /* sorted array of sub-tables */
+};
+
+struct tdata_loca {
+ sal_uInt32 nbytes; /* number of bytes in loca table */
+ std::unique_ptr<sal_uInt8[]> ptr; /* pointer to the data */
+};
+
+/* allocate memory for a TT table */
+static std::unique_ptr<sal_uInt8[]> ttmalloc(sal_uInt32 nbytes)
+{
+ sal_uInt32 n = (nbytes + 3) & sal_uInt32(~3);
+ return std::make_unique<sal_uInt8[]>(n);
+}
+
+TrueTypeTable::~TrueTypeTable() {}
+
+TrueTypeTableGeneric::~TrueTypeTableGeneric()
+{
+}
+
+TrueTypeTableHead::~TrueTypeTableHead()
+{
+}
+
+TrueTypeTableHhea::~TrueTypeTableHhea()
+{
+}
+
+TrueTypeTableLoca::~TrueTypeTableLoca()
+{
+}
+
+TrueTypeTableMaxp::~TrueTypeTableMaxp()
+{
+}
+
+TrueTypeTableGlyf::~TrueTypeTableGlyf()
+{
+}
+
+TrueTypeTableCmap::~TrueTypeTableCmap()
+{
+}
+
+TrueTypeTableName::~TrueTypeTableName()
+{
+}
+
+TrueTypeTablePost::~TrueTypeTablePost()
+{
+ if (m_format == 0x00030000) {
+ /* do nothing */
+ } else {
+ SAL_WARN("vcl.fonts", "Unsupported format of a 'post' table: "
+ << std::setfill('0')
+ << std::setw(8)
+ << std::hex
+ << std::uppercase
+ << static_cast<int>(m_format) << ".");
+ }
+}
+
+
+int TrueTypeTableGeneric::GetRawData(TableEntry* te)
+{
+ te->data = this->m_ptr.get();
+ te->length = this->m_nbytes;
+ te->tag = this->m_tag;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableHead::GetRawData(TableEntry* te)
+{
+ te->length = HEAD_Length;
+ te->data = this->m_head.get();
+ te->tag = T_head;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableHhea::GetRawData(TableEntry* te)
+{
+ te->length = HHEA_Length;
+ te->data = this->m_hhea.get();
+ te->tag = T_hhea;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableLoca::GetRawData(TableEntry* te)
+{
+ assert(this->m_loca != nullptr);
+
+ if (m_loca->nbytes == 0) return TTCR_ZEROGLYPHS;
+
+ te->data = m_loca->ptr.get();
+ te->length = m_loca->nbytes;
+ te->tag = T_loca;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableMaxp::GetRawData(TableEntry* te)
+{
+ te->length = MAXP_Version1Length;
+ te->data = this->m_maxp.get();
+ te->tag = T_maxp;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableGlyf::GetRawData(TableEntry* te)
+{
+ sal_uInt32 n, nbytes = 0;
+ /* sal_uInt16 curID = 0; */ /* to check if glyph IDs are sequential and start from zero */
+
+ te->data = nullptr;
+ te->length = 0;
+ te->tag = 0;
+
+ if (m_list.size() == 0) return TTCR_ZEROGLYPHS;
+
+ for (const std::unique_ptr<GlyphData>& pGlyph : m_list)
+ {
+ /* if (((GlyphData *) listCurrent(l))->glyphID != curID++) return TTCR_GLYPHSEQ; */
+ nbytes += pGlyph->nbytes;
+ }
+
+ m_rawdata = ttmalloc(nbytes);
+
+ auto p = m_rawdata.get();
+ for (const std::unique_ptr<GlyphData>& pGlyph : m_list)
+ {
+ n = pGlyph->nbytes;
+ if (n != 0) {
+ memcpy(p, pGlyph->ptr.get(), n);
+ p += n;
+ }
+ }
+
+ te->length = nbytes;
+ te->data = m_rawdata.get();
+ te->tag = T_glyf;
+
+ return TTCR_OK;
+}
+
+/* cmap packers */
+static std::unique_ptr<sal_uInt8[]> PackCmapType0(CmapSubTable const *s, sal_uInt32 *length)
+{
+ std::unique_ptr<sal_uInt8[]> ptr(new sal_uInt8[262]);
+ sal_uInt8 *p = ptr.get() + 6;
+
+ PutUInt16(0, ptr.get(), 0);
+ PutUInt16(262, ptr.get(), 2);
+ PutUInt16(0, ptr.get(), 4);
+
+ for (sal_uInt32 i = 0; i < 256; i++) {
+ sal_uInt16 g = 0;
+ for (const auto& [ch, glyph] : s->mappings) {
+ if (ch == i) {
+ g = static_cast<sal_uInt16>(glyph);
+ }
+ }
+ p[i] = static_cast<sal_uInt8>(g);
+ }
+ *length = 262;
+ return ptr;
+}
+
+static std::unique_ptr<sal_uInt8[]> PackCmapType6(CmapSubTable const *s, sal_uInt32 *length)
+{
+ std::unique_ptr<sal_uInt8[]> ptr(new sal_uInt8[s->mappings.size()*2 + 10]);
+ sal_uInt8 *p = ptr.get() + 10;
+
+ PutUInt16(6, ptr.get(), 0);
+ PutUInt16(static_cast<sal_uInt16>(s->mappings.size()*2+10), ptr.get(), 2);
+ PutUInt16(0, ptr.get(), 4);
+ PutUInt16(0, ptr.get(), 6);
+ PutUInt16(static_cast<sal_uInt16>(s->mappings.size()), ptr.get(), 8 );
+
+ for (size_t i = 0; i < s->mappings.size(); i++) {
+ sal_uInt16 g = 0;
+ for (const auto& [ch, glyph] : s->mappings) {
+ if (ch == i) {
+ g = static_cast<sal_uInt16>(glyph);
+ }
+ }
+ PutUInt16( g, p, 2*i );
+ }
+ *length = s->mappings.size()*2+10;
+ return ptr;
+}
+
+/* XXX it only handles Format 0 encoding tables */
+static std::unique_ptr<sal_uInt8[]> PackCmap(CmapSubTable const *s, sal_uInt32 *length)
+{
+ if (s->mappings.back().second > 0xff)
+ return PackCmapType6(s, length);
+ else
+ return PackCmapType0(s, length);
+}
+
+int TrueTypeTableCmap::GetRawData(TableEntry* te)
+{
+ sal_uInt32 i;
+ sal_uInt32 tlen = 0;
+ sal_uInt32 l;
+ sal_uInt32 cmapsize;
+ sal_uInt8 *cmap;
+ sal_uInt32 coffset;
+
+ assert(m_cmap);
+ assert(m_cmap->n != 0);
+
+ std::unique_ptr<std::unique_ptr<sal_uInt8[]>[]> subtables(new std::unique_ptr<sal_uInt8[]>[m_cmap->n]);
+ std::unique_ptr<sal_uInt32[]> sizes(new sal_uInt32[m_cmap->n]);
+
+ for (i = 0; i < m_cmap->n; i++) {
+ subtables[i] = PackCmap(m_cmap->s.get()+i, &l);
+ sizes[i] = l;
+ tlen += l;
+ }
+
+ cmapsize = tlen + 4 + 8 * m_cmap->n;
+ this->m_rawdata = ttmalloc(cmapsize);
+ cmap = this->m_rawdata.get();
+
+ PutUInt16(0, cmap, 0);
+ PutUInt16(static_cast<sal_uInt16>(m_cmap->n), cmap, 2);
+ coffset = 4 + m_cmap->n * 8;
+
+ for (i = 0; i < m_cmap->n; i++) {
+ PutUInt16(static_cast<sal_uInt16>(m_cmap->s[i].id >> 16), cmap + 4, i * 8);
+ PutUInt16(static_cast<sal_uInt16>(m_cmap->s[i].id & 0xFF), cmap + 4, 2 + i * 8);
+ PutUInt32(coffset, cmap + 4, 4 + i * 8);
+ memcpy(cmap + coffset, subtables[i].get(), sizes[i]);
+ subtables[i].reset();
+ coffset += sizes[i];
+ }
+
+ subtables.reset();
+ sizes.reset();
+
+ te->data = cmap;
+ te->length = cmapsize;
+ te->tag = T_cmap;
+
+ return TTCR_OK;
+}
+
+int TrueTypeTableName::GetRawData(TableEntry* te)
+{
+ sal_Int16 i=0, n; /* number of Name Records */
+ int stringLen = 0;
+ sal_uInt8 *p1, *p2;
+
+ te->data = nullptr;
+ te->length = 0;
+ te->tag = 0;
+
+ if ((n = static_cast<sal_Int16>(m_list.size())) == 0) return TTCR_NONAMES;
+
+ std::vector<NameRecord> nr = m_list;
+
+ for (const NameRecord & rName : m_list)
+ stringLen += rName.sptr.size();
+
+ if (stringLen > 65535) {
+ return TTCR_NAMETOOLONG;
+ }
+
+ std::sort(nr.begin(), nr.end(), NameRecordCompareF());
+
+ int nameLen = stringLen + 12 * n + 6;
+ std::unique_ptr<sal_uInt8[]> name = ttmalloc(nameLen);
+
+ PutUInt16(0, name.get(), 0);
+ PutUInt16(n, name.get(), 2);
+ PutUInt16(static_cast<sal_uInt16>(6 + 12 * n), name.get(), 4);
+
+ p1 = name.get() + 6;
+ p2 = p1 + 12 * n;
+
+ for (i = 0; i < n; i++) {
+ PutUInt16(nr[i].platformID, p1, 0);
+ PutUInt16(nr[i].encodingID, p1, 2);
+ PutUInt16(static_cast<sal_uInt16>(nr[i].languageID), p1, 4);
+ PutUInt16(nr[i].nameID, p1, 6);
+ PutUInt16(nr[i].sptr.size(), p1, 8);
+ PutUInt16(static_cast<sal_uInt16>(p2 - (name.get() + 6 + 12 * n)), p1, 10);
+ if (nr[i].sptr.size()) {
+ memcpy(p2, nr[i].sptr.data(), nr[i].sptr.size());
+ }
+ /* {int j; for(j=0; j<nr[i].slen; j++) printf("%c", nr[i].sptr[j]); printf("\n"); }; */
+ p2 += nr[i].sptr.size();
+ p1 += 12;
+ }
+
+ nr.clear();
+ this->m_rawdata = std::move(name);
+
+ te->data = this->m_rawdata.get();
+ te->length = static_cast<sal_uInt16>(nameLen);
+ te->tag = T_name;
+
+ /*{int j; for(j=0; j<nameLen; j++) printf("%c", name[j]); }; */
+
+ return TTCR_OK;
+}
+
+int TrueTypeTablePost::GetRawData(TableEntry* te)
+{
+ std::unique_ptr<sal_uInt8[]> post;
+ sal_uInt32 postLen = 0;
+ int ret;
+
+ this->m_rawdata.reset();
+
+ if (m_format == 0x00030000) {
+ postLen = 32;
+ post = ttmalloc(postLen);
+ PutUInt32(0x00030000, post.get(), 0);
+ PutUInt32(m_italicAngle, post.get(), 4);
+ PutUInt16(m_underlinePosition, post.get(), 8);
+ PutUInt16(m_underlineThickness, post.get(), 10);
+ PutUInt16(static_cast<sal_uInt16>(m_isFixedPitch), post.get(), 12);
+ ret = TTCR_OK;
+ } else {
+ SAL_WARN("vcl.fonts", "Unrecognized format of a post table: "
+ << std::setfill('0')
+ << std::setw(8)
+ << std::hex
+ << std::uppercase
+ << static_cast<int>(m_format) << ".");
+ ret = TTCR_POSTFORMAT;
+ }
+
+ this->m_rawdata = std::move(post);
+ te->data = this->m_rawdata.get();
+ te->length = postLen;
+ te->tag = T_post;
+
+ return ret;
+}
+
+/*
+ * TrueTypeTable public methods
+ */
+
+/* Note: Type42 fonts only need these tables:
+ * head, hhea, loca, maxp, cvt, prep, glyf, hmtx, fpgm
+ *
+ * Microsoft required tables
+ * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post, OS/2
+ *
+ * Apple required tables
+ * cmap, glyf, head, hhea, hmtx, loca, maxp, name, post
+ *
+ */
+
+TrueTypeTableGeneric::TrueTypeTableGeneric(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ const sal_uInt8* ptr)
+ : TrueTypeTable(tag),
+ m_nbytes(nbytes)
+{
+ if (nbytes) {
+ m_ptr = ttmalloc(nbytes);
+ memcpy(m_ptr.get(), ptr, nbytes);
+ }
+}
+
+TrueTypeTableGeneric::TrueTypeTableGeneric(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ std::unique_ptr<sal_uInt8[]> ptr)
+ : TrueTypeTable(tag),
+ m_nbytes(nbytes)
+{
+ if (nbytes) {
+ m_ptr = std::move(ptr);
+ }
+}
+
+TrueTypeTableHead::TrueTypeTableHead(sal_uInt32 fontRevision,
+ sal_uInt16 flags,
+ sal_uInt16 unitsPerEm,
+ const sal_uInt8* created,
+ sal_uInt16 macStyle,
+ sal_uInt16 lowestRecPPEM,
+ sal_Int16 fontDirectionHint)
+ : TrueTypeTable(T_head)
+ , m_head(ttmalloc(HEAD_Length))
+{
+ assert(created != nullptr);
+
+ sal_uInt8* ptr = m_head.get();
+
+ PutUInt32(0x00010000, ptr, 0); /* version */
+ PutUInt32(fontRevision, ptr, 4);
+ PutUInt32(0x5F0F3CF5, ptr, 12); /* magic number */
+ PutUInt16(flags, ptr, 16);
+ PutUInt16(unitsPerEm, ptr, 18);
+ memcpy(ptr+20, created, 8); /* Created Long Date */
+ memset(ptr+28, 0, 8); /* Modified Long Date */
+ PutUInt16(macStyle, ptr, 44);
+ PutUInt16(lowestRecPPEM, ptr, 46);
+ PutUInt16(fontDirectionHint, ptr, 48);
+ PutUInt16(0, ptr, 52); /* glyph data format: 0 */
+}
+
+TrueTypeTableHhea::TrueTypeTableHhea(sal_Int16 ascender,
+ sal_Int16 descender,
+ sal_Int16 linegap,
+ sal_Int16 caretSlopeRise,
+ sal_Int16 caretSlopeRun)
+ : TrueTypeTable(T_hhea),
+ m_hhea(ttmalloc(HHEA_Length))
+{
+ sal_uInt8* ptr = m_hhea.get();
+
+ PutUInt32(0x00010000, ptr, 0); /* version */
+ PutUInt16(ascender, ptr, 4);
+ PutUInt16(descender, ptr, 6);
+ PutUInt16(linegap, ptr, 8);
+ PutUInt16(caretSlopeRise, ptr, 18);
+ PutUInt16(caretSlopeRun, ptr, 20);
+ PutUInt16(0, ptr, 22); /* reserved 1 */
+ PutUInt16(0, ptr, 24); /* reserved 2 */
+ PutUInt16(0, ptr, 26); /* reserved 3 */
+ PutUInt16(0, ptr, 28); /* reserved 4 */
+ PutUInt16(0, ptr, 30); /* reserved 5 */
+ PutUInt16(0, ptr, 32); /* metricDataFormat */
+}
+
+TrueTypeTableLoca::TrueTypeTableLoca()
+ : TrueTypeTable(T_loca),
+ m_loca(new tdata_loca)
+{
+ this->m_loca->nbytes = 0;
+ this->m_loca->ptr = nullptr;
+}
+
+TrueTypeTableMaxp::TrueTypeTableMaxp( const sal_uInt8* maxp, int size)
+ : TrueTypeTable(T_maxp)
+{
+ this->m_maxp = ttmalloc(MAXP_Version1Length);
+
+ if (maxp && size == MAXP_Version1Length) {
+ memcpy(this->m_maxp.get(), maxp, MAXP_Version1Length);
+ }
+}
+
+TrueTypeTableGlyf::TrueTypeTableGlyf()
+ : TrueTypeTable(T_glyf)
+{
+}
+
+TrueTypeTableCmap::TrueTypeTableCmap()
+ : TrueTypeTable(T_cmap)
+ , m_cmap(new table_cmap)
+{
+ m_cmap->n = 0;
+ m_cmap->m = CMAP_SUBTABLE_INIT;
+ m_cmap->s.reset(new CmapSubTable[CMAP_SUBTABLE_INIT]);
+}
+
+TrueTypeTableName::TrueTypeTableName(std::vector<NameRecord> nr)
+ : TrueTypeTable(T_name)
+ , m_list(std::move(nr))
+{
+}
+
+TrueTypeTablePost::TrueTypeTablePost(sal_Int32 format,
+ sal_Int32 italicAngle,
+ sal_Int16 underlinePosition,
+ sal_Int16 underlineThickness,
+ sal_uInt32 isFixedPitch)
+ : TrueTypeTable(T_post)
+{
+ assert(format == 0x00030000); /* Only format 3.0 is supported at this time */
+
+ m_format = format;
+ m_italicAngle = italicAngle;
+ m_underlinePosition = underlinePosition;
+ m_underlineThickness = underlineThickness;
+ m_isFixedPitch = isFixedPitch;
+}
+
+void TrueTypeTableCmap::cmapAdd(sal_uInt32 id, sal_uInt32 c, sal_uInt32 g)
+{
+ sal_uInt32 i, found;
+ CmapSubTable *s;
+
+ assert(m_cmap);
+ s = m_cmap->s.get(); assert(s != nullptr);
+
+ found = 0;
+
+ for (i = 0; i < m_cmap->n; i++) {
+ if (s[i].id == id) {
+ found = 1;
+ break;
+ }
+ }
+
+ if (!found) {
+ if (m_cmap->n == m_cmap->m) {
+ std::unique_ptr<CmapSubTable[]> tmp(new CmapSubTable[m_cmap->m + CMAP_SUBTABLE_INCR]);
+ for (sal_uInt32 j = 0; j != m_cmap->m; ++j) {
+ tmp[j] = std::move(s[j]);
+ }
+ m_cmap->m += CMAP_SUBTABLE_INCR;
+ s = tmp.get();
+ m_cmap->s = std::move(tmp);
+ }
+
+ for (i = 0; i < m_cmap->n; i++) {
+ if (s[i].id > id) break;
+ }
+
+ if (i < m_cmap->n) {
+ for (sal_uInt32 j = m_cmap->n; j != i; --j) {
+ s[j + 1] = std::move(s[j]);
+ }
+ }
+
+ m_cmap->n++;
+
+ s[i].id = id;
+ }
+
+ s[i].mappings.emplace_back(c, g);
+}
+
+sal_uInt32 TrueTypeTableGlyf::glyfAdd(std::unique_ptr<GlyphData> glyphdata, AbstractTrueTypeFont *fnt)
+{
+ sal_uInt32 currentID;
+ int ret, n, ncomponents;
+
+ if (!glyphdata) return sal_uInt32(~0);
+
+ std::vector< sal_uInt32 > glyphlist;
+
+ ncomponents = GetTTGlyphComponents(fnt, glyphdata->glyphID, glyphlist);
+
+ if (m_list.size() > 0) {
+ ret = n = m_list.back()->newID + 1;
+ } else {
+ ret = n = 0;
+ }
+ glyphdata->newID = n++;
+ m_list.push_back(std::move(glyphdata));
+
+ if (ncomponents > 1 && glyphlist.size() > 1 )
+ {
+ std::vector< sal_uInt32 >::const_iterator it = glyphlist.begin();
+ ++it;
+ /* glyphData->glyphID is always the first glyph on the list */
+ do
+ {
+ int found = 0;
+ currentID = *it;
+ /* XXX expensive! should be rewritten with sorted arrays! */
+ for (const std::unique_ptr<GlyphData>& pGlyph : m_list)
+ {
+ if (pGlyph->glyphID == currentID) {
+ found = 1;
+ break;
+ }
+ }
+
+ if (!found) {
+ std::unique_ptr<GlyphData> gd = GetTTRawGlyphData(fnt, currentID);
+ gd->newID = n++;
+ m_list.push_back(std::move(gd));
+ }
+ } while( ++it != glyphlist.end() );
+ }
+
+ return ret;
+}
+
+TrueTypeTable *TrueTypeCreator::FindTable(sal_uInt32 tableTag)
+{
+ for (const std::unique_ptr<TrueTypeTable>& p : this->m_tables)
+ if (p->m_tag == tableTag) {
+ return p.get();
+ }
+
+ return nullptr;
+}
+
+/* This function processes all the tables and synchronizes them before creating
+ * the output TrueType stream.
+ *
+ * *** It adds two TrueType tables to the font: 'loca' and 'hmtx' ***
+ *
+ * It does:
+ *
+ * - Re-numbers glyph IDs and creates 'glyf', 'loca', and 'hmtx' tables.
+ * - Calculates xMin, yMin, xMax, and yMax and stores values in 'head' table.
+ * - Stores indexToLocFormat in 'head'
+ * - updates 'maxp' table
+ * - Calculates advanceWidthMax, minLSB, minRSB, xMaxExtent and numberOfHMetrics
+ * in 'hhea' table
+ *
+ */
+void TrueTypeCreator::ProcessTables()
+{
+ TrueTypeTableHhea *hhea = nullptr;
+ TrueTypeTableMaxp *maxp = nullptr;
+ TrueTypeTableHead *head = nullptr;
+ std::unique_ptr<TrueTypeTableLoca> loca;
+ TrueTypeTableGlyf *glyf = nullptr;
+ sal_uInt32 nGlyphs, locaLen = 0, glyfLen = 0;
+ sal_Int16 xMin = 0, yMin = 0, xMax = 0, yMax = 0;
+ sal_uInt32 i = 0;
+ sal_Int16 indexToLocFormat;
+ std::unique_ptr<sal_uInt8[]> hmtxPtr;
+ sal_uInt8 *hheaPtr;
+ sal_uInt32 hmtxSize;
+ sal_uInt8 *p1, *p2;
+ sal_uInt16 maxPoints = 0, maxContours = 0, maxCompositePoints = 0, maxCompositeContours = 0;
+ int nlsb = 0;
+ std::unique_ptr<sal_uInt32[]> gid; /* array of old glyphIDs */
+
+ glyf = static_cast<TrueTypeTableGlyf*>(FindTable(T_glyf));
+ std::vector<std::unique_ptr<GlyphData>>& glyphlist = glyf->m_list;
+ nGlyphs = glyphlist.size();
+ if (!nGlyphs)
+ {
+ SAL_WARN("vcl.fonts", "no glyphs found in ProcessTables");
+ return;
+ }
+ gid.reset(new sal_uInt32[nGlyphs]);
+
+ RemoveTable(T_loca);
+ RemoveTable(T_hmtx);
+
+ /* XXX Need to make sure that composite glyphs do not break during glyph renumbering */
+
+ for (const std::unique_ptr<GlyphData>& gd : glyphlist)
+ {
+ glyfLen += gd->nbytes;
+ /* XXX if (gd->nbytes & 1) glyfLen++; */
+
+ assert(gd->newID == i);
+ gid[i++] = gd->glyphID;
+ /* gd->glyphID = i++; */
+
+ /* printf("IDs: %d %d.\n", gd->glyphID, gd->newID); */
+
+ if (gd->nbytes >= 10) {
+ sal_Int16 z = GetInt16(gd->ptr.get(), 2);
+ if (z < xMin) xMin = z;
+
+ z = GetInt16(gd->ptr.get(), 4);
+ if (z < yMin) yMin = z;
+
+ z = GetInt16(gd->ptr.get(), 6);
+ if (z > xMax) xMax = z;
+
+ z = GetInt16(gd->ptr.get(), 8);
+ if (z > yMax) yMax = z;
+ }
+
+ if (!gd->compflag) { /* non-composite glyph */
+ if (gd->npoints > maxPoints) maxPoints = gd->npoints;
+ if (gd->ncontours > maxContours) maxContours = gd->ncontours;
+ } else { /* composite glyph */
+ if (gd->npoints > maxCompositePoints) maxCompositePoints = gd->npoints;
+ if (gd->ncontours > maxCompositeContours) maxCompositeContours = gd->ncontours;
+ }
+
+ }
+
+ indexToLocFormat = (glyfLen / 2 > 0xFFFF) ? 1 : 0;
+ locaLen = indexToLocFormat ? (nGlyphs + 1) << 2 : (nGlyphs + 1) << 1;
+
+ std::unique_ptr<sal_uInt8[]> glyfPtr = ttmalloc(glyfLen);
+ std::unique_ptr<sal_uInt8[]> locaPtr = ttmalloc(locaLen);
+ std::unique_ptr<TTSimpleGlyphMetrics[]> met(new TTSimpleGlyphMetrics[nGlyphs]);
+ i = 0;
+
+ p1 = glyfPtr.get();
+ p2 = locaPtr.get();
+ for (const std::unique_ptr<GlyphData>& gd : glyphlist)
+ {
+ if (gd->compflag && gd->nbytes > 10) { /* re-number all components */
+ sal_uInt16 flags, index;
+ sal_uInt8 *ptr = gd->ptr.get() + 10;
+ size_t nRemaining = gd->nbytes - 10;
+ do {
+ if (nRemaining < 4)
+ {
+ SAL_WARN("vcl.fonts", "truncated font");
+ break;
+ }
+ flags = GetUInt16(ptr, 0);
+ index = GetUInt16(ptr, 2);
+
+ /* XXX use the sorted array of old to new glyphID mapping and do a binary search */
+ sal_uInt32 j;
+ for (j = 0; j < nGlyphs; j++) {
+ if (gid[j] == index) {
+ break;
+ }
+ }
+ /* printf("X: %d -> %d.\n", index, j); */
+
+ PutUInt16(static_cast<sal_uInt16>(j), ptr, 2);
+
+ ptr += 4;
+ nRemaining -= 4;
+
+ sal_uInt32 nAdvance = 0;
+ if (flags & ARG_1_AND_2_ARE_WORDS) {
+ nAdvance += 4;
+ } else {
+ nAdvance += 2;
+ }
+
+ if (flags & WE_HAVE_A_SCALE) {
+ nAdvance += 2;
+ } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
+ nAdvance += 4;
+ } else if (flags & WE_HAVE_A_TWO_BY_TWO) {
+ nAdvance += 8;
+ }
+
+ if (nRemaining < nAdvance)
+ {
+ SAL_WARN("vcl.fonts", "truncated font");
+ break;
+ }
+
+ ptr += nAdvance;
+ nRemaining -= nAdvance;
+
+ } while (flags & MORE_COMPONENTS);
+ }
+
+ if (gd->nbytes != 0) {
+ memcpy(p1, gd->ptr.get(), gd->nbytes);
+ }
+ if (indexToLocFormat == 1) {
+ PutUInt32(p1 - glyfPtr.get(), p2, 0);
+ p2 += 4;
+ } else {
+ PutUInt16(static_cast<sal_uInt16>((p1 - glyfPtr.get()) >> 1), p2, 0);
+ p2 += 2;
+ }
+ p1 += gd->nbytes;
+
+ /* fill the array of metrics */
+ met[i].adv = gd->aw;
+ met[i].sb = gd->lsb;
+ i++;
+ }
+
+ gid.reset();
+
+ if (indexToLocFormat == 1) {
+ PutUInt32(p1 - glyfPtr.get(), p2, 0);
+ } else {
+ PutUInt16(static_cast<sal_uInt16>((p1 - glyfPtr.get()) >> 1), p2, 0);
+ }
+
+ glyf->m_rawdata = std::move(glyfPtr);
+
+ loca.reset(new TrueTypeTableLoca());
+ loca->m_loca->ptr = std::move(locaPtr);
+ loca->m_loca->nbytes = locaLen;
+
+ AddTable(std::move(loca));
+
+ head = static_cast<TrueTypeTableHead*>(FindTable(T_head));
+ sal_uInt8* const pHeadData = head->m_head.get();
+ PutInt16(xMin, pHeadData, HEAD_xMin_offset);
+ PutInt16(yMin, pHeadData, HEAD_yMin_offset);
+ PutInt16(xMax, pHeadData, HEAD_xMax_offset);
+ PutInt16(yMax, pHeadData, HEAD_yMax_offset);
+ PutInt16(indexToLocFormat, pHeadData, HEAD_indexToLocFormat_offset);
+
+ maxp = static_cast<TrueTypeTableMaxp*>(FindTable(T_maxp));
+
+ sal_uInt8* const pMaxpData = maxp->m_maxp.get();
+ PutUInt16(static_cast<sal_uInt16>(nGlyphs), pMaxpData, MAXP_numGlyphs_offset);
+ PutUInt16(maxPoints, pMaxpData, MAXP_maxPoints_offset);
+ PutUInt16(maxContours, pMaxpData, MAXP_maxContours_offset);
+ PutUInt16(maxCompositePoints, pMaxpData, MAXP_maxCompositePoints_offset);
+ PutUInt16(maxCompositeContours, pMaxpData, MAXP_maxCompositeContours_offset);
+
+ /*
+ * Generate an htmx table and update hhea table
+ */
+ hhea = static_cast<TrueTypeTableHhea*>(FindTable(T_hhea)); assert(hhea != nullptr);
+ hheaPtr = hhea->m_hhea.get();
+ if (nGlyphs > 2) {
+ for (i = nGlyphs - 1; i > 0; i--) {
+ if (met[i].adv != met[i-1].adv) break;
+ }
+ nlsb = nGlyphs - 1 - i;
+ }
+ hmtxSize = (nGlyphs - nlsb) * 4 + nlsb * 2;
+ hmtxPtr = ttmalloc(hmtxSize);
+ p1 = hmtxPtr.get();
+
+ for (i = 0; i < nGlyphs; i++) {
+ if (i < nGlyphs - nlsb) {
+ PutUInt16(met[i].adv, p1, 0);
+ PutUInt16(met[i].sb, p1, 2);
+ p1 += 4;
+ } else {
+ PutUInt16(met[i].sb, p1, 0);
+ p1 += 2;
+ }
+ }
+
+ AddTable(std::make_unique<TrueTypeTableGeneric>(T_hmtx, hmtxSize, std::move(hmtxPtr)));
+ PutUInt16(static_cast<sal_uInt16>(nGlyphs - nlsb), hheaPtr, 34);
+}
+
+/**
+ * TrueTypeCreator destructor. It calls destructors for all TrueTypeTables added to it.
+ */
+TrueTypeCreator::~TrueTypeCreator()
+{
+}
+
+} // namespace vcl
+
+#ifdef TEST_TTCR
+static sal_uInt32 mkTag(sal_uInt8 a, sal_uInt8 b, sal_uInt8 c, sal_uInt8 d) {
+ return (a << 24) | (b << 16) | (c << 8) | d;
+}
+
+int main()
+{
+ TrueTypeCreator *ttcr;
+ sal_uInt8 *t1, *t2, *t3, *t4, *t5, *t6;
+
+ TrueTypeCreatorNewEmpty(mkTag('t','r','u','e'), &ttcr);
+
+ t1 = malloc(1000); memset(t1, 'a', 1000);
+ t2 = malloc(2000); memset(t2, 'b', 2000);
+ t3 = malloc(3000); memset(t3, 'c', 3000);
+ t4 = malloc(4000); memset(t4, 'd', 4000);
+ t5 = malloc(5000); memset(t5, 'e', 5000);
+ t6 = malloc(6000); memset(t6, 'f', 6000);
+
+ AddTable(ttcr, TrueTypeTableNew(T_maxp, 1000, t1));
+ AddTable(ttcr, TrueTypeTableNew(T_OS2, 2000, t2));
+ AddTable(ttcr, TrueTypeTableNew(T_cmap, 3000, t3));
+ AddTable(ttcr, TrueTypeTableNew(T_loca, 4000, t4));
+ AddTable(ttcr, TrueTypeTableNew(T_hhea, 5000, t5));
+ AddTable(ttcr, TrueTypeTableNew(T_glyf, 6000, t6));
+
+ free(t1);
+ free(t2);
+ free(t3);
+ free(t4);
+ free(t5);
+ free(t6);
+
+ StreamToFile(ttcr, "ttcrout.ttf");
+
+ TrueTypeCreatorDispose(ttcr);
+ return 0;
+}
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/ttcr.hxx b/vcl/source/fontsubset/ttcr.hxx
new file mode 100644
index 0000000000..4dd78b0544
--- /dev/null
+++ b/vcl/source/fontsubset/ttcr.hxx
@@ -0,0 +1,288 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/**
+ * @file ttcr.hxx
+ * @brief TrueType font creator
+ */
+
+#pragma once
+
+#include <sft.hxx>
+#include <vector>
+
+namespace vcl
+{
+class TrueTypeTable;
+struct tdata_loca;
+struct table_cmap;
+struct TableEntry;
+
+
+/* TrueType data types */
+ typedef struct {
+ sal_uInt16 aw;
+ sal_Int16 lsb;
+ } longHorMetrics;
+
+/** Error codes for most functions */
+ enum TTCRErrCodes {
+ TTCR_OK, /**< no error */
+ TTCR_ZEROGLYPHS, /**< At least one glyph should be defined */
+ TTCR_UNKNOWN, /**< Unknown TrueType table */
+ TTCR_NONAMES, /**< 'name' table does not contain any names */
+ TTCR_NAMETOOLONG, /**< 'name' table is too long (string data > 64K) */
+ TTCR_POSTFORMAT /**< unsupported format of a 'post' table */
+ };
+
+ class TrueTypeCreator {
+ public:
+ /**
+ * TrueTypeCreator constructor.
+ * Allocates all internal structures.
+ */
+ TrueTypeCreator(sal_uInt32 tag);
+ ~TrueTypeCreator();
+ /**
+ * Adds a TrueType table to the TrueType creator.
+ */
+ void AddTable(std::unique_ptr<TrueTypeTable> table);
+ /**
+ * Removes a TrueType table from the TrueType creator if it is stored there.
+ * It also calls a TrueTypeTable destructor.
+ * Note: all generic tables (with tag 0) will be removed if this function is
+ * called with the second argument of 0.
+ * @return value of SFErrCodes type
+ */
+ void RemoveTable(sal_uInt32 tag);
+ /**
+ * Writes a TrueType font generated by the TrueTypeCreator to a segment of
+ * memory that this method allocates. When it is not needed anymore the caller
+ * is supposed to call free() on it.
+ * @return value of SFErrCodes type
+ */
+ SFErrCodes StreamToMemory(std::vector<sal_uInt8>& rOutBuffer);
+
+ private:
+ TrueTypeTable *FindTable(sal_uInt32 tag);
+ void ProcessTables();
+
+ sal_uInt32 m_tag; /**< TrueType file tag */
+ std::vector<std::unique_ptr<TrueTypeTable>> m_tables; /**< List of table tags and pointers */
+ };
+
+ /* A generic base class for all TrueType tables */
+ class TrueTypeTable {
+ protected:
+ TrueTypeTable(sal_uInt32 tag_) : m_tag(tag_) {}
+
+ public:
+ virtual ~TrueTypeTable();
+
+ /**
+ * This function converts the data of a TrueType table to a raw array of bytes.
+ * It may allocates the memory for it and returns the size of the raw data in bytes.
+ * If memory is allocated it does not need to be freed by the caller of this function,
+ * since the pointer to it is stored in the TrueTypeTable and it is freed by the destructor
+ * @return TTCRErrCode
+ *
+ */
+ virtual int GetRawData(TableEntry*) = 0;
+
+ sal_uInt32 m_tag = 0; /* table tag */
+ std::unique_ptr<sal_uInt8[]> m_rawdata; /* raw data allocated by GetRawData_*() */
+ };
+
+ class TrueTypeTableGeneric : public TrueTypeTable
+ {
+ public:
+ /**
+ *
+ * Creates a new raw TrueType table. The difference between this constructor and
+ * TrueTypeTableNew_tag constructors is that the latter create structured tables
+ * while this constructor just copies memory pointed to by ptr to its buffer
+ * and stores its length. This constructor is suitable for data that is not
+ * supposed to be processed in any way, just written to the resulting TTF file.
+ */
+ TrueTypeTableGeneric(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ const sal_uInt8* ptr);
+ TrueTypeTableGeneric(sal_uInt32 tag,
+ sal_uInt32 nbytes,
+ std::unique_ptr<sal_uInt8[]> ptr);
+ virtual ~TrueTypeTableGeneric() override;
+ virtual int GetRawData(TableEntry*) override;
+ private:
+ sal_uInt32 m_nbytes;
+ std::unique_ptr<sal_uInt8[]> m_ptr;
+ };
+
+/**
+ * Creates a new 'head' table for a TrueType font.
+ * Allocates memory for it. Since a lot of values in the 'head' table depend on the
+ * rest of the tables in the TrueType font this table should be the last one added
+ * to the font.
+ */
+ class TrueTypeTableHead : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableHead(sal_uInt32 fontRevision,
+ sal_uInt16 flags,
+ sal_uInt16 unitsPerEm,
+ const sal_uInt8 *created,
+ sal_uInt16 macStyle,
+ sal_uInt16 lowestRecPPEM,
+ sal_Int16 fontDirectionHint);
+ virtual ~TrueTypeTableHead() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ std::unique_ptr<sal_uInt8[]> m_head;
+ };
+
+/**
+ * Creates a new 'hhea' table for a TrueType font.
+ * Allocates memory for it and stores it in the hhea pointer.
+ */
+ class TrueTypeTableHhea : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableHhea(sal_Int16 ascender,
+ sal_Int16 descender,
+ sal_Int16 linegap,
+ sal_Int16 caretSlopeRise,
+ sal_Int16 caretSlopeRun);
+ virtual ~TrueTypeTableHhea() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ std::unique_ptr<sal_uInt8[]> m_hhea;
+ };
+
+/**
+ * Creates a new empty 'loca' table for a TrueType font.
+ *
+ * INTERNAL: gets called only from ProcessTables();
+ */
+ class TrueTypeTableLoca : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableLoca();
+ virtual ~TrueTypeTableLoca() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ std::unique_ptr<tdata_loca> m_loca;
+ };
+
+/**
+ * Creates a new 'maxp' table based on an existing maxp table.
+ * If maxp is 0, a new empty maxp table is created
+ * size specifies the size of existing maxp table for
+ * error-checking purposes
+ */
+ class TrueTypeTableMaxp : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableMaxp(const sal_uInt8* maxp, int size);
+ virtual ~TrueTypeTableMaxp() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ std::unique_ptr<sal_uInt8[]> m_maxp;
+ };
+
+/**
+ * Creates a new empty 'glyf' table.
+ */
+ class TrueTypeTableGlyf : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableGlyf();
+ virtual ~TrueTypeTableGlyf() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ /**
+ * Add a glyph to a glyf table.
+ *
+ * @return glyphID of the glyph in the new font
+ *
+ * NOTE: This function does not duplicate GlyphData, so memory will be
+ * deallocated in the table destructor
+ */
+ sal_uInt32 glyfAdd(std::unique_ptr<GlyphData> glyphdata, AbstractTrueTypeFont *fnt);
+
+ std::vector<std::unique_ptr<GlyphData>> m_list;
+ };
+
+/**
+ * Creates a new empty 'cmap' table.
+ */
+ class TrueTypeTableCmap : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableCmap();
+ virtual ~TrueTypeTableCmap() override;
+ virtual int GetRawData(TableEntry*) override;
+
+ /**
+ * Add a character/glyph pair to a cmap table
+ */
+ void cmapAdd(sal_uInt32 id, sal_uInt32 c, sal_uInt32 g);
+
+ private:
+ std::unique_ptr<table_cmap> m_cmap;
+ };
+
+/**
+ * Creates a new 'name' table. If n != 0 the table gets populated by
+ * the Name Records stored in the nr array. This function allocates
+ * memory for its own copy of NameRecords, so nr array has to
+ * be explicitly deallocated when it is not needed.
+ */
+ class TrueTypeTableName : public TrueTypeTable
+ {
+ public:
+ TrueTypeTableName(std::vector<NameRecord> nr);
+ virtual ~TrueTypeTableName() override;
+ virtual int GetRawData(TableEntry*) override;
+ private:
+ std::vector<NameRecord> m_list;
+ };
+
+/**
+ * Creates a new 'post' table of one of the supported formats
+ */
+ class TrueTypeTablePost : public TrueTypeTable
+ {
+ public:
+ TrueTypeTablePost(sal_Int32 format,
+ sal_Int32 italicAngle,
+ sal_Int16 underlinePosition,
+ sal_Int16 underlineThickness,
+ sal_uInt32 isFixedPitch);
+ virtual ~TrueTypeTablePost() override;
+ virtual int GetRawData(TableEntry*) override;
+ private:
+ sal_uInt32 m_format;
+ sal_uInt32 m_italicAngle;
+ sal_Int16 m_underlinePosition;
+ sal_Int16 m_underlineThickness;
+ sal_uInt32 m_isFixedPitch;
+ };
+
+} // namespace
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/xlat.cxx b/vcl/source/fontsubset/xlat.cxx
new file mode 100644
index 0000000000..b7966f2798
--- /dev/null
+++ b/vcl/source/fontsubset/xlat.cxx
@@ -0,0 +1,144 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+#include <rtl/textcvt.h>
+#include "xlat.hxx"
+
+namespace {
+
+#define MAX_CVT_SELECT 6
+
+class ConverterCache
+{
+public:
+ explicit ConverterCache();
+ ~ConverterCache();
+ sal_uInt16 convertOne( int nSelect, sal_Unicode );
+private:
+ void ensureConverter( int nSelect );
+ rtl_UnicodeToTextConverter maConverterCache[ MAX_CVT_SELECT+1 ];
+ rtl_UnicodeToTextContext maContexts[ MAX_CVT_SELECT+1 ];
+};
+
+ConverterCache::ConverterCache()
+{
+ for( int i = 0; i <= MAX_CVT_SELECT; ++i)
+ {
+ maConverterCache[i] = nullptr;
+ maContexts[i] = nullptr;
+ }
+}
+
+ConverterCache::~ConverterCache()
+{
+ for( int i = 0; i <= MAX_CVT_SELECT; ++i)
+ {
+ if( !maContexts[i] )
+ continue;
+ rtl_destroyUnicodeToTextContext( maConverterCache[i], maContexts[i] );
+ rtl_destroyUnicodeToTextConverter( maConverterCache[i] );
+ }
+}
+
+void ConverterCache::ensureConverter( int nSelect )
+{
+ // SAL_WARN_IF( (2>nSelect) || (nSelect>MAX_CVT_SELECT)), "vcl", "invalid XLAT.Converter requested" );
+ rtl_UnicodeToTextContext aContext = maContexts[ nSelect ];
+ if( !aContext )
+ {
+ rtl_TextEncoding eRecodeFrom = RTL_TEXTENCODING_UNICODE;
+ switch( nSelect )
+ {
+ default: nSelect = 1; [[fallthrough]]; // to unicode recoding
+ case 1: eRecodeFrom = RTL_TEXTENCODING_UNICODE; break;
+ case 2: eRecodeFrom = RTL_TEXTENCODING_SHIFT_JIS; break;
+ case 3: eRecodeFrom = RTL_TEXTENCODING_GB_2312; break;
+ case 4: eRecodeFrom = RTL_TEXTENCODING_BIG5; break;
+ case 5: eRecodeFrom = RTL_TEXTENCODING_MS_949; break;
+ case 6: eRecodeFrom = RTL_TEXTENCODING_MS_1361; break;
+ }
+ rtl_UnicodeToTextConverter aRecodeConverter = rtl_createUnicodeToTextConverter( eRecodeFrom );
+ maConverterCache[ nSelect ] = aRecodeConverter;
+
+ aContext = rtl_createUnicodeToTextContext( aRecodeConverter );
+ maContexts[ nSelect ] = aContext;
+ }
+
+ rtl_resetUnicodeToTextContext( maConverterCache[ nSelect ], aContext );
+}
+
+sal_uInt16 ConverterCache::convertOne( int nSelect, sal_Unicode aChar )
+{
+ ensureConverter( nSelect );
+
+ sal_Unicode aUCS2Char = aChar;
+ char aTempArray[8];
+ sal_Size nTempSize;
+ sal_uInt32 nCvtInfo;
+
+ // TODO: use direct unicode->mbcs converter should there ever be one
+ int nCodeLen = rtl_convertUnicodeToText(
+ maConverterCache[ nSelect ], maContexts[ nSelect ],
+ &aUCS2Char, 1, aTempArray, sizeof(aTempArray),
+ RTL_UNICODETOTEXT_FLAGS_UNDEFINED_0
+ | RTL_UNICODETOTEXT_FLAGS_INVALID_0,
+ &nCvtInfo, &nTempSize );
+
+ sal_uInt16 aCode = aTempArray[0];
+ for( int i = 1; i < nCodeLen; ++i )
+ aCode = (aCode << 8) + (aTempArray[i] & 0xFF);
+ return aCode;
+}
+
+} // anonymous namespace
+
+namespace vcl
+{
+
+static ConverterCache aCC;
+
+sal_uInt16 TranslateChar12(sal_uInt16 src)
+{
+ return aCC.convertOne( 2, src);
+}
+
+sal_uInt16 TranslateChar13(sal_uInt16 src)
+{
+ return aCC.convertOne( 3, src);
+}
+
+sal_uInt16 TranslateChar14(sal_uInt16 src)
+{
+ return aCC.convertOne( 4, src);
+}
+
+sal_uInt16 TranslateChar15(sal_uInt16 src)
+{
+ return aCC.convertOne( 5, src);
+}
+
+sal_uInt16 TranslateChar16(sal_uInt16 src)
+{
+ return aCC.convertOne( 6, src);
+}
+
+
+} // namespace vcl
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/vcl/source/fontsubset/xlat.hxx b/vcl/source/fontsubset/xlat.hxx
new file mode 100644
index 0000000000..89eba1b7f4
--- /dev/null
+++ b/vcl/source/fontsubset/xlat.hxx
@@ -0,0 +1,37 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This file incorporates work covered by the following license notice:
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed
+ * with this work for additional information regarding copyright
+ * ownership. The ASF licenses this file to you under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.apache.org/licenses/LICENSE-2.0 .
+ */
+
+/*| Author: Alexander Gelfenbain |*/
+
+#pragma once
+
+#include <sal/types.h>
+
+namespace vcl
+{
+// TODO: sal_UCS4
+
+sal_uInt16 TranslateChar12(sal_uInt16);
+sal_uInt16 TranslateChar13(sal_uInt16);
+sal_uInt16 TranslateChar14(sal_uInt16);
+sal_uInt16 TranslateChar15(sal_uInt16);
+sal_uInt16 TranslateChar16(sal_uInt16);
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */