diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-27 16:51:28 +0000 |
commit | 940b4d1848e8c70ab7642901a68594e8016caffc (patch) | |
tree | eb72f344ee6c3d9b80a7ecc079ea79e9fba8676d /vcl/source/font | |
parent | Initial commit. (diff) | |
download | libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.tar.xz libreoffice-940b4d1848e8c70ab7642901a68594e8016caffc.zip |
Adding upstream version 1:7.0.4.upstream/1%7.0.4upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vcl/source/font')
-rw-r--r-- | vcl/source/font/Feature.cxx | 165 | ||||
-rw-r--r-- | vcl/source/font/FeatureCollector.cxx | 158 | ||||
-rw-r--r-- | vcl/source/font/FeatureParser.cxx | 69 | ||||
-rw-r--r-- | vcl/source/font/OpenTypeFeatureDefinitionList.cxx | 197 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontCollection.cxx | 1267 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontFace.cxx | 199 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontFamily.cxx | 273 | ||||
-rw-r--r-- | vcl/source/font/font.cxx | 894 | ||||
-rw-r--r-- | vcl/source/font/fontattributes.cxx | 62 | ||||
-rw-r--r-- | vcl/source/font/fontcache.cxx | 278 | ||||
-rw-r--r-- | vcl/source/font/fontcharmap.cxx | 634 | ||||
-rw-r--r-- | vcl/source/font/fontinstance.cxx | 168 | ||||
-rw-r--r-- | vcl/source/font/fontmetric.cxx | 394 | ||||
-rw-r--r-- | vcl/source/font/fontselect.cxx | 150 |
14 files changed, 4908 insertions, 0 deletions
diff --git a/vcl/source/font/Feature.cxx b/vcl/source/font/Feature.cxx new file mode 100644 index 000000000..99a3910b8 --- /dev/null +++ b/vcl/source/font/Feature.cxx @@ -0,0 +1,165 @@ +/* -*- 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_aID({ 0, 0, 0 }) + , m_eType(FeatureType::OpenType) +{ +} + +Feature::Feature(FeatureID const& rID, FeatureType eType) + : m_aID(rID) + , 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)) + , m_pDescriptionID(nullptr) +{ +} + +FeatureParameter::FeatureParameter(uint32_t nCode, const char* 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_pDescriptionID(nullptr) + , m_nCode(0) + , m_nDefault(0) + , m_eType(FeatureParameterType::BOOL) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, OUString const& rDescription, + FeatureParameterType eType, + std::vector<FeatureParameter> const& rEnumParameters, + uint32_t nDefault) + : m_sDescription(rDescription) + , m_pDescriptionID(nullptr) + , m_nCode(nCode) + , m_nDefault(nDefault) + , m_eType(eType) + , m_aEnumParameters(rEnumParameters) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, const char* pDescriptionID, + OUString const& rNumericPart) + : m_pDescriptionID(pDescriptionID) + , m_sNumericPart(rNumericPart) + , m_nCode(nCode) + , m_nDefault(0) + , m_eType(FeatureParameterType::BOOL) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, const char* pDescriptionID, + std::vector<FeatureParameter> aEnumParameters) + : m_pDescriptionID(pDescriptionID) + , m_nCode(nCode) + , m_nDefault(0) + , 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; } + +uint32_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 000000000..e8219b07c --- /dev/null +++ b/vcl/source/font/FeatureCollector.cxx @@ -0,0 +1,158 @@ +/* -*- 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 <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_eLanguageType); + + 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( + FeatureID{ nFeatureCode, HB_OT_TAG_DEFAULT_SCRIPT, HB_OT_TAG_DEFAULT_LANGUAGE }, + vcl::font::FeatureType::Graphite); + vcl::font::Feature& rFeature = m_rFontFeatures.back(); + rFeature.m_aDefinition = vcl::font::FeatureDefinition( + nFeatureCode, sLabel, eFeatureParameterType, aParameters, sal_uInt32(nValue)); + } + } + gr_featureval_destroy(pfeatureValues); + return true; +} + +void FeatureCollector::collectForLanguage(hb_tag_t aTableTag, sal_uInt32 nScript, + hb_tag_t aScriptTag, sal_uInt32 nLanguage, + hb_tag_t aLanguageTag) +{ + unsigned int nFeatureCount = hb_ot_layout_language_get_feature_tags( + m_pHbFace, aTableTag, nScript, nLanguage, 0, nullptr, nullptr); + std::vector<hb_tag_t> aFeatureTags(nFeatureCount); + hb_ot_layout_language_get_feature_tags(m_pHbFace, aTableTag, nScript, nLanguage, 0, + &nFeatureCount, aFeatureTags.data()); + aFeatureTags.resize(nFeatureCount); + + for (hb_tag_t aFeatureTag : aFeatureTags) + { + if (OpenTypeFeatureDefinitionList::get().isRequired(aFeatureTag)) + continue; + + m_rFontFeatures.emplace_back(); + vcl::font::Feature& rFeature = m_rFontFeatures.back(); + rFeature.m_aID = { aFeatureTag, aScriptTag, aLanguageTag }; + + FeatureDefinition aDefinition + = OpenTypeFeatureDefinitionList::get().getDefinition(aFeatureTag); + if (aDefinition) + { + rFeature.m_aDefinition = aDefinition; + } + } +} + +void FeatureCollector::collectForScript(hb_tag_t aTableTag, sal_uInt32 nScript, hb_tag_t aScriptTag) +{ + collectForLanguage(aTableTag, nScript, aScriptTag, HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX, + HB_OT_TAG_DEFAULT_LANGUAGE); + + unsigned int nLanguageCount + = hb_ot_layout_script_get_language_tags(m_pHbFace, aTableTag, nScript, 0, nullptr, nullptr); + std::vector<hb_tag_t> aLanguageTags(nLanguageCount); + hb_ot_layout_script_get_language_tags(m_pHbFace, aTableTag, nScript, 0, &nLanguageCount, + aLanguageTags.data()); + aLanguageTags.resize(nLanguageCount); + for (sal_uInt32 nLanguage = 0; nLanguage < sal_uInt32(nLanguageCount); ++nLanguage) + collectForLanguage(aTableTag, nScript, aScriptTag, nLanguage, aLanguageTags[nLanguage]); +} + +void FeatureCollector::collectForTable(hb_tag_t aTableTag) +{ + unsigned int nScriptCount + = hb_ot_layout_table_get_script_tags(m_pHbFace, aTableTag, 0, nullptr, nullptr); + std::vector<hb_tag_t> aScriptTags(nScriptCount); + hb_ot_layout_table_get_script_tags(m_pHbFace, aTableTag, 0, &nScriptCount, aScriptTags.data()); + aScriptTags.resize(nScriptCount); + + for (sal_uInt32 nScript = 0; nScript < sal_uInt32(nScriptCount); ++nScript) + collectForScript(aTableTag, nScript, aScriptTags[nScript]); +} + +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 000000000..c886482df --- /dev/null +++ b/vcl/source/font/FeatureParser.cxx @@ -0,0 +1,69 @@ +/* -*- 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> + +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(OUString const& rFontName) +{ + sal_Int32 nPrefixIdx{ rFontName.indexOf(vcl::font::FeaturePrefix) }; + + if (nPrefixIdx < 0) + return; + + OUString sName = rFontName.copy(++nPrefixIdx); + sal_Int32 nIndex = 0; + do + { + OUString sToken = sName.getToken(0, vcl::font::FeatureSeparator, nIndex); + + sal_Int32 nInnerIdx{ 0 }; + OUString sID = sToken.getToken(0, '=', nInnerIdx); + + if (sID == "lang") + { + m_sLanguage = sToken.getToken(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, uint32_t> FeatureParser::getFeaturesMap() const +{ + std::unordered_map<uint32_t, uint32_t> aResultMap; + for (auto const& rFeat : m_aFeatures) + { + if (rFeat.m_nValue != 0) + 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/OpenTypeFeatureDefinitionList.cxx b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx new file mode 100644 index 000000000..9c3a0ca6a --- /dev/null +++ b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx @@ -0,0 +1,197 @@ +/* -*- 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::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, + std::vector<FeatureParameter>{ { 0, STR_FONT_FEATURE_ID_FRAC_PARAM_0 }, + { 1, STR_FONT_FEATURE_ID_FRAC_PARAM_1 }, + { 2, STR_FONT_FEATURE_ID_FRAC_PARAM_2 } } }, + { 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"), + }); +} + +namespace +{ +bool isCharacterVariantCode(sal_uInt32 nFeatureCode) +{ + return char((sal_uInt32(nFeatureCode) >> 24) & 0xFF) == 'c' + && char((sal_uInt32(nFeatureCode) >> 16) & 0xFF) == 'v'; +} + +bool isStylisticSetCode(sal_uInt32 nFeatureCode) +{ + return char((sal_uInt32(nFeatureCode) >> 24) & 0xFF) == 's' + && char((sal_uInt32(nFeatureCode) >> 16) & 0xFF) == 's'; +} + +OUString getNumericLowerPart(sal_uInt32 nFeatureCode) +{ + char cChar1((sal_uInt32(nFeatureCode) >> 8) & 0xFF); + char cChar2((sal_uInt32(nFeatureCode) >> 0) & 0xFF); + + if (rtl::isAsciiDigit(static_cast<unsigned char>(cChar1)) + && rtl::isAsciiDigit(static_cast<unsigned char>(cChar2))) + { + return OUStringChar(cChar1) + OUStringChar(cChar2); + } + return OUString(); +} + +} // end anonymous namespace + +bool OpenTypeFeatureDefinitionListPrivate::isSpecialFeatureCode(sal_uInt32 nFeatureCode) +{ + return isCharacterVariantCode(nFeatureCode) || isStylisticSetCode(nFeatureCode); +} + +FeatureDefinition +OpenTypeFeatureDefinitionListPrivate::handleSpecialFeatureCode(sal_uInt32 nFeatureCode) +{ + FeatureDefinition aFeatureDefinition; + OUString sNumericPart = getNumericLowerPart(nFeatureCode); + if (!sNumericPart.isEmpty()) + { + if (isCharacterVariantCode(nFeatureCode)) + aFeatureDefinition = { nFeatureCode, STR_FONT_FEATURE_ID_CVXX, sNumericPart }; + else if (isStylisticSetCode(nFeatureCode)) + aFeatureDefinition = { nFeatureCode, STR_FONT_FEATURE_ID_SSXX, sNumericPart }; + } + return aFeatureDefinition; +} + +FeatureDefinition OpenTypeFeatureDefinitionListPrivate::getDefinition(sal_uInt32 nFeatureCode) +{ + if (isSpecialFeatureCode(nFeatureCode)) + { + return handleSpecialFeatureCode(nFeatureCode); + } + + 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 000000000..43ca203ff --- /dev/null +++ b/vcl/source/font/PhysicalFontCollection.cxx @@ -0,0 +1,1267 @@ +/* -*- 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 <memory> + +#include <i18nlangtag/languagetag.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/fontdefs.hxx> + +#include <outdev.h> +#include <PhysicalFontCollection.hxx> + +static ImplFontAttrs lcl_IsCJKFont( const OUString& rFontName ) +{ + // Test, if Fontname includes CJK characters --> In this case we + // mention that it is a CJK font + for(int i = 0; i < rFontName.getLength(); 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; +} + +PhysicalFontCollection::PhysicalFontCollection() + : mbMatchData( false ) + , mpPreMatchHook( nullptr ) + , mpFallbackHook( nullptr ) + , mnFallbackCount( -1 ) +{} + +PhysicalFontCollection::~PhysicalFontCollection() +{ + Clear(); +} + +void PhysicalFontCollection::SetPreMatchHook( ImplPreMatchFontSubstitution* pHook ) +{ + mpPreMatchHook = pHook; +} + +void PhysicalFontCollection::SetFallbackHook( ImplGlyphFallbackFontSubstitution* 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 ); + + // 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; + + while( nStrIndex < rMissingCodes.getLength() ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + bCached = pFontInstance->GetFallbackForUnicode( cChar, rFontSelData.GetWeight(), &aFontName ); + if( !bCached || (rFontSelData.maSearchName != aFontName) ) + 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(); + + // See fdo#32665 for an example. FreeSerif that has glyphs in normal + // font, but not in the italic or bold version + bool bSubSetOfFontRequiresPropertyFaking = rFontSelData.mbEmbolden || rFontSelData.maItalicMatrix != ItalicMatrix(); + + // Cache the result even if there was no match, unless its from part of a font for which the properties need + // to be faked. We need to rework this cache to take into account that fontconfig can return different fonts + // for different input sizes, weights, etc. Basically the cache is way to naive + if (!bSubSetOfFontRequiresPropertyFaking) + { + for(;;) + { + if( !pFontInstance->GetFallbackForUnicode( cChar, rFontSelData.GetWeight(), &rFontSelData.maSearchName ) ) + pFontInstance->AddFallbackForUnicode( cChar, rFontSelData.GetWeight(), rFontSelData.maSearchName ); + 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( const OUString& rFontName ) const +{ + return ImplFindFontFamilyBySearchName( GetEnglishSearchFontName( rFontName ) ); +} + +PhysicalFontFamily *PhysicalFontCollection::FindOrCreateFontFamily( const OUString &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(const OUString& rTokenStr) const +{ + PhysicalFontFamily* pFoundData = nullptr; + + // use normalized font name tokens to find the font + for( sal_Int32 nTokenPos = 0; nTokenPos != -1; ) + { + OUString aFamilyName = GetNextFontToken( rTokenStr, nTokenPos ); + if( aFamilyName.isEmpty() ) + continue; + + pFoundData = FindFontFamily( aFamilyName ); + + if( pFoundData ) + break; + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySubstFontAttr( const utl::FontNameAttr& 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; + const OUString aSearchName; + + pFoundData = FindFontFamilyByAttributes( nSearchType, + eSearchWeight, eSearchWidth, eSearchSlant, aSearchName ); + + 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, + const OUString& 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; + + 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 + long nTestMatch = 0; + + // test CJK script attributes + if ( nSearchType & ImplFontAttrs::CJK ) + { + // Matching language + if( ImplFontAttrs::None == ((nSearchType ^ 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.isEmpty() && (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.getLength() >= 4) && + (pData->GetMatchFamilyName().getLength() >= 4) && + ((rSearchFamilyName.indexOf( pData->GetMatchFamilyName() ) != -1) || + (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<ImplDeviceFontList> PhysicalFontCollection::GetDeviceFontList() const +{ + std::unique_ptr<ImplDeviceFontList> pDeviceFontList(new ImplDeviceFontList); + + for (auto const& family : maPhysicalFontFamilies) + { + const PhysicalFontFamily* pFontFamily = family.second.get(); + pFontFamily->UpdateDevFontList( *pDeviceFontList ); + } + + return pDeviceFontList; +} + +std::unique_ptr<ImplDeviceFontSizeList> PhysicalFontCollection::GetDeviceFontSizeList( const OUString& rFontName ) const +{ + std::unique_ptr<ImplDeviceFontSizeList> pDeviceFontSizeList(new ImplDeviceFontSizeList); + + PhysicalFontFamily* pFontFamily = FindFontFamily( rFontName ); + if( pFontFamily != nullptr ) + { + std::set<int> rHeights; + pFontFamily->GetFontHeights( rHeights ); + + for( const auto& rHeight : rHeights ) + pDeviceFontSizeList->Add( rHeight ); + } + + return pDeviceFontSizeList; +} + +// 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. +static 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; + + if (getenv("SAL_NO_FONT_LOOKUP") != nullptr) + { + // 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.IsSymbolFont() ) + { + 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.IsSymbolFont() ) + 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: */ + diff --git a/vcl/source/font/PhysicalFontFace.cxx b/vcl/source/font/PhysicalFontFace.cxx new file mode 100644 index 000000000..b16488ddc --- /dev/null +++ b/vcl/source/font/PhysicalFontFace.cxx @@ -0,0 +1,199 @@ +/* -*- 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/types.h> +#include <tools/fontenum.hxx> +#include <unotools/fontdefs.hxx> + +#include <fontattributes.hxx> +#include <fontselect.hxx> + +#include <PhysicalFontFace.hxx> + +PhysicalFontFace::PhysicalFontFace( const FontAttributes& rDFA ) + : FontAttributes( rDFA ) + , mnWidth(0) + , mnHeight(0) +{ + // StarSymbol is a unicode font, but it still deserves the symbol flag + if( !IsSymbolFont() ) + if ( IsStarSymbol( GetFamilyName() ) ) + SetSymbolFlag( true ); +} + +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; +} + +sal_Int32 PhysicalFontFace::CompareWithSize( const PhysicalFontFace& rOther ) const +{ + sal_Int32 nCompare = CompareIgnoreSize( rOther ); + if (nCompare != 0) + return nCompare; + + if( mnHeight < rOther.mnHeight ) + return -1; + else if( mnHeight > rOther.mnHeight ) + return 1; + + if( mnWidth < rOther.mnWidth ) + return -1; + else if( mnWidth > rOther.mnWidth ) + return 1; + + return 0; +} + +bool PhysicalFontFace::IsBetterMatch( const FontSelectPattern& rFSD, FontMatchStatus& rStatus ) const +{ + int nMatch = 0; + + const OUString& rFontName = rFSD.maTargetName; + if( rFontName.equalsIgnoreAsciiCase( GetFamilyName() ) ) + nMatch += 240000; + + if( rStatus.mpTargetStyleName + && GetStyleName().equalsIgnoreAsciiCase( *rStatus.mpTargetStyleName ) ) + nMatch += 120000; + + if( (rFSD.GetPitch() != PITCH_DONTKNOW) && (rFSD.GetPitch() == GetPitch()) ) + nMatch += 20000; + + // prefer NORMAL font width + // TODO: change when the upper layers can tell their width preference + if( GetWidthType() == WIDTH_NORMAL ) + nMatch += 400; + else if( (GetWidthType() == WIDTH_SEMI_EXPANDED) || (GetWidthType() == WIDTH_SEMI_CONDENSED) ) + nMatch += 300; + + if( rFSD.GetWeight() != WEIGHT_DONTKNOW ) + { + // if not bold or requiring emboldening prefer light fonts to bold fonts + FontWeight ePatternWeight = rFSD.mbEmbolden ? WEIGHT_NORMAL : rFSD.GetWeight(); + + int nReqWeight = static_cast<int>(ePatternWeight); + if ( ePatternWeight > WEIGHT_MEDIUM ) + nReqWeight += 100; + + int nGivenWeight = static_cast<int>(GetWeight()); + if( GetWeight() > 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 // requested weight == WEIGHT_DONTKNOW + { + // prefer NORMAL font weight + // TODO: change when the upper layers can tell their weight preference + if( GetWeight() == WEIGHT_NORMAL ) + nMatch += 450; + else if( GetWeight() == WEIGHT_MEDIUM ) + nMatch += 350; + else if( (GetWeight() == WEIGHT_SEMILIGHT) || (GetWeight() == WEIGHT_SEMIBOLD) ) + nMatch += 200; + else if( GetWeight() == WEIGHT_LIGHT ) + nMatch += 150; + } + + // if requiring custom matrix to fake italic, prefer upright font + FontItalic ePatternItalic = rFSD.maItalicMatrix != ItalicMatrix() ? ITALIC_NONE : rFSD.GetItalic(); + + if ( ePatternItalic == ITALIC_NONE ) + { + if( GetItalic() == ITALIC_NONE ) + nMatch += 900; + } + else + { + if( ePatternItalic == GetItalic() ) + nMatch += 900; + else if( GetItalic() != ITALIC_NONE ) + nMatch += 600; + } + + int nHeightMatch = 0; + int nWidthMatch = 0; + + if( rFSD.mnOrientation != 0 ) + nMatch += 80; + else if( rFSD.mnWidth != 0 ) + nMatch += 25; + else + nMatch += 5; + + if( rStatus.mnFaceMatch > nMatch ) + return false; + else if( rStatus.mnFaceMatch < nMatch ) + { + rStatus.mnFaceMatch = nMatch; + rStatus.mnHeightMatch = nHeightMatch; + rStatus.mnWidthMatch = nWidthMatch; + return true; + } + + // when two fonts are still competing prefer the + // one with the best matching height + if( rStatus.mnHeightMatch > nHeightMatch ) + return false; + else if( rStatus.mnHeightMatch < nHeightMatch ) + { + rStatus.mnHeightMatch = nHeightMatch; + rStatus.mnWidthMatch = nWidthMatch; + return true; + } + + if( rStatus.mnWidthMatch > nWidthMatch ) + return false; + + rStatus.mnWidthMatch = nWidthMatch; + return true; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/PhysicalFontFamily.cxx b/vcl/source/font/PhysicalFontFamily.cxx new file mode 100644 index 000000000..b8c630b6a --- /dev/null +++ b/vcl/source/font/PhysicalFontFamily.cxx @@ -0,0 +1,273 @@ +/* -*- 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/ustring.hxx> +#include <unotools/fontdefs.hxx> + +#include <outdev.h> +#include <PhysicalFontCollection.hxx> + +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( const OUString& rFontName ) +{ + // Test, if Fontname includes CJK characters --> In this case we + // mention that it is a CJK font + for(int i = 0; i < rFontName.getLength(); 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( const OUString& rSearchName ) +: maSearchName( rSearchName ), + 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(); + maMapNames = pNewFontFace->GetMapNames(); + 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->IsSymbolFont() ) + 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->CompareWithSize( *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 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,0,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( ImplDeviceFontList& 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::GetFontHeights( std::set<int>& rHeights ) const +{ + // add all available font heights + for (auto const& font : maFontFaces) + { + PhysicalFontFace *pFoundFontFace = font.get(); + rHeights.insert( pFoundFontFace->GetHeight() ); + } +} + +void PhysicalFontFamily::UpdateCloneFontList(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 000000000..4db757cd7 --- /dev/null +++ b/vcl/source/font/font.cxx @@ -0,0 +1,894 @@ +/* -*- 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/fontcfg.hxx> +#include <unotools/fontdefs.hxx> + +#include <vcl/font.hxx> + +#include <impfont.hxx> +#include <fontattributes.hxx> +#include <sft.hxx> + +#include <algorithm> + +#include <rtl/instance.hxx> +#include <TypeSerializer.hxx> + +using namespace vcl; + +namespace +{ + struct theGlobalDefault : + public rtl::Static< Font::ImplType, theGlobalDefault > {}; +} + +Font::Font() : mpImplFont(theGlobalDefault::get()) +{ +} + +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 ) : mpImplFont() +{ + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetFontSize( rSize ); +} + +Font::Font( const OUString& rFamilyName, const OUString& rStyleName, const Size& rSize ) : mpImplFont() +{ + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetStyleName( rStyleName ); + mpImplFont->SetFontSize( rSize ); +} + +Font::Font( FontFamily eFamily, const Size& rSize ) : mpImplFont() +{ + mpImplFont->SetFamilyType( eFamily ); + mpImplFont->SetFontSize( rSize ); +} + +Font::~Font() +{ +} + +void Font::SetColor( const Color& rColor ) +{ + if (const_cast<const ImplType&>(mpImplFont)->maColor != rColor) + { + mpImplFont->maColor = rColor; + } +} + +void Font::SetFillColor( const Color& rColor ) +{ + mpImplFont->maFillColor = rColor; + if ( rColor.GetTransparency() ) + mpImplFont->mbTransparent = true; +} + +void Font::SetTransparent( bool bTransparent ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mbTransparent != bTransparent) + mpImplFont->mbTransparent = bTransparent; +} + +void Font::SetAlignment( FontAlign eAlign ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meAlign != eAlign) + mpImplFont->SetAlignment(eAlign); +} + +void Font::SetFamilyName( const OUString& rFamilyName ) +{ + mpImplFont->SetFamilyName( rFamilyName ); +} + +void Font::SetStyleName( const OUString& 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 ); + + if ( eCharSet == RTL_TEXTENCODING_SYMBOL ) + mpImplFont->SetSymbolFlag( true ); + else + mpImplFont->SetSymbolFlag( false ); + } +} + +bool Font::IsSymbolFont() const +{ + return mpImplFont->IsSymbolFont(); +} + +void Font::SetSymbolFlag( bool bSymbol ) +{ + mpImplFont->SetSymbolFlag( bSymbol ); + + if ( IsSymbolFont() ) + { + mpImplFont->SetCharSet( RTL_TEXTENCODING_SYMBOL ); + } + else + { + if ( mpImplFont->GetCharSet() == RTL_TEXTENCODING_SYMBOL ) + mpImplFont->SetCharSet( RTL_TEXTENCODING_DONTKNOW ); + } +} + +void Font::SetLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (const_cast<const ImplType&>(mpImplFont)->maLanguageTag != rLanguageTag) + mpImplFont->maLanguageTag = rLanguageTag; +} + +void Font::SetCJKContextLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (const_cast<const ImplType&>(mpImplFont)->maCJKLanguageTag != rLanguageTag) + mpImplFont->maCJKLanguageTag = rLanguageTag; +} + +void Font::SetLanguage( LanguageType eLanguage ) +{ + if (const_cast<const ImplType&>(mpImplFont)->maLanguageTag.getLanguageType(false) != eLanguage) + mpImplFont->maLanguageTag.reset( eLanguage); +} + +void Font::SetCJKContextLanguage( LanguageType eLanguage ) +{ + if (const_cast<const ImplType&>(mpImplFont)->maCJKLanguageTag.getLanguageType(false) != eLanguage) + mpImplFont->maCJKLanguageTag.reset( eLanguage); +} + +void Font::SetPitch( FontPitch ePitch ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetPitchNoAsk() != ePitch) + mpImplFont->SetPitch( ePitch ); +} + +void Font::SetOrientation( short 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::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; +} + +bool Font::operator==( const vcl::Font& rFont ) const +{ + return mpImplFont == rFont.mpImplFont; +} + +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.SetSymbolFlag( mpImplFont->GetCharSet() == RTL_TEXTENCODING_SYMBOL ); +} + +SvStream& ReadImplFont( SvStream& rIStm, ImplFont& rImplFont ) +{ + VersionCompat aCompat( rIStm, StreamMode::READ ); + sal_uInt16 nTmp16(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); + + 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( rImplFont.mnOrientation ); + + 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); + } + + if( aCompat.GetVersion() >= 3 ) + { + rIStm.ReadUInt16( nTmp16 ); rImplFont.meOverline = static_cast<FontLineStyle>(nTmp16); + } + + // Relief + // CJKContextLanguage + + return rIStm; +} + +SvStream& WriteImplFont( SvStream& rOStm, const ImplFont& rImplFont ) +{ + VersionCompat aCompat( rOStm, StreamMode::WRITE, 3 ); + 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 ); + + 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<sal_uChar>(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 ); + + return rOStm; +} + +SvStream& ReadFont( SvStream& rIStm, vcl::Font& rFont ) +{ + return ReadImplFont( rIStm, *rFont.mpImplFont ); +} + +SvStream& WriteFont( SvStream& rOStm, const vcl::Font& rFont ) +{ + return WriteImplFont( rOStm, *rFont.mpImplFont ); +} + +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 ) + o_rResult.SetFamilyName( aInfo.ufamily ); + else if( aInfo.family ) + 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 ) + o_rResult.SetStyleName( OUString( aInfo.usubfamily ) ); + else if( aInfo.subfamily ) + o_rResult.SetStyleName( OUString::createFromAscii( aInfo.subfamily ) ); + + // cleanup + CloseTTFont( pTTF ); + // success + bResult = true; + } + return bResult; + } + + static 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( OString( 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; } + +FontAlign Font::GetAlignment() const { return mpImplFont->GetAlignment(); } + +const OUString& Font::GetFamilyName() const { return mpImplFont->GetFamilyName(); } +const OUString& Font::GetStyleName() const { return mpImplFont->maStyleName; } + +const Size& Font::GetFontSize() const { return mpImplFont->GetFontSize(); } +void Font::SetFontHeight( long nHeight ) { SetFontSize( Size( mpImplFont->GetFontSize().Width(), nHeight ) ); } +long Font::GetFontHeight() const { return mpImplFont->GetFontSize().Height(); } +void Font::SetAverageFontWidth( long nWidth ) { SetFontSize( Size( nWidth, mpImplFont->GetFontSize().Height() ) ); } +long Font::GetAverageFontWidth() const { return mpImplFont->GetFontSize().Width(); } + +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); } + +short 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 ), + meCharSet( RTL_TEXTENCODING_DONTKNOW ), + maLanguageTag( LANGUAGE_DONTKNOW ), + maCJKLanguageTag( LANGUAGE_DONTKNOW ), + mbSymbolFlag( false ), + mbOutline( false ), + mbConfigLookup( false ), + mbShadow( false ), + mbVertical( false ), + mbTransparent( true ), + maColor( COL_TRANSPARENT ), + maFillColor( COL_TRANSPARENT ), + mbWordLine( false ), + mnOrientation( 0 ), + mnQuality( 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 ), + maAverageFontSize( rImplFont.maAverageFontSize ), + meCharSet( rImplFont.meCharSet ), + maLanguageTag( rImplFont.maLanguageTag ), + maCJKLanguageTag( rImplFont.maCJKLanguageTag ), + mbSymbolFlag( rImplFont.mbSymbolFlag ), + 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 ) +{} + +bool ImplFont::operator==( 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( (maColor != rOther.maColor) + || (maFillColor != rOther.maFillColor) ) + 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) + || (mbTransparent != rOther.mbTransparent) ) + return false; + + return true; +} + +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 000000000..20e8e1b65 --- /dev/null +++ b/vcl/source/font/fontattributes.cxx @@ -0,0 +1,62 @@ +/* -*- 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 ), + meCharSet( RTL_TEXTENCODING_DONTKNOW ), + mbSymbolFlag( 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 (mbSymbolFlag != rOther.mbSymbolFlag) + 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 000000000..a37154d27 --- /dev/null +++ b/vcl/source/font/fontcache.cxx @@ -0,0 +1,278 @@ +/* -*- 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 <fontinstance.hxx> +#include <impfontcache.hxx> +#include <PhysicalFontCollection.hxx> +#include <PhysicalFontFace.hxx> +#include <PhysicalFontFamily.hxx> +#include <sal/log.hxx> + +#if !(defined(_WIN32) || defined(MACOSX) || defined(IOS)) +#include <unx/glyphcache.hxx> +#endif + +size_t ImplFontCache::IFSD_Hash::operator()( const FontSelectPattern& rFSD ) const +{ + return rFSD.hashCode(); +} + +bool ImplFontCache::IFSD_Equal::operator()(const FontSelectPattern& rA, const 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.IsSymbolFont() || rB.IsSymbolFont()) + { + if (rA.maTargetName != rB.maTargetName) + return false; + } + + // check for features + if ((rA.maTargetName.indexOf(FontSelectPattern::FEAT_PREFIX) + != -1 || + rB.maTargetName.indexOf(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(0) + // The cache limit is set by the rough number of characters needed to read your average Asian newspaper. + , m_aBoundRectCache(3000) +{} + +ImplFontCache::~ImplFontCache() +{ + 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 + FontSelectPattern aFontSelData(rFont, rFont.GetFamilyName(), rSize, fExactHeight, bNonAntialias); + return GetFontInstance( pFontList, aFontSelData ); +} + +rtl::Reference<LogicalFontInstance> ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList, + FontSelectPattern& aFontSelData ) +{ + 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 + { + 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->IsSymbolFont() || aFontSelData.IsSymbolFont() ) + { + 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( "Symbol", "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] (FontInstanceListPair 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] (GlyphBoundRectCachePair 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, + 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("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() +{ + // #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 000000000..af8533451 --- /dev/null +++ b/vcl/source/font/fontcharmap.cxx @@ -0,0 +1,634 @@ +/* + * 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 <vcl/fontcharmap.hxx> +#include <impfontcharmap.hxx> +#include <rtl/textcvt.h> +#include <rtl/textenc.h> +#include <sal/log.hxx> + +#include <vector> +#include <set> + +CmapResult::CmapResult( bool bSymbolic, + const sal_UCS4* pRangeCodes, int nRangeCount ) +: mpRangeCodes( pRangeCodes) +, mpStartGlyphs( nullptr) +, mpGlyphIds( nullptr) +, mnRangeCount( nRangeCount) +, mbSymbolic( bSymbolic) +, mbRecoded( false) +{} + +static ImplFontCharMapRef g_pDefaultImplFontCharMap; +static const sal_UCS4 aDefaultUnicodeRanges[] = {0x0020,0xD800, 0xE000,0xFFF0}; +static const sal_UCS4 aDefaultSymbolRanges[] = {0x0020,0x0100, 0xF020,0xF100}; + +ImplFontCharMap::~ImplFontCharMap() +{ + if( !isDefaultMap() ) + { + delete[] mpRangeCodes; + delete[] mpStartGlyphs; + delete[] mpGlyphIds; + } +} + +ImplFontCharMap::ImplFontCharMap( const CmapResult& rCR ) +: mpRangeCodes( rCR.mpRangeCodes ) +, mpStartGlyphs( rCR.mpStartGlyphs ) +, mpGlyphIds( rCR.mpGlyphIds ) +, mnRangeCount( rCR.mnRangeCount ) +, mnCharCount( 0 ) +{ + const sal_UCS4* pRangePtr = mpRangeCodes; + for( int i = mnRangeCount; --i >= 0; pRangePtr += 2 ) + { + sal_UCS4 cFirst = pRangePtr[0]; + sal_UCS4 cLast = pRangePtr[1]; + mnCharCount += cLast - cFirst; + } +} + +ImplFontCharMapRef const & ImplFontCharMap::getDefaultMap( bool bSymbols ) +{ + const sal_UCS4* pRangeCodes = aDefaultUnicodeRanges; + int nCodesCount = SAL_N_ELEMENTS(aDefaultUnicodeRanges); + if( bSymbols ) + { + pRangeCodes = aDefaultSymbolRanges; + nCodesCount = SAL_N_ELEMENTS(aDefaultSymbolRanges); + } + + CmapResult aDefaultCR( bSymbols, pRangeCodes, nCodesCount/2 ); + g_pDefaultImplFontCharMap = ImplFontCharMapRef(new ImplFontCharMap(aDefaultCR)); + + return g_pDefaultImplFontCharMap; +} + +bool ImplFontCharMap::isDefaultMap() const +{ + const bool bIsDefault = (mpRangeCodes == aDefaultUnicodeRanges) || (mpRangeCodes == aDefaultSymbolRanges); + return bIsDefault; +} + +static unsigned GetUInt( const unsigned char* p ) { return((p[0]<<24)+(p[1]<<16)+(p[2]<<8)+p[3]);} +static unsigned GetUShort( const unsigned char* p ){ return((p[0]<<8) | p[1]);} +static int GetSShort( const unsigned char* p ){ return static_cast<sal_Int16>((p[0]<<8)|p[1]);} + +// TODO: move CMAP parsing directly into the ImplFontCharMap class +bool ParseCMAP( const unsigned char* pCmap, int nLength, CmapResult& rResult ) +{ + rResult.mpRangeCodes = nullptr; + rResult.mpStartGlyphs= nullptr; + rResult.mpGlyphIds = nullptr; + rResult.mnRangeCount = 0; + rResult.mbRecoded = false; + rResult.mbSymbolic = false; + + // 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) || (nLength < (24 + 8*nSubTables)) ) + return false; + + const unsigned char* pEndValidArea = pCmap + nLength; + + // find the most interesting subtable in the CMAP + rtl_TextEncoding eRecodeFrom = RTL_TEXTENCODING_UNICODE; + int nOffset = 0; + int nFormat = -1; + int nBestVal = 0; + for( const unsigned char* p = pCmap + 4; --nSubTables >= 0; p += 8 ) + { + int nPlatform = GetUShort( p ); + int nEncoding = GetUShort( p+2 ); + int nPlatformEncoding = (nPlatform << 8) + nEncoding; + + int nValue; + rtl_TextEncoding eTmpEncoding = RTL_TEXTENCODING_UNICODE; + switch( nPlatformEncoding ) + { + case 0x000: nValue = 20; break; // Unicode 1.0 + case 0x001: nValue = 21; break; // Unicode 1.1 + case 0x002: nValue = 22; break; // iso10646_1993 + case 0x003: nValue = 23; break; // UCS-2 + case 0x004: nValue = 24; break; // UCS-4 + case 0x100: nValue = 22; break; // Mac Unicode<2.0 + case 0x103: nValue = 23; break; // Mac Unicode>2.0 + case 0x300: nValue = 5; rResult.mbSymbolic = true; break; // Win Symbol + case 0x301: nValue = 28; break; // Win UCS-2 + case 0x30A: nValue = 29; break; // Win-UCS-4 + case 0x302: nValue = 11; eTmpEncoding = RTL_TEXTENCODING_SHIFT_JIS; break; + case 0x303: nValue = 12; eTmpEncoding = RTL_TEXTENCODING_GB_18030; break; + case 0x304: nValue = 11; eTmpEncoding = RTL_TEXTENCODING_BIG5; break; + case 0x305: nValue = 11; eTmpEncoding = RTL_TEXTENCODING_MS_949; break; + case 0x306: nValue = 11; eTmpEncoding = RTL_TEXTENCODING_MS_1361; break; + default: nValue = 0; break; + } + + if( nValue <= 0 ) // ignore unknown encodings + continue; + + int nTmpOffset = GetUInt( p+4 ); + + if (nTmpOffset > nLength - 2 || nTmpOffset < 0) + continue; + + int nTmpFormat = GetUShort( pCmap + nTmpOffset ); + if( nTmpFormat == 12 ) // 32bit code -> glyph map format + nValue += 3; + else if( nTmpFormat != 4 ) // 16bit code -> glyph map format + continue; // ignore other formats + + if( nBestVal < nValue ) + { + nBestVal = nValue; + nOffset = nTmpOffset; + nFormat = nTmpFormat; + eRecodeFrom = eTmpEncoding; + } + } + + // parse the best CMAP subtable + int nRangeCount = 0; + sal_UCS4* pCodePairs = nullptr; + int* pStartGlyphs = nullptr; + + std::vector<sal_uInt16> aGlyphIdArray; + aGlyphIdArray.reserve( 0x1000 ); + aGlyphIdArray.push_back( 0 ); + + // format 4, the most common 16bit char mapping table + if( (nFormat == 4) && ((nOffset+16) < nLength) ) + { + int nSegCountX2 = GetUShort( pCmap + nOffset + 6 ); + nRangeCount = nSegCountX2/2 - 1; + if (nRangeCount < 0) + { + SAL_WARN("vcl.gdi", "negative RangeCount"); + nRangeCount = 0; + } + + const unsigned char* pLimitBase = pCmap + nOffset + 14; + const unsigned char* pBeginBase = pLimitBase + nSegCountX2 + 2; + const unsigned char* pDeltaBase = pBeginBase + nSegCountX2; + const unsigned char* pOffsetBase = pDeltaBase + nSegCountX2; + + const int nOffsetBaseStart = pOffsetBase - pCmap; + const int nRemainingLen = nLength - nOffsetBaseStart; + const int nMaxPossibleRangeOffsets = nRemainingLen / 2; + if (nRangeCount > nMaxPossibleRangeOffsets) + { + SAL_WARN("vcl.gdi", "more range offsets requested then space available"); + nRangeCount = std::max(0, nMaxPossibleRangeOffsets); + } + + pCodePairs = new sal_UCS4[ nRangeCount * 2 ]; + pStartGlyphs = new int[ nRangeCount ]; + + sal_UCS4* pCP = pCodePairs; + for( int i = 0; i < nRangeCount; ++i ) + { + const sal_UCS4 cMinChar = GetUShort( pBeginBase + 2*i ); + const sal_UCS4 cMaxChar = GetUShort( pLimitBase + 2*i ); + const int nGlyphDelta = GetSShort( pDeltaBase + 2*i ); + const int nRangeOffset = GetUShort( pOffsetBase + 2*i ); + if( cMinChar > cMaxChar ) { // no sane font should trigger this + SAL_WARN("vcl.gdi", "Min char should never be more than the max char!"); + break; + } + if( cMaxChar == 0xFFFF ) { + SAL_WARN("vcl.gdi", "Format 4 char should not be 0xFFFF"); + break; + } + if( !nRangeOffset ) { + // glyphid can be calculated directly + pStartGlyphs[i] = (cMinChar + nGlyphDelta) & 0xFFFF; + } else { + // update the glyphid-array with the glyphs in this range + pStartGlyphs[i] = -static_cast<int>(aGlyphIdArray.size()); + const unsigned char* pGlyphIdPtr = pOffsetBase + 2*i + nRangeOffset; + const size_t nRemainingSize = pEndValidArea >= pGlyphIdPtr ? pEndValidArea - pGlyphIdPtr : 0; + const size_t nMaxPossibleRecords = nRemainingSize/2; + if (nMaxPossibleRecords == 0) { // no sane font should trigger this + SAL_WARN("vcl.gdi", "More indexes claimed that space available in font!"); + break; + } + const size_t nMaxLegalChar = cMinChar + nMaxPossibleRecords-1; + if (cMaxChar > nMaxLegalChar) { // no sane font should trigger this + SAL_WARN("vcl.gdi", "More indexes claimed that space available in font!"); + break; + } + for( sal_UCS4 c = cMinChar; c <= cMaxChar; ++c, pGlyphIdPtr+=2 ) { + const int nGlyphIndex = GetUShort( pGlyphIdPtr ) + nGlyphDelta; + aGlyphIdArray.push_back( static_cast<sal_uInt16>(nGlyphIndex) ); + } + } + *(pCP++) = cMinChar; + *(pCP++) = cMaxChar + 1; + } + nRangeCount = (pCP - pCodePairs) / 2; + } + // format 12, the most common 32bit char mapping table + else if( (nFormat == 12) && ((nOffset+16) < nLength) ) + { + nRangeCount = GetUInt( pCmap + nOffset + 12 ); + if (nRangeCount < 0) + { + SAL_WARN("vcl.gdi", "negative RangeCount"); + nRangeCount = 0; + } + + const int nGroupOffset = nOffset + 16; + const int nRemainingLen = nLength - nGroupOffset; + const int nMaxPossiblePairs = nRemainingLen / 12; + if (nRangeCount > nMaxPossiblePairs) + { + SAL_WARN("vcl.gdi", "more code pairs requested then space available"); + nRangeCount = std::max(0, nMaxPossiblePairs); + } + + pCodePairs = new sal_UCS4[ nRangeCount * 2 ]; + pStartGlyphs = new int[ nRangeCount ]; + + const unsigned char* pGroup = pCmap + nGroupOffset; + sal_UCS4* pCP = pCodePairs; + for( int i = 0; i < nRangeCount; ++i ) + { + sal_UCS4 cMinChar = GetUInt( pGroup + 0 ); + sal_UCS4 cMaxChar = GetUInt( pGroup + 4 ); + int nGlyphId = GetUInt( pGroup + 8 ); + pGroup += 12; + + if( cMinChar > cMaxChar ) { // no sane font should trigger this + SAL_WARN("vcl.gdi", "Min char should never be more than the max char!"); + break; + } + + *(pCP++) = cMinChar; + *(pCP++) = cMaxChar + 1; + pStartGlyphs[i] = nGlyphId; + } + nRangeCount = (pCP - pCodePairs) / 2; + } + + // check if any subtable resulted in something usable + if( nRangeCount <= 0 ) + { + delete[] pCodePairs; + delete[] pStartGlyphs; + + // even when no CMAP is available we know it for symbol fonts + if( rResult.mbSymbolic ) + { + pCodePairs = new sal_UCS4[4]; + pCodePairs[0] = 0x0020; // aliased symbols + pCodePairs[1] = 0x0100; + pCodePairs[2] = 0xF020; // original symbols + pCodePairs[3] = 0xF100; + rResult.mpRangeCodes = pCodePairs; + rResult.mnRangeCount = 2; + return true; + } + + return false; + } + + // recode the code ranges to their unicode encoded ranges if needed + rtl_TextToUnicodeConverter aConverter = nullptr; + rtl_UnicodeToTextContext aCvtContext = nullptr; + + rResult.mbRecoded = ( eRecodeFrom != RTL_TEXTENCODING_UNICODE ); + if( rResult.mbRecoded ) + { + aConverter = rtl_createTextToUnicodeConverter( eRecodeFrom ); + aCvtContext = rtl_createTextToUnicodeContext( aConverter ); + } + + if( aConverter && aCvtContext ) + { + // determine the set of supported code points from encoded ranges + std::set<sal_UCS4> aSupportedCodePoints; + + static const int NINSIZE = 64; + static const int NOUTSIZE = 64; + std::vector<char> cCharsInp; + cCharsInp.reserve(NINSIZE); + sal_Unicode cCharsOut[ NOUTSIZE ]; + sal_UCS4* pCP = pCodePairs; + for( int i = 0; i < nRangeCount; ++i ) + { + sal_UCS4 cMin = *(pCP++); + sal_UCS4 cEnd = *(pCP++); + // ofz#25868 the conversion only makes sense with + // input codepoints in 0..SAL_MAX_UINT16 range + while (cMin < cEnd && cMin <= SAL_MAX_UINT16) + { + for (int j = 0; (cMin < cEnd) && (j < NINSIZE); ++cMin, ++j) + { + if( cMin >= 0x0100 ) + cCharsInp.push_back(static_cast<char>(cMin >> 8)); + if( (cMin >= 0x0100) || (cMin < 0x00A0) ) + cCharsInp.push_back(static_cast<char>(cMin)); + } + + sal_uInt32 nCvtInfo; + sal_Size nSrcCvtBytes; + int nOutLen = rtl_convertTextToUnicode( + aConverter, aCvtContext, + cCharsInp.data(), cCharsInp.size(), cCharsOut, NOUTSIZE, + RTL_TEXTTOUNICODE_FLAGS_INVALID_IGNORE + | RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_IGNORE, + &nCvtInfo, &nSrcCvtBytes ); + + cCharsInp.clear(); + + for (int j = 0; j < nOutLen; ++j) + aSupportedCodePoints.insert( cCharsOut[j] ); + } + } + + rtl_destroyTextToUnicodeConverter( aCvtContext ); + rtl_destroyTextToUnicodeConverter( aConverter ); + + // convert the set of supported code points to ranges + std::vector<sal_UCS4> aSupportedRanges; + + for (auto const& supportedPoint : aSupportedCodePoints) + { + if( aSupportedRanges.empty() + || (aSupportedRanges.back() != supportedPoint) ) + { + // add new range beginning with current unicode + aSupportedRanges.push_back(supportedPoint); + aSupportedRanges.push_back( 0 ); + } + + // extend existing range to include current unicode + aSupportedRanges.back() = supportedPoint + 1; + } + + // glyph mapping for non-unicode fonts not implemented + delete[] pStartGlyphs; + pStartGlyphs = nullptr; + aGlyphIdArray.clear(); + + // make a pCodePairs array using the vector from above + delete[] pCodePairs; + nRangeCount = aSupportedRanges.size() / 2; + if( nRangeCount <= 0 ) + return false; + pCodePairs = new sal_UCS4[ nRangeCount * 2 ]; + pCP = pCodePairs; + for (auto const& supportedRange : aSupportedRanges) + *(pCP++) = supportedRange; + } + + // prepare the glyphid-array if needed + // TODO: merge ranges if they are close enough? + sal_uInt16* pGlyphIds = nullptr; + if( !aGlyphIdArray.empty()) + { + pGlyphIds = new sal_uInt16[ aGlyphIdArray.size() ]; + sal_uInt16* pOut = pGlyphIds; + for (auto const& glyphId : aGlyphIdArray) + *(pOut++) = glyphId; + } + + // update the result struct + rResult.mpRangeCodes = pCodePairs; + rResult.mpStartGlyphs = pStartGlyphs; + rResult.mnRangeCount = nRangeCount; + rResult.mpGlyphIds = pGlyphIds; + return true; +} + +FontCharMap::FontCharMap() + : mpImplFontCharMap( ImplFontCharMap::getDefaultMap() ) +{ +} + +FontCharMap::FontCharMap( ImplFontCharMapRef const & pIFCMap ) + : mpImplFontCharMap( pIFCMap ) +{ +} + +FontCharMap::FontCharMap( const CmapResult& rCR ) + : mpImplFontCharMap(new ImplFontCharMap(rCR)) +{ +} + +FontCharMap::~FontCharMap() +{ + mpImplFontCharMap = nullptr; +} + +FontCharMapRef FontCharMap::GetDefaultMap( bool bSymbol ) +{ + FontCharMapRef xFontCharMap( new FontCharMap( ImplFontCharMap::getDefaultMap( bSymbol ) ) ); + return xFontCharMap; +} + +bool FontCharMap::IsDefaultMap() const +{ + return mpImplFontCharMap->isDefaultMap(); +} + +int FontCharMap::GetCharCount() const +{ + return mpImplFontCharMap->mnCharCount; +} + +int FontCharMap::CountCharsInRange( sal_UCS4 cMin, sal_UCS4 cMax ) const +{ + int nCount = 0; + + // find and adjust range and char count for cMin + int nRangeMin = findRangeIndex( cMin ); + if( nRangeMin & 1 ) + ++nRangeMin; + else if( cMin > mpImplFontCharMap->mpRangeCodes[ nRangeMin ] ) + nCount -= cMin - mpImplFontCharMap->mpRangeCodes[ nRangeMin ]; + + // find and adjust range and char count for cMax + int nRangeMax = findRangeIndex( cMax ); + if( nRangeMax & 1 ) + --nRangeMax; + else + nCount -= mpImplFontCharMap->mpRangeCodes[ nRangeMax+1 ] - cMax - 1; + + // count chars in complete ranges between cMin and cMax + for( int i = nRangeMin; i <= nRangeMax; i+=2 ) + nCount += mpImplFontCharMap->mpRangeCodes[i+1] - mpImplFontCharMap->mpRangeCodes[i]; + + return nCount; +} + +bool FontCharMap::HasChar( sal_UCS4 cChar ) const +{ + bool bHasChar = false; + + if( mpImplFontCharMap->mpStartGlyphs == nullptr ) { // only the char-ranges are known + const int nRange = findRangeIndex( cChar ); + if( nRange==0 && cChar < mpImplFontCharMap->mpRangeCodes[0] ) + return false; + bHasChar = ((nRange & 1) == 0); // inside a range + } else { // glyph mapping is available + const int nGlyphIndex = GetGlyphIndex( cChar ); + bHasChar = (nGlyphIndex != 0); // not the notdef-glyph + } + + return bHasChar; +} + +sal_UCS4 FontCharMap::GetFirstChar() const +{ + return mpImplFontCharMap->mpRangeCodes[0]; +} + +sal_UCS4 FontCharMap::GetLastChar() const +{ + return (mpImplFontCharMap->mpRangeCodes[ 2*mpImplFontCharMap->mnRangeCount-1 ] - 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->mpRangeCodes[ 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->mpRangeCodes[ nRange ] - 1); // => last in prev range + return (cChar - 1); +} + +int FontCharMap::GetIndexFromChar( sal_UCS4 cChar ) const +{ + // TODO: improve linear walk? + int nCharIndex = 0; + const sal_UCS4* pRange = &mpImplFontCharMap->mpRangeCodes[0]; + for( int i = 0; i < mpImplFontCharMap->mnRangeCount; ++i ) + { + sal_UCS4 cFirst = *(pRange++); + sal_UCS4 cLast = *(pRange++); + 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 sal_UCS4* pRange = &mpImplFontCharMap->mpRangeCodes[0]; + for( int i = 0; i < mpImplFontCharMap->mnRangeCount; ++i ) + { + sal_UCS4 cFirst = *(pRange++); + sal_UCS4 cLast = *(pRange++); + nIndex -= cLast - cFirst; + if( nIndex < 0 ) + return (cLast + nIndex); + } + + // we can only get here with an out-of-bounds charindex + return mpImplFontCharMap->mpRangeCodes[0]; +} + +int FontCharMap::findRangeIndex( sal_UCS4 cChar ) const +{ + int nLower = 0; + int nMid = mpImplFontCharMap->mnRangeCount; + int nUpper = 2 * mpImplFontCharMap->mnRangeCount - 1; + while( nLower < nUpper ) + { + if( cChar >= mpImplFontCharMap->mpRangeCodes[ nMid ] ) + nLower = nMid; + else + nUpper = nMid - 1; + nMid = (nLower + nUpper + 1) / 2; + } + + return nMid; +} + +int FontCharMap::GetGlyphIndex( sal_UCS4 cChar ) const +{ + // return -1 if the object doesn't know the glyph ids + if( !mpImplFontCharMap->mpStartGlyphs ) + return -1; + + // return 0 if the unicode doesn't have a matching glyph + int nRange = findRangeIndex( cChar ); + // check that we are inside any range + if( (nRange == 0) && (cChar < mpImplFontCharMap->mpRangeCodes[0]) ) { + // symbol aliasing gives symbol fonts a second chance + const bool bSymbolic = cChar <= 0xFF && (mpImplFontCharMap->mpRangeCodes[0]>=0xF000) && + (mpImplFontCharMap->mpRangeCodes[1]<=0xF0FF); + if( !bSymbolic ) + return 0; + // check for symbol aliasing (U+F0xx -> U+00xx) + cChar |= 0xF000; + nRange = findRangeIndex( cChar ); + if( (nRange == 0) && (cChar < mpImplFontCharMap->mpRangeCodes[0]) ) { + return 0; + } + } + // check that we are inside a range + if( (nRange & 1) != 0 ) + return 0; + + // get glyph index directly or indirectly + int nGlyphIndex = cChar - mpImplFontCharMap->mpRangeCodes[ nRange ]; + const int nStartIndex = mpImplFontCharMap->mpStartGlyphs[ nRange/2 ]; + if( nStartIndex >= 0 ) { + // the glyph index can be calculated + nGlyphIndex += nStartIndex; + } else { + // the glyphid array has the glyph index + nGlyphIndex = mpImplFontCharMap->mpGlyphIds[ nGlyphIndex - nStartIndex]; + } + + return nGlyphIndex; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontinstance.cxx b/vcl/source/font/fontinstance.cxx new file mode 100644 index 000000000..40e334bd6 --- /dev/null +++ b/vcl/source/font/fontinstance.cxx @@ -0,0 +1,168 @@ +/* -*- 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 <hb-ot.h> +#include <hb-graphite2.h> + +#include <fontinstance.hxx> +#include <impfontcache.hxx> + +#include <PhysicalFontFace.hxx> + +// extend std namespace to add custom hash needed for LogicalFontInstance + +namespace std +{ + template <> struct hash< pair< sal_UCS4, FontWeight > > + { + size_t operator()(const pair< sal_UCS4, FontWeight >& rData) const + { + std::size_t seed = 0; + boost::hash_combine(seed, rData.first); + boost::hash_combine(seed, rData.second); + return seed; + } + }; +} + + +LogicalFontInstance::LogicalFontInstance(const PhysicalFontFace& rFontFace, const FontSelectPattern& rFontSelData ) + : mxFontMetric( new ImplFontMetricData( 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<PhysicalFontFace&>(rFontFace)) +{ +} + +LogicalFontInstance::~LogicalFontInstance() +{ + mpUnicodeFallbackList.reset(); + mpFontCache = nullptr; + mxFontMetric = nullptr; + + if (m_pHbFont) + hb_font_destroy(m_pHbFont); +} + +hb_font_t* LogicalFontInstance::InitHbFont(hb_face_t* pHbFace) +{ + assert(pHbFace); + hb_font_t* pHbFont = hb_font_create(pHbFace); + unsigned int nUPEM = hb_face_get_upem(pHbFace); + hb_font_set_scale(pHbFont, nUPEM, nUPEM); + hb_ot_font_set_funcs(pHbFont); + // hb_font_t keeps a reference to hb_face_t, so destroy this one. + hb_face_destroy(pHbFace); + return pHbFont; +} + +int LogicalFontInstance::GetKashidaWidth() +{ + hb_font_t* pHbFont = GetHbFont(); + hb_position_t nWidth = 0; + hb_codepoint_t nIndex = 0; + + if (hb_font_get_glyph(pHbFont, 0x0640, 0, &nIndex)) + { + double nXScale = 0; + GetScale(&nXScale, nullptr); + nWidth = hb_font_get_glyph_h_advance(pHbFont, nIndex) * nXScale; + } + + return nWidth; +} + +void LogicalFontInstance::GetScale(double* nXScale, double* nYScale) +{ + hb_face_t* pHbFace = hb_font_get_face(GetHbFont()); + unsigned int nUPEM = hb_face_get_upem(pHbFace); + + 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 ) +{ + if( !mpUnicodeFallbackList ) + mpUnicodeFallbackList.reset(new UnicodeFallbackList); + (*mpUnicodeFallbackList)[ std::pair< sal_UCS4, FontWeight >(cChar,eWeight) ] = rFontName; +} + +bool LogicalFontInstance::GetFallbackForUnicode( sal_UCS4 cChar, FontWeight eWeight, OUString* pFontName ) const +{ + if( !mpUnicodeFallbackList ) + return false; + + UnicodeFallbackList::const_iterator it = mpUnicodeFallbackList->find( std::pair< sal_UCS4, FontWeight >(cChar,eWeight) ); + if( it == mpUnicodeFallbackList->end() ) + return false; + + *pFontName = (*it).second; + return true; +} + +void LogicalFontInstance::IgnoreFallbackForUnicode( sal_UCS4 cChar, FontWeight eWeight, const OUString& rFontName ) +{ + UnicodeFallbackList::iterator it = mpUnicodeFallbackList->find( std::pair< sal_UCS4,FontWeight >(cChar,eWeight) ); + if( it == mpUnicodeFallbackList->end() ) + return; + if( (*it).second == rFontName ) + mpUnicodeFallbackList->erase( it ); +} + +bool LogicalFontInstance::GetGlyphBoundRect(sal_GlyphId nID, tools::Rectangle &rRect, bool bVertical) const +{ + if (mpFontCache && mpFontCache->GetCachedGlyphBoundRect(this, nID, rRect)) + return true; + + bool res = ImplGetGlyphBoundRect(nID, rRect, bVertical); + if (mpFontCache && res) + mpFontCache->CacheGlyphBoundRect(this, nID, rRect); + return res; +} + +bool LogicalFontInstance::IsGraphiteFont() +{ + if (!m_xbIsGraphiteFont) + { + m_xbIsGraphiteFont = hb_graphite2_face_get_gr_face(hb_font_get_face(GetHbFont())) != nullptr; + } + return *m_xbIsGraphiteFont; +} + +/* 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 000000000..3b7a7ed09 --- /dev/null +++ b/vcl/source/font/fontmetric.cxx @@ -0,0 +1,394 @@ +/* -*- 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 <i18nlangtag/mslangid.hxx> +#include <officecfg/Office/Common.hxx> +#include <unotools/configmgr.hxx> +#include <vcl/metric.hxx> +#include <vcl/outdev.hxx> +#include <sal/log.hxx> + +#include <fontinstance.hxx> +#include <fontselect.hxx> +#include <impfontmetricdata.hxx> +#include <sft.hxx> + +#include <com/sun/star/uno/Sequence.hxx> +#include <comphelper/sequence.hxx> + +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 ), + mbFullstopCentered( false ) +{} + +FontMetric::FontMetric( const FontMetric& rFontMetric ) = default; + +FontMetric::~FontMetric() +{ +} + +FontMetric& FontMetric::operator=(const FontMetric& rFontMetric) = default; + +FontMetric& FontMetric::operator=(FontMetric&& rFontMetric) = default; + +bool FontMetric::operator==( const FontMetric& r ) const +{ + if( Font::operator!=(r) ) + return false; + 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; +} + +ImplFontMetricData::ImplFontMetricData( const 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 ) + , 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( GetNextFontToken( rFontSelData.GetFamilyName(), nTokenPos ) ); + SetStyleName( rFontSelData.GetStyleName() ); +} + +void ImplFontMetricData::ImplInitTextLineSize( const OutputDevice* pDev ) +{ + 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; + + long nLineHeight = ((nDescent*25)+50) / 100; + if ( !nLineHeight ) + nLineHeight = 1; + long nLineHeight2 = nLineHeight / 2; + if ( !nLineHeight2 ) + nLineHeight2 = 1; + + long nBLineHeight = ((nDescent*50)+50) / 100; + if ( nBLineHeight == nLineHeight ) + nBLineHeight++; + long nBLineHeight2 = nBLineHeight/2; + if ( !nBLineHeight2 ) + nBLineHeight2 = 1; + + long n2LineHeight = ((nDescent*16)+50) / 100; + if ( !n2LineHeight ) + n2LineHeight = 1; + long n2LineDY = n2LineHeight; + /* #117909# + * add some pixels to minimum double line distance on higher resolution devices + */ + long nMin2LineDY = 1 + pDev->GetDPIY()/150; + if ( n2LineDY < nMin2LineDY ) + n2LineDY = nMin2LineDY; + long n2LineDY2 = n2LineDY/2; + if ( !n2LineDY2 ) + n2LineDY2 = 1; + + const vcl::Font& rFont ( pDev->GetFont() ); + bool bCJKVertical = MsLangId::isCJK(rFont.GetLanguage()) && rFont.IsVertical(); + long nUnderlineOffset = bCJKVertical ? mnDescent : (mnDescent/2 + 1); + long nStrikeoutOffset = -((mnAscent - mnIntLeading) / 3); + + mnUnderlineSize = nLineHeight; + mnUnderlineOffset = nUnderlineOffset - nLineHeight2; + + mnBUnderlineSize = nBLineHeight; + mnBUnderlineOffset = nUnderlineOffset - nBLineHeight2; + + mnDUnderlineSize = n2LineHeight; + mnDUnderlineOffset1 = nUnderlineOffset - n2LineDY2 - n2LineHeight; + mnDUnderlineOffset2 = mnDUnderlineOffset1 + n2LineDY + n2LineHeight; + + 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; + + mnBulletOffset = ( pDev->GetTextWidth( OUString( u' ' ) ) - pDev->GetTextWidth( OUString( u'\x00b7' ) ) ) >> 1 ; + +} + + +void ImplFontMetricData::ImplInitAboveTextLineSize() +{ + 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; + } + + long nLineHeight = ((nIntLeading*25)+50) / 100; + if ( !nLineHeight ) + nLineHeight = 1; + + long nBLineHeight = ((nIntLeading*50)+50) / 100; + if ( nBLineHeight == nLineHeight ) + nBLineHeight++; + + long n2LineHeight = ((nIntLeading*16)+50) / 100; + if ( !n2LineHeight ) + n2LineHeight = 1; + + long nCeiling = -mnAscent; + + mnAboveUnderlineSize = nLineHeight; + mnAboveUnderlineOffset = nCeiling + (nIntLeading - nLineHeight + 1) / 2; + + mnAboveBUnderlineSize = nBLineHeight; + mnAboveBUnderlineOffset = nCeiling + (nIntLeading - nBLineHeight + 1) / 2; + + mnAboveDUnderlineSize = n2LineHeight; + mnAboveDUnderlineOffset1 = nCeiling + (nIntLeading - 3*n2LineHeight + 1) / 2; + mnAboveDUnderlineOffset2 = nCeiling + (nIntLeading + n2LineHeight + 1) / 2; + + long nWCalcSize = nIntLeading; + if ( nWCalcSize < 6 ) + { + if ( (nWCalcSize == 1) || (nWCalcSize == 2) ) + mnAboveWUnderlineSize = nWCalcSize; + else + mnAboveWUnderlineSize = 3; + } + else + mnAboveWUnderlineSize = ((nWCalcSize*50)+50) / 100; + + mnAboveWUnderlineOffset = nCeiling + (nIntLeading + 1) / 2; +} + +void ImplFontMetricData::ImplInitFlags( const OutputDevice* pDev ) +{ + const vcl::Font& rFont ( pDev->GetFont() ); + bool bCentered = true; + if (MsLangId::isCJK(rFont.GetLanguage())) + { + const OUString sFullstop( u'\x3001' ); // Fullwidth fullstop + tools::Rectangle aRect; + pDev->GetTextBoundRect( aRect, sFullstop ); + 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 ImplFontMetricData::ShouldUseWinMetrics(const vcl::TTGlobalFontInfo& rInfo) +{ + if (utl::ConfigManager::IsFuzzing()) + return false; + + OUString aFontIdentifier( + GetFamilyName() + "," + + OUString::number(rInfo.ascender) + "," + OUString::number(rInfo.descender) + "," + + OUString::number(rInfo.typoAscender) + "," + OUString::number(rInfo.typoDescender) + "," + + OUString::number(rInfo.winAscent) + "," + OUString::number(rInfo.winDescent)); + + 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; +} + +/* + * Calculate line spacing: + * + * - 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. +*/ +void ImplFontMetricData::ImplCalcLineSpacing(LogicalFontInstance *pFontInstance) +{ + mnAscent = mnDescent = mnExtLeading = mnIntLeading = 0; + + hb_font_t* pHbFont = pFontInstance->GetHbFont(); + hb_face_t* pHbFace = hb_font_get_face(pHbFont); + + hb_blob_t* pHhea = hb_face_reference_table(pHbFace, HB_TAG('h', 'h', 'e', 'a')); + hb_blob_t* pOS2 = hb_face_reference_table(pHbFace, HB_TAG('O', 'S', '/', '2')); + + vcl::TTGlobalFontInfo rInfo = {}; + GetTTFontMetrics(reinterpret_cast<const uint8_t*>(hb_blob_get_data(pHhea, nullptr)), hb_blob_get_length(pHhea), + reinterpret_cast<const uint8_t*>(hb_blob_get_data(pOS2, nullptr)), hb_blob_get_length(pOS2), + &rInfo); + + hb_blob_destroy(pHhea); + hb_blob_destroy(pOS2); + + double nUPEM = hb_face_get_upem(pHbFace); + double fScale = mnHeight / nUPEM; + double fAscent = 0, fDescent = 0, fExtLeading = 0; + + // Try hhea table first. + // tdf#107605: Some fonts have weird values here, so check that ascender is + // +ve and descender is -ve as they normally should. + if (rInfo.ascender >= 0 && rInfo.descender <= 0) + { + fAscent = rInfo.ascender * fScale; + fDescent = -rInfo.descender * fScale; + fExtLeading = rInfo.linegap * fScale; + } + + // But if OS/2 is present, prefer it. + if (rInfo.winAscent || rInfo.winDescent || + rInfo.typoAscender || rInfo.typoDescender) + { + if (ShouldUseWinMetrics(rInfo) || (fAscent == 0.0 && fDescent == 0.0)) + { + fAscent = rInfo.winAscent * fScale; + fDescent = rInfo.winDescent * fScale; + fExtLeading = 0; + } + + const uint16_t kUseTypoMetricsMask = 1 << 7; + if (rInfo.fsSelection & kUseTypoMetricsMask && + rInfo.typoAscender >= 0 && rInfo.typoDescender <= 0) + { + fAscent = rInfo.typoAscender * fScale; + fDescent = -rInfo.typoDescender * fScale; + fExtLeading = rInfo.typoLineGap * fScale; + } + } + + mnAscent = round(fAscent); + mnDescent = round(fDescent); + mnExtLeading = round(fExtLeading); + + if (mnAscent || mnDescent) + mnIntLeading = mnAscent + mnDescent - mnHeight; + + SAL_INFO("vcl.gdi.fontmetric", GetFamilyName() + << ": fsSelection: " << rInfo.fsSelection + << ", typoAscender: " << rInfo.typoAscender + << ", typoDescender: " << rInfo.typoDescender + << ", typoLineGap: " << rInfo.typoLineGap + << ", winAscent: " << rInfo.winAscent + << ", winDescent: " << rInfo.winDescent + << ", ascender: " << rInfo.ascender + << ", descender: " << rInfo.descender + << ", linegap: " << rInfo.linegap + ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontselect.cxx b/vcl/source/font/fontselect.cxx new file mode 100644 index 000000000..faafdb61b --- /dev/null +++ b/vcl/source/font/fontselect.cxx @@ -0,0 +1,150 @@ +/* -*- 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 <vcl/font.hxx> + +#include <PhysicalFontFace.hxx> +#include <fontselect.hxx> + +// 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, + const OUString& rSearchName, const Size& rSize, float fExactHeight, bool bNonAntialias) + : maSearchName( rSearchName ) + , 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( 3600 <= static_cast<unsigned>(mnOrientation) ) + { + if( mnOrientation >= 0 ) + mnOrientation %= 3600; + else + mnOrientation = 3600 - (-mnOrientation % 3600); + } + + // 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; + 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: */ |