From ed5640d8b587fbcfed7dd7967f3de04b37a76f26 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:06:44 +0200 Subject: Adding upstream version 4:7.4.7. Signed-off-by: Daniel Baumann --- vcl/source/font/DirectFontSubstitution.cxx | 71 ++ vcl/source/font/Feature.cxx | 162 +++ vcl/source/font/FeatureCollector.cxx | 158 +++ vcl/source/font/FeatureParser.cxx | 70 ++ vcl/source/font/FontSelectPattern.cxx | 155 +++ vcl/source/font/OpenTypeFeatureDefinitionList.cxx | 200 ++++ vcl/source/font/PhysicalFontCollection.cxx | 1279 +++++++++++++++++++++ vcl/source/font/PhysicalFontFace.cxx | 206 ++++ vcl/source/font/PhysicalFontFamily.cxx | 269 +++++ vcl/source/font/font.cxx | 1155 +++++++++++++++++++ vcl/source/font/fontattributes.cxx | 62 + vcl/source/font/fontcache.cxx | 279 +++++ vcl/source/font/fontcharmap.cxx | 639 ++++++++++ vcl/source/font/fontinstance.cxx | 192 ++++ vcl/source/font/fontmetric.cxx | 468 ++++++++ 15 files changed, 5365 insertions(+) create mode 100644 vcl/source/font/DirectFontSubstitution.cxx create mode 100644 vcl/source/font/Feature.cxx create mode 100644 vcl/source/font/FeatureCollector.cxx create mode 100644 vcl/source/font/FeatureParser.cxx create mode 100644 vcl/source/font/FontSelectPattern.cxx create mode 100644 vcl/source/font/OpenTypeFeatureDefinitionList.cxx create mode 100644 vcl/source/font/PhysicalFontCollection.cxx create mode 100644 vcl/source/font/PhysicalFontFace.cxx create mode 100644 vcl/source/font/PhysicalFontFamily.cxx create mode 100644 vcl/source/font/font.cxx create mode 100644 vcl/source/font/fontattributes.cxx create mode 100644 vcl/source/font/fontcache.cxx create mode 100644 vcl/source/font/fontcharmap.cxx create mode 100644 vcl/source/font/fontinstance.cxx create mode 100644 vcl/source/font/fontmetric.cxx (limited to 'vcl/source/font') diff --git a/vcl/source/font/DirectFontSubstitution.cxx b/vcl/source/font/DirectFontSubstitution.cxx new file mode 100644 index 000000000..e494fb7ce --- /dev/null +++ b/vcl/source/font/DirectFontSubstitution.cxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include + +#include + +#include +#include + +namespace vcl::font +{ +void DirectFontSubstitution::AddFontSubstitute(const OUString& rFontName, + const OUString& rSubstFontName, + AddFontSubstituteFlags nFlags) +{ + maFontSubstList.emplace_back(rFontName, rSubstFontName, nFlags); +} + +void DirectFontSubstitution::RemoveFontsSubstitute() { maFontSubstList.clear(); } + +bool DirectFontSubstitution::FindFontSubstitute(OUString& rSubstName, + std::u16string_view rSearchName) const +{ + // TODO: get rid of O(N) searches + std::vector::const_iterator it = std::find_if( + maFontSubstList.begin(), maFontSubstList.end(), [&](const FontSubstEntry& s) { + return (s.mnFlags & AddFontSubstituteFlags::ALWAYS) && (s.maSearchName == rSearchName); + }); + if (it != maFontSubstList.end()) + { + rSubstName = it->maSearchReplaceName; + return true; + } + return false; +} + +void ImplFontSubstitute(OUString& rFontName) +{ + // must be canonicalised + assert(GetEnglishSearchFontName(rFontName) == rFontName); + OUString aSubstFontName; + // apply user-configurable font replacement (eg, from the list in Tools->Options) + const DirectFontSubstitution* pSubst = ImplGetSVData()->maGDIData.mpDirectFontSubst; + if (pSubst && pSubst->FindFontSubstitute(aSubstFontName, rFontName)) + { + rFontName = aSubstFontName; + return; + } +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/Feature.cxx b/vcl/source/font/Feature.cxx new file mode 100644 index 000000000..ba4b09a5d --- /dev/null +++ b/vcl/source/font/Feature.cxx @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#include +#include +#include + +#include + +namespace vcl::font +{ +OUString featureCodeAsString(uint32_t nFeature) +{ + std::vector 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)) +{ +} + +FeatureParameter::FeatureParameter(uint32_t nCode, TranslateId pDescriptionID) + : m_nCode(nCode) + , m_pDescriptionID(pDescriptionID) +{ +} + +OUString FeatureParameter::getDescription() const +{ + OUString aReturnString; + + if (m_pDescriptionID) + aReturnString = VclResId(m_pDescriptionID); + else if (!m_sDescription.isEmpty()) + aReturnString = m_sDescription; + + return aReturnString; +} + +uint32_t FeatureParameter::getCode() const { return m_nCode; } + +// FeatureDefinition + +FeatureDefinition::FeatureDefinition() + : m_nCode(0) + , m_nDefault(0) + , m_eType(FeatureParameterType::BOOL) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, OUString const& rDescription, + FeatureParameterType eType, + std::vector&& rEnumParameters, + uint32_t nDefault) + : m_sDescription(rDescription) + , m_nCode(nCode) + , m_nDefault(nDefault) + , m_eType(eType) + , m_aEnumParameters(std::move(rEnumParameters)) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, TranslateId 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, TranslateId pDescriptionID, + std::vector aEnumParameters) + : m_pDescriptionID(pDescriptionID) + , m_nCode(nCode) + , m_nDefault(0) + , m_eType(FeatureParameterType::ENUM) + , m_aEnumParameters(std::move(aEnumParameters)) +{ +} + +const std::vector& 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..6cb1b14c5 --- /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 +#include + +#include +#include + +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(pLabel))); + gr_label_destroy(pLabel); + + std::vector 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(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, + std::move(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 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().isRequired(aFeatureTag)) + continue; + + m_rFontFeatures.emplace_back(); + vcl::font::Feature& rFeature = m_rFontFeatures.back(); + rFeature.m_aID = { aFeatureTag, aScriptTag, aLanguageTag }; + + FeatureDefinition aDefinition = OpenTypeFeatureDefinitionList().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 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 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..5182cea7a --- /dev/null +++ b/vcl/source/font/FeatureParser.cxx @@ -0,0 +1,70 @@ +/* -*- 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 +#include +#include + +namespace vcl::font +{ +OUString trimFontNameFeatures(OUString const& rFontName) +{ + const sal_Int32 nPrefixIdx{ rFontName.indexOf(vcl::font::FeaturePrefix) }; + + if (nPrefixIdx < 0) + return rFontName; + + return rFontName.copy(0, nPrefixIdx); +} + +FeatureParser::FeatureParser(std::u16string_view rFontName) +{ + size_t nPrefixIdx{ rFontName.find(vcl::font::FeaturePrefix) }; + + if (nPrefixIdx == std::u16string_view::npos) + return; + + std::u16string_view sName(rFontName.substr(++nPrefixIdx)); + sal_Int32 nIndex = 0; + do + { + std::u16string_view sToken = o3tl::getToken(sName, 0, vcl::font::FeatureSeparator, nIndex); + + sal_Int32 nInnerIdx{ 0 }; + std::u16string_view sID = o3tl::getToken(sToken, 0, '=', nInnerIdx); + + if (sID == u"lang") + { + m_sLanguage = o3tl::getToken(sToken, 0, '=', nInnerIdx); + } + else + { + OString sFeature = OUStringToOString(sToken, RTL_TEXTENCODING_ASCII_US); + FeatureSetting aFeature(sFeature); + if (aFeature.m_nTag != 0) + m_aFeatures.push_back(aFeature); + } + } while (nIndex >= 0); +} + +std::unordered_map FeatureParser::getFeaturesMap() const +{ + std::unordered_map 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/FontSelectPattern.cxx b/vcl/source/font/FontSelectPattern.cxx new file mode 100644 index 000000000..23e7673c8 --- /dev/null +++ b/vcl/source/font/FontSelectPattern.cxx @@ -0,0 +1,155 @@ +/* -*- 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 +#include +#include + +#include + +#include +#include + +namespace vcl::font +{ + +// These mustn't conflict with font name lists which use ; and , +const char FontSelectPattern::FEAT_PREFIX = ':'; +const char FontSelectPattern::FEAT_SEPARATOR = '&'; + +FontSelectPattern::FontSelectPattern( const vcl::Font& rFont, + 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( mnOrientation < 0_deg10 || mnOrientation >= 3600_deg10 ) + { + if( mnOrientation >= 0_deg10 ) + mnOrientation %= 3600_deg10; + else + mnOrientation = 3600_deg10 - (-mnOrientation % 3600_deg10); + } + + // normalize width and height + if( mnHeight < 0 ) + mnHeight = o3tl::saturating_toggle_sign(mnHeight); + if( mnWidth < 0 ) + mnWidth = o3tl::saturating_toggle_sign(mnWidth); +} + + +// NOTE: this ctor is still used on Windows. Do not remove. +#ifdef _WIN32 +FontSelectPattern::FontSelectPattern( const PhysicalFontFace& rFontData, + const Size& rSize, float fExactHeight, int nOrientation, bool bVertical ) + : FontAttributes( rFontData ) + , mnWidth( rSize.Width() ) + , mnHeight( rSize.Height() ) + , mfExactHeight( fExactHeight ) + , mnOrientation( nOrientation ) + , meLanguage( 0 ) + , mbVertical( bVertical ) + , mbNonAntialiased( false ) + , mbEmbolden( false ) +{ + maTargetName = maSearchName = GetFamilyName(); + // NOTE: no normalization for width/height/orientation +} + +#endif + +size_t FontSelectPattern::hashCode() const +{ + // TODO: does it pay off to improve this hash function? + size_t nHash; + // check for features and generate a unique hash if necessary + if (maTargetName.indexOf(FontSelectPattern::FEAT_PREFIX) + != -1) + { + nHash = maTargetName.hashCode(); + } + else + { + nHash = maSearchName.hashCode(); + } + nHash += 11U * mnHeight; + nHash += 19 * GetWeight(); + nHash += 29 * GetItalic(); + nHash += 37 * mnOrientation.get(); + nHash += 41 * static_cast(meLanguage); + if( mbVertical ) + nHash += 53; + return nHash; +} + +bool FontSelectPattern::operator==(const FontSelectPattern& rOther) const +{ + if (!CompareDeviceIndependentFontAttributes(rOther)) + return false; + + if (maTargetName != rOther.maTargetName) + return false; + + if (maSearchName != rOther.maSearchName) + return false; + + if (mnWidth != rOther.mnWidth) + return false; + + if (mnHeight != rOther.mnHeight) + return false; + + if (mfExactHeight != rOther.mfExactHeight) + return false; + + if (mnOrientation != rOther.mnOrientation) + return false; + + if (meLanguage != rOther.meLanguage) + return false; + + if (mbVertical != rOther.mbVertical) + return false; + + if (mbNonAntialiased != rOther.mbNonAntialiased) + return false; + + if (mbEmbolden != rOther.mbEmbolden) + return false; + + if (maItalicMatrix != rOther.maItalicMatrix) + return false; + + return true; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/OpenTypeFeatureDefinitionList.cxx b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx new file mode 100644 index 000000000..f49837cce --- /dev/null +++ b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx @@ -0,0 +1,200 @@ +/* -*- 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 +#include + +#include + +#include + +namespace vcl::font +{ +OpenTypeFeatureDefinitionListPrivate& OpenTypeFeatureDefinitionList() +{ + static OpenTypeFeatureDefinitionListPrivate SINGLETON; + return SINGLETON; +}; + +OpenTypeFeatureDefinitionListPrivate::OpenTypeFeatureDefinitionListPrivate() { init(); } + +void OpenTypeFeatureDefinitionListPrivate::init() +{ + m_aFeatureDefinition.assign({ + { featureCode("aalt"), STR_FONT_FEATURE_ID_AALT }, + { featureCode("afrc"), STR_FONT_FEATURE_ID_AFRC }, + { featureCode("alig"), STR_FONT_FEATURE_ID_ALIG }, + { featureCode("c2pc"), STR_FONT_FEATURE_ID_C2PC }, + { featureCode("c2sc"), STR_FONT_FEATURE_ID_C2SC }, + { featureCode("calt"), STR_FONT_FEATURE_ID_CALT }, + { featureCode("case"), STR_FONT_FEATURE_ID_CASE }, + { featureCode("clig"), STR_FONT_FEATURE_ID_CLIG }, + { featureCode("cpct"), STR_FONT_FEATURE_ID_CPCT }, + { featureCode("cpsp"), STR_FONT_FEATURE_ID_CPSP }, + { featureCode("cswh"), STR_FONT_FEATURE_ID_CSWH }, + { featureCode("dcap"), STR_FONT_FEATURE_ID_DCAP }, + { featureCode("dlig"), STR_FONT_FEATURE_ID_DLIG }, + { featureCode("dnom"), STR_FONT_FEATURE_ID_DNOM }, + { featureCode("dpng"), STR_FONT_FEATURE_ID_DPNG }, + { featureCode("expt"), STR_FONT_FEATURE_ID_EXPT }, + { featureCode("falt"), STR_FONT_FEATURE_ID_FALT }, + { featureCode("frac"), STR_FONT_FEATURE_ID_FRAC }, + { featureCode("fwid"), STR_FONT_FEATURE_ID_FWID }, + { featureCode("halt"), STR_FONT_FEATURE_ID_HALT }, + { featureCode("hist"), STR_FONT_FEATURE_ID_HIST }, + { featureCode("hkna"), STR_FONT_FEATURE_ID_HKNA }, + { featureCode("hlig"), STR_FONT_FEATURE_ID_HLIG }, + { featureCode("hngl"), STR_FONT_FEATURE_ID_HNGL }, + { featureCode("hojo"), STR_FONT_FEATURE_ID_HOJO }, + { featureCode("hwid"), STR_FONT_FEATURE_ID_HWID }, + { featureCode("ital"), STR_FONT_FEATURE_ID_ITAL }, + { featureCode("jalt"), STR_FONT_FEATURE_ID_JALT }, + { featureCode("jp78"), STR_FONT_FEATURE_ID_JP78 }, + { featureCode("jp83"), STR_FONT_FEATURE_ID_JP83 }, + { featureCode("jp90"), STR_FONT_FEATURE_ID_JP90 }, + { featureCode("jp04"), STR_FONT_FEATURE_ID_JP04 }, + { featureCode("kern"), STR_FONT_FEATURE_ID_KERN }, + { featureCode("lfbd"), STR_FONT_FEATURE_ID_LFBD }, + { featureCode("liga"), STR_FONT_FEATURE_ID_LIGA }, + { featureCode("lnum"), STR_FONT_FEATURE_ID_LNUM }, + { featureCode("mgrk"), STR_FONT_FEATURE_ID_MGRK }, + { featureCode("nalt"), STR_FONT_FEATURE_ID_NALT }, + { featureCode("nlck"), STR_FONT_FEATURE_ID_NLCK }, + { featureCode("numr"), STR_FONT_FEATURE_ID_NUMR }, + { featureCode("onum"), STR_FONT_FEATURE_ID_ONUM }, + { featureCode("opbd"), STR_FONT_FEATURE_ID_OPBD }, + { featureCode("ordn"), STR_FONT_FEATURE_ID_ORDN }, + { featureCode("ornm"), STR_FONT_FEATURE_ID_ORNM }, + { featureCode("palt"), STR_FONT_FEATURE_ID_PALT }, + { featureCode("pcap"), STR_FONT_FEATURE_ID_PCAP }, + { featureCode("pkna"), STR_FONT_FEATURE_ID_PKNA }, + { featureCode("pnum"), STR_FONT_FEATURE_ID_PNUM }, + { featureCode("pwid"), STR_FONT_FEATURE_ID_PWID }, + { featureCode("qwid"), STR_FONT_FEATURE_ID_QWID }, + { featureCode("rtbd"), STR_FONT_FEATURE_ID_RTBD }, + { featureCode("ruby"), STR_FONT_FEATURE_ID_RUBY }, + { featureCode("salt"), STR_FONT_FEATURE_ID_SALT }, + { featureCode("sinf"), STR_FONT_FEATURE_ID_SINF }, + { featureCode("smcp"), STR_FONT_FEATURE_ID_SMCP }, + { featureCode("smpl"), STR_FONT_FEATURE_ID_SMPL }, + { featureCode("subs"), STR_FONT_FEATURE_ID_SUBS }, + { featureCode("sups"), STR_FONT_FEATURE_ID_SUPS }, + { featureCode("swsh"), STR_FONT_FEATURE_ID_SWSH }, + { featureCode("titl"), STR_FONT_FEATURE_ID_TITL }, + { featureCode("tnam"), STR_FONT_FEATURE_ID_TNAM }, + { featureCode("tnum"), STR_FONT_FEATURE_ID_TNUM }, + { featureCode("trad"), STR_FONT_FEATURE_ID_TRAD }, + { featureCode("twid"), STR_FONT_FEATURE_ID_TWID }, + { featureCode("unic"), STR_FONT_FEATURE_ID_UNIC }, + { featureCode("valt"), STR_FONT_FEATURE_ID_VALT }, + { featureCode("vhal"), STR_FONT_FEATURE_ID_VHAL }, + { featureCode("vkna"), STR_FONT_FEATURE_ID_VKNA }, + { featureCode("vkrn"), STR_FONT_FEATURE_ID_VKRN }, + { featureCode("vpal"), STR_FONT_FEATURE_ID_VPAL }, + { featureCode("vrt2"), STR_FONT_FEATURE_ID_VRT2 }, + { featureCode("vrtr"), STR_FONT_FEATURE_ID_VRTR }, + { featureCode("zero"), STR_FONT_FEATURE_ID_ZERO }, + }); + + for (size_t i = 0; i < m_aFeatureDefinition.size(); ++i) + { + m_aCodeToIndex.emplace(m_aFeatureDefinition[i].getCode(), i); + } + + m_aRequiredFeatures.assign({ + featureCode("abvf"), featureCode("abvm"), featureCode("abvs"), featureCode("akhn"), + featureCode("blwf"), featureCode("blwm"), featureCode("blws"), featureCode("ccmp"), + featureCode("cfar"), featureCode("cjct"), featureCode("curs"), featureCode("dist"), + featureCode("dtls"), featureCode("fin2"), featureCode("fin3"), featureCode("fina"), + featureCode("flac"), featureCode("half"), featureCode("haln"), featureCode("init"), + featureCode("isol"), featureCode("ljmo"), featureCode("locl"), featureCode("ltra"), + featureCode("ltrm"), featureCode("mark"), featureCode("med2"), featureCode("medi"), + featureCode("mkmk"), featureCode("mset"), featureCode("nukt"), featureCode("pref"), + featureCode("pres"), featureCode("pstf"), featureCode("psts"), featureCode("rand"), + featureCode("rclt"), featureCode("rkrf"), featureCode("rlig"), featureCode("rphf"), + featureCode("rtla"), featureCode("rtlm"), featureCode("rvrn"), featureCode("size"), + featureCode("ssty"), featureCode("stch"), featureCode("tjmo"), featureCode("vatu"), + featureCode("vert"), featureCode("vjmo"), + }); +} + +namespace +{ +bool isCharacterVariantCode(sal_uInt32 nFeatureCode) +{ + return ((sal_uInt32(nFeatureCode) >> 24) & 0xFF) == 'c' + && ((sal_uInt32(nFeatureCode) >> 16) & 0xFF) == 'v'; +} + +bool isStylisticSetCode(sal_uInt32 nFeatureCode) +{ + return ((sal_uInt32(nFeatureCode) >> 24) & 0xFF) == 's' + && ((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(cChar1)) + && rtl::isAsciiDigit(static_cast(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..3abf7db3d --- /dev/null +++ b/vcl/source/font/PhysicalFontCollection.cxx @@ -0,0 +1,1279 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +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; +} + +namespace vcl::font +{ + +PhysicalFontCollection::PhysicalFontCollection() + : mbMatchData( false ) + , mpPreMatchHook( nullptr ) + , mpFallbackHook( nullptr ) + , mnFallbackCount( -1 ) +{} + +PhysicalFontCollection::~PhysicalFontCollection() +{ + Clear(); +} + +void PhysicalFontCollection::SetPreMatchHook(PreMatchFontSubstitution* pHook) +{ + mpPreMatchHook = pHook; +} + +void PhysicalFontCollection::SetFallbackHook(GlyphFallbackFontSubstitution* pHook) +{ + mpFallbackHook = pHook; +} + +void PhysicalFontCollection::Clear() +{ + // remove fallback lists + mpFallbackList.reset(); + mnFallbackCount = -1; + + // clear all entries in the device font list + maPhysicalFontFamilies.clear(); + + // match data must be recalculated too + mbMatchData = false; +} + +void PhysicalFontCollection::ImplInitGenericGlyphFallback() const +{ + // normalized family names of fonts suited for glyph fallback + // if a font is available related fonts can be ignored + // TODO: implement dynamic lists + static const char* aGlyphFallbackList[] = { + // empty strings separate the names of unrelated fonts + "eudc", "", + "arialunicodems", "cyberbit", "code2000", "", + "andalesansui", "", + "starsymbol", "opensymbol", "", + "msmincho", "fzmingti", "fzheiti", "ipamincho", "sazanamimincho", "kochimincho", "", + "sunbatang", "sundotum", "baekmukdotum", "gulim", "batang", "dotum", "", + "hgmincholightj", "msunglightsc", "msunglighttc", "hymyeongjolightk", "", + "tahoma", "dejavusans", "timesnewroman", "liberationsans", "", + "shree", "mangal", "", + "raavi", "shruti", "tunga", "", + "latha", "gautami", "kartika", "vrinda", "", + "shayyalmt", "naskmt", "scheherazade", "", + "david", "nachlieli", "lucidagrande", "", + "norasi", "angsanaupc", "", + "khmerossystem", "", + "muktinarrow", "", + "phetsarathot", "", + "padauk", "pinlonmyanmar", "", + "iskoolapota", "lklug", "", + nullptr + }; + + bool bHasEudc = false; + int nMaxLevel = 0; + int nBestQuality = 0; + std::unique_ptr> 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); + + (*pFallbackList)[ nMaxLevel ] = pFallbackFont; + if( !bHasEudc && !nMaxLevel ) + bHasEudc = !strncmp( *ppNames, "eudc", 5 ); + } + } + + mnFallbackCount = nMaxLevel; + mpFallbackList = std::move(pFallbackList); +} + +PhysicalFontFamily* PhysicalFontCollection::GetGlyphFallbackFont(FontSelectPattern& rFontSelData, + LogicalFontInstance* pFontInstance, + OUString& rMissingCodes, + int nFallbackLevel) const +{ + PhysicalFontFamily* pFallbackData = nullptr; + + // find a matching font candidate for platform specific glyph fallback + if( mpFallbackHook ) + { + // check cache for the first matching entry + // to avoid calling the expensive fallback hook (#i83491#) + sal_UCS4 cChar = 0; + bool bCached = true; + sal_Int32 nStrIndex = 0; + while( nStrIndex < rMissingCodes.getLength() ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &rFontSelData.maSearchName, + &rFontSelData.mbEmbolden, + &rFontSelData.maItalicMatrix); + + // ignore entries which don't have a fallback + if( !bCached || !rFontSelData.maSearchName.isEmpty() ) + break; + } + + if( bCached ) + { + // there is a matching fallback in the cache + // so update rMissingCodes with codepoints not yet resolved by this fallback + int nRemainingLength = 0; + std::unique_ptr const pRemainingCodes(new sal_UCS4[rMissingCodes.getLength()]); + OUString aFontName; + bool bEmbolden; + ItalicMatrix aMatrix; + + while( nStrIndex < rMissingCodes.getLength() ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &aFontName, &bEmbolden, &aMatrix); + if (!bCached || rFontSelData.maSearchName != aFontName || + rFontSelData.mbEmbolden != bEmbolden || + rFontSelData.maItalicMatrix != aMatrix) + { + pRemainingCodes[ nRemainingLength++ ] = cChar; + } + } + rMissingCodes = OUString( pRemainingCodes.get(), nRemainingLength ); + } + else + { + OUString aOldMissingCodes = rMissingCodes; + + // call the hook to query the best matching glyph fallback font + if (mpFallbackHook->FindFontSubstitute(rFontSelData, pFontInstance, rMissingCodes)) + // apply outdev3.cxx specific fontname normalization + rFontSelData.maSearchName = GetEnglishSearchFontName( rFontSelData.maSearchName ); + else + rFontSelData.maSearchName.clear(); + + // Cache the result even if there was no match + // See tdf#32665 and tdf#147283 for an example where FreeSerif that has glyphs that exist + // in the bold font, but not in the bold+italic version where fontconfig suggest the bold + // font + applying a matrix to fake the missing italic. + for(;;) + { + if (!pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &rFontSelData.maSearchName, + &rFontSelData.mbEmbolden, + &rFontSelData.maItalicMatrix)) + { + pFontInstance->AddFallbackForUnicode(cChar, rFontSelData.GetWeight(), + rFontSelData.maSearchName, + rFontSelData.mbEmbolden, + rFontSelData.maItalicMatrix); + } + if( nStrIndex >= aOldMissingCodes.getLength() ) + break; + cChar = aOldMissingCodes.iterateCodePoints( &nStrIndex ); + } + if( !rFontSelData.maSearchName.isEmpty() ) + { + // remove cache entries that were still not resolved + for( nStrIndex = 0; nStrIndex < rMissingCodes.getLength(); ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + pFontInstance->IgnoreFallbackForUnicode( cChar, rFontSelData.GetWeight(), rFontSelData.maSearchName ); + } + } + } + + // find the matching device font + if( !rFontSelData.maSearchName.isEmpty() ) + pFallbackData = FindFontFamily( rFontSelData.maSearchName ); + } + + // else find a matching font candidate for generic glyph fallback + if( !pFallbackData ) + { + // initialize font candidates for generic glyph fallback if needed + if( mnFallbackCount < 0 ) + ImplInitGenericGlyphFallback(); + + // TODO: adjust nFallbackLevel by number of levels resolved by the fallback hook + if( nFallbackLevel < mnFallbackCount ) + pFallbackData = (*mpFallbackList)[ nFallbackLevel ]; + } + + return pFallbackData; +} + +void PhysicalFontCollection::Add(PhysicalFontFace* pNewData) +{ + OUString aSearchName = GetEnglishSearchFontName( pNewData->GetFamilyName() ); + + PhysicalFontFamily* pFoundData = FindOrCreateFontFamily(aSearchName); + + pFoundData->AddFontFace( pNewData ); +} + +// find the font from the normalized font family name +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySearchName(const OUString& rSearchName) const +{ + // must be called with a normalized name. + assert( GetEnglishSearchFontName( rSearchName ) == rSearchName ); + + PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rSearchName ); + if( it == maPhysicalFontFamilies.end() ) + return nullptr; + + PhysicalFontFamily* pFoundData = (*it).second.get(); + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(std::u16string_view rFontName) const +{ + return ImplFindFontFamilyBySearchName( GetEnglishSearchFontName( rFontName ) ); +} + +PhysicalFontFamily *PhysicalFontCollection::FindOrCreateFontFamily(OUString const& rFamilyName) +{ + PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rFamilyName ); + PhysicalFontFamily* pFoundData = nullptr; + + if( it != maPhysicalFontFamilies.end() ) + pFoundData = (*it).second.get(); + + if( !pFoundData ) + { + pFoundData = new PhysicalFontFamily(rFamilyName); + maPhysicalFontFamilies[ rFamilyName ].reset(pFoundData); + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamilyByTokenNames(std::u16string_view rTokenStr) const +{ + PhysicalFontFamily* pFoundData = nullptr; + + // use normalized font name tokens to find the font + for( sal_Int32 nTokenPos = 0; nTokenPos != -1; ) + { + std::u16string_view aFamilyName = GetNextFontToken( rTokenStr, nTokenPos ); + if( aFamilyName.empty() ) + continue; + + pFoundData = FindFontFamily( aFamilyName ); + + if( pFoundData ) + break; + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySubstFontAttr(utl::FontNameAttr const& rFontAttr) const +{ + PhysicalFontFamily* pFoundData = nullptr; + + // use the font substitutions suggested by the FontNameAttr to find the font + for (auto const& substitution : rFontAttr.Substitutions) + { + pFoundData = FindFontFamily(substitution); + if( pFoundData ) + return pFoundData; + } + + // use known attributes from the configuration to find a matching substitute + const ImplFontAttrs nSearchType = rFontAttr.Type; + if( nSearchType != ImplFontAttrs::None ) + { + const FontWeight eSearchWeight = rFontAttr.Weight; + const FontWidth eSearchWidth = rFontAttr.Width; + const FontItalic eSearchSlant = ITALIC_DONTKNOW; + + pFoundData = FindFontFamilyByAttributes( nSearchType, + eSearchWeight, eSearchWidth, eSearchSlant, "" ); + + 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, + OUString const& rSearchFamilyName ) const +{ + if( (eSearchItalic != ITALIC_NONE) && (eSearchItalic != ITALIC_DONTKNOW) ) + nSearchType |= ImplFontAttrs::Italic; + + // don't bother to match attributes if the attributes aren't worth matching + if( nSearchType == ImplFontAttrs::None + && ((eSearchWeight == WEIGHT_DONTKNOW) || (eSearchWeight == WEIGHT_NORMAL)) + && ((eSearchWidth == WIDTH_DONTKNOW) || (eSearchWidth == WIDTH_NORMAL)) ) + return nullptr; + + ImplInitMatchData(); + PhysicalFontFamily* pFoundData = nullptr; + + tools::Long nBestMatch = 40000; + ImplFontAttrs nBestType = ImplFontAttrs::None; + + for (auto const& family : maPhysicalFontFamilies) + { + PhysicalFontFamily* pData = family.second.get(); + + // Get all information about the matching font + ImplFontAttrs nMatchType = pData->GetMatchType(); + FontWeight eMatchWeight= pData->GetMatchWeight(); + FontWidth eMatchWidth = pData->GetMatchWidth(); + + // Calculate Match Value + // 1000000000 + // 100000000 + // 10000000 CJK, CTL, None-Latin, Symbol + // 1000000 FamilyName, Script, Fixed, -Special, -Decorative, + // Titling, Capitals, Outline, Shadow + // 100000 Match FamilyName, Serif, SansSerif, Italic, + // Width, Weight + // 10000 Scalable, Standard, Default, + // full, Normal, Knownfont, + // Otherstyle, +Special, +Decorative, + // 1000 Typewriter, Rounded, Gothic, Schollbook + // 100 + tools::Long nTestMatch = 0; + + // test CJK script attributes + if ( nSearchType & ImplFontAttrs::CJK ) + { + // if the matching font doesn't support any CJK languages, then + // it is not appropriate + if ( !(nMatchType & ImplFontAttrs::CJK_AllLang) ) + { + nTestMatch -= 10000000; + } + else + { + // Matching language + if ( (nSearchType & ImplFontAttrs::CJK_AllLang) + && (nMatchType & ImplFontAttrs::CJK_AllLang) ) + nTestMatch += 10000000*3; + if ( nMatchType & ImplFontAttrs::CJK ) + nTestMatch += 10000000*2; + if ( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + } + else if ( nMatchType & ImplFontAttrs::CJK ) + { + nTestMatch -= 10000000; + } + + // test CTL script attributes + if( nSearchType & ImplFontAttrs::CTL ) + { + if( nMatchType & ImplFontAttrs::CTL ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + else if ( nMatchType & ImplFontAttrs::CTL ) + { + nTestMatch -= 10000000; + } + + // test LATIN script attributes + if( nSearchType & ImplFontAttrs::NoneLatin ) + { + if( nMatchType & ImplFontAttrs::NoneLatin ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + + // test SYMBOL attributes + if ( nSearchType & ImplFontAttrs::Symbol ) + { + const OUString& rSearchName = family.first; + // prefer some special known symbol fonts + if ( rSearchName == "starsymbol" ) + { + nTestMatch += 10000000*6+(10000*3); + } + else if ( rSearchName == "opensymbol" ) + { + nTestMatch += 10000000*6; + } + else if ( rSearchName == "starbats" || + rSearchName == "wingdings" || + rSearchName == "monotypesorts" || + rSearchName == "dingbats" || + rSearchName == "zapfdingbats" ) + { + nTestMatch += 10000000*5; + } + else if (pData->GetTypeFaces() & FontTypeFaces::Symbol) + { + nTestMatch += 10000000*4; + } + else + { + if( nMatchType & ImplFontAttrs::Symbol ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + } + else if ((pData->GetTypeFaces() & (FontTypeFaces::Symbol | FontTypeFaces::NoneSymbol)) == FontTypeFaces::Symbol) + { + nTestMatch -= 10000000; + } + else if ( nMatchType & ImplFontAttrs::Symbol ) + { + nTestMatch -= 10000; + } + + // match stripped family name + if( !rSearchFamilyName.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::Clone() const +{ + auto xClonedCollection = std::make_shared(); + 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 PhysicalFontCollection::GetFontFaceCollection() const +{ + std::unique_ptr pDeviceFontList(new PhysicalFontFaceCollection); + + for (auto const& family : maPhysicalFontFamilies) + { + const PhysicalFontFamily* pFontFamily = family.second.get(); + pFontFamily->UpdateDevFontList( *pDeviceFontList ); + } + + return pDeviceFontList; +} + +// These are the metric-compatible replacement fonts that are bundled with +// LibreOffice, we prefer them over generic substitutions that might be +// provided by the system. +const std::vector> aMetricCompatibleMap = +{ + { "Times New Roman", "Liberation Serif" }, + { "Arial", "Liberation Sans" }, + { "Arial Narrow", "Liberation Sans Narrow" }, + { "Courier New", "Liberation Mono" }, + { "Cambria", "Caladea" }, + { "Calibri", "Carlito" }, +}; + +static bool FindMetricCompatibleFont(FontSelectPattern& rFontSelData) +{ + for (const auto& aSub : aMetricCompatibleMap) + { + if (rFontSelData.maSearchName == GetEnglishSearchFontName(aSub.first)) + { + rFontSelData.maSearchName = aSub.second; + return true; + } + } + + return false; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(FontSelectPattern& rFSD) const +{ + // give up if no fonts are available + if( !Count() ) + return nullptr; + + static bool noFontLookup = getenv("SAL_NO_FONT_LOOKUP") != nullptr; + if (noFontLookup) + { + // Hard code the use of Liberation Sans and skip font search. + sal_Int32 nIndex = 0; + rFSD.maTargetName = GetNextFontToken(rFSD.GetFamilyName(), nIndex); + rFSD.maSearchName = "liberationsans"; + PhysicalFontFamily* pFont = ImplFindFontFamilyBySearchName(rFSD.maSearchName); + assert(pFont); + return pFont; + } + + bool bMultiToken = false; + sal_Int32 nTokenPos = 0; + OUString& aSearchName = rFSD.maSearchName; // TODO: get rid of reference + for(;;) + { + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = rFSD.maTargetName; + + // Until features are properly supported, they are appended to the + // font name, so we need to strip them off so the font is found. + sal_Int32 nFeat = aSearchName.indexOf(FontSelectPattern::FEAT_PREFIX); + OUString aOrigName = rFSD.maTargetName; + OUString aBaseFontName = aSearchName.copy( 0, (nFeat != -1) ? nFeat : aSearchName.getLength() ); + + if (nFeat != -1) + { + aSearchName = aBaseFontName; + rFSD.maTargetName = aBaseFontName; + } + + aSearchName = GetEnglishSearchFontName( aSearchName ); + ImplFontSubstitute(aSearchName); + // #114999# special emboldening for Ricoh fonts + // TODO: smarter check for special cases by using PreMatch infrastructure? + if( (rFSD.GetWeight() > WEIGHT_MEDIUM) && + aSearchName.startsWithIgnoreAsciiCase( "hg" ) ) + { + OUString aBoldName; + if( aSearchName.startsWithIgnoreAsciiCase( "hggothicb" ) ) + aBoldName = "hggothice"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgpgothicb" ) ) + aBoldName = "hgpgothice"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgminchol" ) ) + aBoldName = "hgminchob"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgpminchol" ) ) + aBoldName = "hgpminchob"; + else if( aSearchName.equalsIgnoreAsciiCase( "hgminchob" ) ) + aBoldName = "hgminchoe"; + else if( aSearchName.equalsIgnoreAsciiCase( "hgpminchob" ) ) + aBoldName = "hgpminchoe"; + + if( !aBoldName.isEmpty() && ImplFindFontFamilyBySearchName( aBoldName ) ) + { + // the other font is available => use it + aSearchName = aBoldName; + // prevent synthetic emboldening of bold version + rFSD.SetWeight(WEIGHT_DONTKNOW); + } + } + + // restore the features to make the font selection data unique + rFSD.maTargetName = aOrigName; + + // check if the current font name token or its substitute is valid + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + + // some systems provide special customization + // e.g. they suggest "serif" as UI-font, but this name cannot be used directly + // because the system wants to map it to another font first, e.g. "Helvetica" + + // use the target name to search in the prematch hook + rFSD.maTargetName = aBaseFontName; + + // Related: fdo#49271 RTF files often contain weird-ass + // Win 3.1/Win95 style fontnames which attempt to put the + // charset encoding into the filename + // http://www.webcenter.ru/~kazarn/eng/fonts_ttf.htm + OUString sStrippedName = StripScriptFromName(rFSD.maTargetName); + if (sStrippedName != rFSD.maTargetName) + { + rFSD.maTargetName = sStrippedName; + aSearchName = GetEnglishSearchFontName(rFSD.maTargetName); + pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + } + + if (FindMetricCompatibleFont(rFSD) || + (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD))) + { + aSearchName = GetEnglishSearchFontName(aSearchName); + } + + // the prematch hook uses the target name to search, but we now need + // to restore the features to make the font selection data unique + rFSD.maTargetName = aOrigName; + + pFoundData = ImplFindFontFamilyBySearchName( aSearchName ); + if( pFoundData ) + return pFoundData; + + // break after last font name token was checked unsuccessfully + if( nTokenPos == -1) + break; + bMultiToken = true; + } + + // if the first font was not available find the next available font in + // the semicolon separated list of font names. A font is also considered + // available when there is a matching entry in the Tools->Options->Fonts + // dialog with neither ALWAYS nor SCREENONLY flags set and the substitution + // font is available + for( nTokenPos = 0; nTokenPos != -1; ) + { + if( bMultiToken ) + { + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = GetEnglishSearchFontName( rFSD.maTargetName ); + } + else + nTokenPos = -1; + if (FindMetricCompatibleFont(rFSD) || + (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD))) + { + aSearchName = GetEnglishSearchFontName( aSearchName ); + } + ImplFontSubstitute(aSearchName); + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + } + + // if no font with a directly matching name is available use the + // first font name token and get its attributes to find a replacement + if ( bMultiToken ) + { + nTokenPos = 0; + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = GetEnglishSearchFontName( rFSD.maTargetName ); + } + + OUString aSearchShortName; + OUString aSearchFamilyName; + FontWeight eSearchWeight = rFSD.GetWeight(); + FontWidth eSearchWidth = rFSD.GetWidthType(); + ImplFontAttrs nSearchType = ImplFontAttrs::None; + utl::FontSubstConfiguration::getMapName( aSearchName, aSearchShortName, aSearchFamilyName, + eSearchWeight, eSearchWidth, nSearchType ); + + // note: the search name was already translated to english (if possible) + // use the font's shortened name if needed + if ( aSearchShortName != aSearchName ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchShortName); + if( pFoundData ) + { +#ifdef UNX + /* #96738# don't use mincho as a replacement for "MS Mincho" on X11: Mincho is + a korean bitmap font that is not suitable here. Use the font replacement table, + that automatically leads to the desired "HG Mincho Light J". Same story for + MS Gothic, there are thai and korean "Gothic" fonts, so we even prefer Andale */ + if ((aSearchName != "msmincho") && (aSearchName != "msgothic")) + // TODO: add heuristic to only throw out the fake ms* fonts +#endif + { + return pFoundData; + } + } + } + + // use font fallback + const utl::FontNameAttr* pFontAttr = nullptr; + if (!aSearchName.isEmpty() && !utl::ConfigManager::IsFuzzing()) + { + // get fallback info using FontSubstConfiguration and + // the target name, it's shortened name and family name in that order + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + pFontAttr = rFontSubst.getSubstInfo( aSearchName ); + if ( !pFontAttr && (aSearchShortName != aSearchName) ) + pFontAttr = rFontSubst.getSubstInfo( aSearchShortName ); + if ( !pFontAttr && (aSearchFamilyName != aSearchShortName) ) + pFontAttr = rFontSubst.getSubstInfo( aSearchFamilyName ); + + // try the font substitutions suggested by the fallback info + if( pFontAttr ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySubstFontAttr(*pFontAttr); + if( pFoundData ) + return pFoundData; + } + } + + // if a target symbol font is not available use a default symbol font + if( rFSD.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 cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/PhysicalFontFace.cxx b/vcl/source/font/PhysicalFontFace.cxx new file mode 100644 index 000000000..aef9054fd --- /dev/null +++ b/vcl/source/font/PhysicalFontFace.cxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * 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 + +#include +#include +#include + +#include + +#include +#include +#include + +#include + +namespace vcl::font +{ + +PhysicalFontFace::PhysicalFontFace( const FontAttributes& rDFA ) + : FontAttributes( rDFA ) +{ + // 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; +} + +static int FamilyNameMatchValue(FontSelectPattern const& rFSP, std::u16string_view sFontFamily) +{ + const OUString& rFontName = rFSP.maTargetName; + + if (rFontName.equalsIgnoreAsciiCase(sFontFamily)) + return 240000; + + return 0; +} + +static int StyleNameMatchValue(FontMatchStatus const& rStatus, std::u16string_view rStyle) +{ + if (rStatus.mpTargetStyleName && o3tl::equalsIgnoreAsciiCase(rStyle, *rStatus.mpTargetStyleName)) + return 120000; + + return 0; +} + +static int PitchMatchValue(FontSelectPattern const& rFSP, FontPitch ePitch) +{ + if ((rFSP.GetPitch() != PITCH_DONTKNOW) && (rFSP.GetPitch() == ePitch)) + return 20000; + + return 0; +} + +static int PreferNormalFontWidthMatchValue(FontWidth eWidthType) +{ + // TODO: change when the upper layers can tell their width preference + if (eWidthType == WIDTH_NORMAL) + return 400; + else if ((eWidthType == WIDTH_SEMI_EXPANDED) || (eWidthType == WIDTH_SEMI_CONDENSED)) + return 300; + + return 0; +} + +static int WeightMatchValue(FontSelectPattern const& rFSP, FontWeight eWeight) +{ + int nMatch = 0; + + if (rFSP.GetWeight() != WEIGHT_DONTKNOW) + { + // if not bold or requiring emboldening prefer light fonts to bold fonts + FontWeight ePatternWeight = rFSP.mbEmbolden ? WEIGHT_NORMAL : rFSP.GetWeight(); + + int nReqWeight = static_cast(ePatternWeight); + if (ePatternWeight > WEIGHT_MEDIUM) + nReqWeight += 100; + + int nGivenWeight = static_cast(eWeight); + if (eWeight > WEIGHT_MEDIUM) + nGivenWeight += 100; + + int nWeightDiff = nReqWeight - nGivenWeight; + + if (nWeightDiff == 0) + nMatch += 1000; + else if (nWeightDiff == +1 || nWeightDiff == -1) + nMatch += 700; + else if (nWeightDiff < +50 && nWeightDiff > -50) + nMatch += 200; + } + else + { + // prefer NORMAL font weight + // TODO: change when the upper layers can tell their weight preference + if (eWeight == WEIGHT_NORMAL) + nMatch += 450; + else if (eWeight == WEIGHT_MEDIUM) + nMatch += 350; + else if ((eWeight == WEIGHT_SEMILIGHT) || (eWeight == WEIGHT_SEMIBOLD)) + nMatch += 200; + else if (eWeight == WEIGHT_LIGHT) + nMatch += 150; + } + + return nMatch; +} + +static int ItalicMatchValue(FontSelectPattern const& rFSP, FontItalic eItalic) +{ + // if requiring custom matrix to fake italic, prefer upright font + FontItalic ePatternItalic + = rFSP.maItalicMatrix != ItalicMatrix() ? ITALIC_NONE : rFSP.GetItalic(); + + if (ePatternItalic == ITALIC_NONE) + { + if (eItalic == ITALIC_NONE) + return 900; + } + else + { + if (ePatternItalic == eItalic) + return 900; + else if (eItalic != ITALIC_NONE) + return 600; + } + + return 0; +} + +bool PhysicalFontFace::IsBetterMatch( const FontSelectPattern& rFSP, FontMatchStatus& rStatus ) const +{ + int nMatch = FamilyNameMatchValue(rFSP, GetFamilyName()); + nMatch += StyleNameMatchValue(rStatus, GetStyleName()); + nMatch += PitchMatchValue(rFSP, GetPitch()); + nMatch += PreferNormalFontWidthMatchValue(GetWidthType()); + nMatch += WeightMatchValue(rFSP, GetWeight()); + nMatch += ItalicMatchValue(rFSP, GetItalic()); + + if (rFSP.mnOrientation != 0_deg10) + nMatch += 80; + else if (rFSP.mnWidth != 0) + nMatch += 25; + else + nMatch += 5; + + if( rStatus.mnFaceMatch > nMatch ) + { + return false; + } + else if( rStatus.mnFaceMatch < nMatch ) + { + rStatus.mnFaceMatch = nMatch; + return true; + } + + return true; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/PhysicalFontFamily.cxx b/vcl/source/font/PhysicalFontFamily.cxx new file mode 100644 index 000000000..b402cd618 --- /dev/null +++ b/vcl/source/font/PhysicalFontFamily.cxx @@ -0,0 +1,269 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include +#include + +#include +#include + +namespace vcl::font +{ + +void PhysicalFontFamily::CalcType( ImplFontAttrs& rType, FontWeight& rWeight, FontWidth& rWidth, + FontFamily eFamily, const utl::FontNameAttr* pFontAttr ) +{ + if ( eFamily != FAMILY_DONTKNOW ) + { + if ( eFamily == FAMILY_SWISS ) + rType |= ImplFontAttrs::SansSerif; + else if ( eFamily == FAMILY_ROMAN ) + rType |= ImplFontAttrs::Serif; + else if ( eFamily == FAMILY_SCRIPT ) + rType |= ImplFontAttrs::Script; + else if ( eFamily == FAMILY_MODERN ) + rType |= ImplFontAttrs::Fixed; + else if ( eFamily == FAMILY_DECORATIVE ) + rType |= ImplFontAttrs::Decorative; + } + + if ( pFontAttr ) + { + rType |= pFontAttr->Type; + + if ( ((rWeight == WEIGHT_DONTKNOW) || (rWeight == WEIGHT_NORMAL)) && + (pFontAttr->Weight != WEIGHT_DONTKNOW) ) + rWeight = pFontAttr->Weight; + if ( ((rWidth == WIDTH_DONTKNOW) || (rWidth == WIDTH_NORMAL)) && + (pFontAttr->Width != WIDTH_DONTKNOW) ) + rWidth = pFontAttr->Width; + } +} + +static ImplFontAttrs lcl_IsCJKFont( 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->CompareIgnoreSize( *pFoundFontFace ); + if( eComp > 0 ) + continue; + if( eComp < 0 ) + break; + + // ignore duplicate if its quality is worse + if( pNewFontFace->GetQuality() < pFoundFontFace->GetQuality() ) + return; + + // keep the device font if its quality is good enough + if( pNewFontFace->GetQuality() == pFoundFontFace->GetQuality() ) + return; + + // replace existing font face with a better one + *it = pNewFontFace; // insert at sort position + return; + } + + maFontFaces.emplace(it, pNewFontFace); // insert at sort position +} + +// get font attributes using the normalized font family name +void PhysicalFontFamily::InitMatchData( const utl::FontSubstConfiguration& rFontSubst, + const OUString& rSearchName ) +{ + OUString aShortName; + OUString aMatchFamilyName(maMatchFamilyName); + // get font attributes from the decorated font name + utl::FontSubstConfiguration::getMapName( rSearchName, aShortName, aMatchFamilyName, + meMatchWeight, meMatchWidth, mnMatchType ); + maMatchFamilyName = aMatchFamilyName; + const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( rSearchName ); + // eventually use the stripped name + if( !pFontAttr ) + if( aShortName != rSearchName ) + pFontAttr = rFontSubst.getSubstInfo( aShortName ); + CalcType( mnMatchType, meMatchWeight, meMatchWidth, meFamily, pFontAttr ); + mnMatchType |= lcl_IsCJKFont( maFamilyName ); +} + +PhysicalFontFace* PhysicalFontFamily::FindBestFontFace( const vcl::font::FontSelectPattern& rFSD ) const +{ + if( maFontFaces.empty() ) + return nullptr; + if( maFontFaces.size() == 1) + return maFontFaces[0].get(); + + // FontName+StyleName should map to FamilyName+StyleName + const OUString& rSearchName = rFSD.maTargetName; + OUString aTargetStyleName; + const OUString* pTargetStyleName = nullptr; + if((rSearchName.getLength() > maSearchName.getLength()) + && rSearchName.startsWith( maSearchName ) ) + { + aTargetStyleName = rSearchName.copy(maSearchName.getLength() + 1); + pTargetStyleName = &aTargetStyleName; + } + + // TODO: linear search improve! + PhysicalFontFace* pBestFontFace = maFontFaces[0].get(); + FontMatchStatus aFontMatchStatus = {0, pTargetStyleName}; + for (auto const& font : maFontFaces) + { + PhysicalFontFace* pFoundFontFace = font.get(); + if( pFoundFontFace->IsBetterMatch( rFSD, aFontMatchStatus ) ) + pBestFontFace = pFoundFontFace; + } + + return pBestFontFace; +} + +// update device font list with unique font faces, with uniqueness +// meaning different font attributes, but not different fonts sizes +void PhysicalFontFamily::UpdateDevFontList( vcl::font::PhysicalFontFaceCollection& rDevFontList ) const +{ + PhysicalFontFace* pPrevFace = nullptr; + for (auto const& font : maFontFaces) + { + PhysicalFontFace* pFoundFontFace = font.get(); + if( !pPrevFace || pFoundFontFace->CompareIgnoreSize( *pPrevFace ) ) + rDevFontList.Add( pFoundFontFace ); + pPrevFace = pFoundFontFace; + } +} + +void PhysicalFontFamily::UpdateCloneFontList(vcl::font::PhysicalFontCollection& rFontCollection) const +{ + OUString aFamilyName = GetEnglishSearchFontName( GetFamilyName() ); + PhysicalFontFamily* pFamily(nullptr); + + for (auto const& font : maFontFaces) + { + PhysicalFontFace *pFoundFontFace = font.get(); + + if (!pFamily) + { // tdf#98989 lazy create as family without faces won't work + pFamily = rFontCollection.FindOrCreateFontFamily(aFamilyName); + } + assert(pFamily); + pFamily->AddFontFace( pFoundFontFace ); + } +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/font.cxx b/vcl/source/font/font.cxx new file mode 100644 index 000000000..2b7f22ad0 --- /dev/null +++ b/vcl/source/font/font.cxx @@ -0,0 +1,1155 @@ +/* -*- 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 +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include + +#ifdef _WIN32 +#include +#endif + +using namespace vcl; + +namespace +{ + Font::ImplType& GetGlobalDefault() + { + static Font::ImplType gDefault; + return gDefault; + } +} + +Font::Font() : mpImplFont(GetGlobalDefault()) +{ +} + +Font::Font( const vcl::Font& rFont ) : mpImplFont( rFont.mpImplFont ) +{ +} + +Font::Font( vcl::Font&& rFont ) noexcept : mpImplFont( std::move(rFont.mpImplFont) ) +{ +} + +Font::Font( const OUString& rFamilyName, const Size& rSize ) +{ + if (const_cast(mpImplFont)->maFamilyName != rFamilyName + || const_cast(mpImplFont)->maAverageFontSize != rSize) + { + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::Font( const OUString& rFamilyName, const OUString& rStyleName, const Size& rSize ) +{ + if (const_cast(mpImplFont)->maFamilyName != rFamilyName + || const_cast(mpImplFont)->maStyleName != rStyleName + || const_cast(mpImplFont)->maAverageFontSize != rSize) + { + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetStyleName( rStyleName ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::Font( FontFamily eFamily, const Size& rSize ) +{ + if (const_cast(mpImplFont)->meFamily != eFamily + || const_cast(mpImplFont)->maAverageFontSize != rSize) + { + mpImplFont->SetFamilyType( eFamily ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::~Font() +{ +} + +void Font::SetColor( const Color& rColor ) +{ + if (const_cast(mpImplFont)->maColor != rColor) + { + mpImplFont->maColor = rColor; + } +} + +void Font::SetFillColor( const Color& rColor ) +{ + if (const_cast(mpImplFont)->maFillColor != rColor) + { + mpImplFont->maFillColor = rColor; + if ( rColor.IsTransparent() ) + mpImplFont->mbTransparent = true; + } +} + +void Font::SetTransparent( bool bTransparent ) +{ + if (const_cast(mpImplFont)->mbTransparent != bTransparent) + mpImplFont->mbTransparent = bTransparent; +} + +void Font::SetAlignment( TextAlign eAlign ) +{ + if (const_cast(mpImplFont)->meAlign != eAlign) + mpImplFont->SetAlignment(eAlign); +} + +void Font::SetFamilyName( const OUString& rFamilyName ) +{ + if (const_cast(mpImplFont)->maFamilyName != rFamilyName) + mpImplFont->SetFamilyName( rFamilyName ); +} + +void Font::SetStyleName( const OUString& rStyleName ) +{ + if (const_cast(mpImplFont)->maStyleName != rStyleName) + mpImplFont->maStyleName = rStyleName; +} + +void Font::SetFontSize( const Size& rSize ) +{ + if (const_cast(mpImplFont)->GetFontSize() != rSize) + mpImplFont->SetFontSize( rSize ); +} + +void Font::SetFamily( FontFamily eFamily ) +{ + if (const_cast(mpImplFont)->GetFamilyTypeNoAsk() != eFamily) + mpImplFont->SetFamilyType( eFamily ); +} + +void Font::SetCharSet( rtl_TextEncoding eCharSet ) +{ + if (const_cast(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 ) +{ + if (const_cast(mpImplFont)->mbSymbolFlag != bSymbol) + { + mpImplFont->SetSymbolFlag( bSymbol ); + + if ( IsSymbolFont() ) + { + mpImplFont->SetCharSet( RTL_TEXTENCODING_SYMBOL ); + } + else + { + if ( std::as_const(mpImplFont)->GetCharSet() == RTL_TEXTENCODING_SYMBOL ) + mpImplFont->SetCharSet( RTL_TEXTENCODING_DONTKNOW ); + } + } +} + +void Font::SetLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (const_cast(mpImplFont)->maLanguageTag != rLanguageTag) + mpImplFont->maLanguageTag = rLanguageTag; +} + +void Font::SetCJKContextLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (const_cast(mpImplFont)->maCJKLanguageTag != rLanguageTag) + mpImplFont->maCJKLanguageTag = rLanguageTag; +} + +void Font::SetLanguage( LanguageType eLanguage ) +{ + if (const_cast(mpImplFont)->maLanguageTag.getLanguageType(false) != eLanguage) + mpImplFont->maLanguageTag.reset( eLanguage); +} + +void Font::SetCJKContextLanguage( LanguageType eLanguage ) +{ + if (const_cast(mpImplFont)->maCJKLanguageTag.getLanguageType(false) != eLanguage) + mpImplFont->maCJKLanguageTag.reset( eLanguage); +} + +void Font::SetPitch( FontPitch ePitch ) +{ + if (const_cast(mpImplFont)->GetPitchNoAsk() != ePitch) + mpImplFont->SetPitch( ePitch ); +} + +void Font::SetOrientation( Degree10 nOrientation ) +{ + if (const_cast(mpImplFont)->mnOrientation != nOrientation) + mpImplFont->mnOrientation = nOrientation; +} + +void Font::SetVertical( bool bVertical ) +{ + if (const_cast(mpImplFont)->mbVertical != bVertical) + mpImplFont->mbVertical = bVertical; +} + +void Font::SetKerning( FontKerning eKerning ) +{ + if (const_cast(mpImplFont)->meKerning != eKerning) + mpImplFont->meKerning = eKerning; +} + +bool Font::IsKerning() const +{ + return mpImplFont->meKerning != FontKerning::NONE; +} + +void Font::SetWeight( FontWeight eWeight ) +{ + if (const_cast(mpImplFont)->GetWeightNoAsk() != eWeight) + mpImplFont->SetWeight( eWeight ); +} + +void Font::SetWidthType( FontWidth eWidth ) +{ + if (const_cast(mpImplFont)->GetWidthTypeNoAsk() != eWidth) + mpImplFont->SetWidthType( eWidth ); +} + +void Font::SetItalic( FontItalic eItalic ) +{ + if (const_cast(mpImplFont)->GetItalicNoAsk() != eItalic) + mpImplFont->SetItalic( eItalic ); +} + +void Font::SetOutline( bool bOutline ) +{ + if (const_cast(mpImplFont)->mbOutline != bOutline) + mpImplFont->mbOutline = bOutline; +} + +void Font::SetShadow( bool bShadow ) +{ + if (const_cast(mpImplFont)->mbShadow != bShadow) + mpImplFont->mbShadow = bShadow; +} + +void Font::SetUnderline( FontLineStyle eUnderline ) +{ + if (const_cast(mpImplFont)->meUnderline != eUnderline) + mpImplFont->meUnderline = eUnderline; +} + +void Font::SetOverline( FontLineStyle eOverline ) +{ + if (const_cast(mpImplFont)->meOverline != eOverline) + mpImplFont->meOverline = eOverline; +} + +void Font::SetStrikeout( FontStrikeout eStrikeout ) +{ + if (const_cast(mpImplFont)->meStrikeout != eStrikeout) + mpImplFont->meStrikeout = eStrikeout; +} + +void Font::SetRelief( FontRelief eRelief ) +{ + if (const_cast(mpImplFont)->meRelief != eRelief) + mpImplFont->meRelief = eRelief; +} + +void Font::SetEmphasisMark( FontEmphasisMark eEmphasisMark ) +{ + if (const_cast(mpImplFont)->meEmphasisMark != eEmphasisMark ) + mpImplFont->meEmphasisMark = eEmphasisMark; +} + +void Font::SetWordLineMode( bool bWordLine ) +{ + if (const_cast(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; +} + +bool Font::EqualIgnoreColor( const vcl::Font& rFont ) const +{ + return mpImplFont->EqualIgnoreColor( *rFont.mpImplFont ); +} + +size_t Font::GetHashValue() const +{ + return mpImplFont->GetHashValue(); +} + +size_t Font::GetHashValueIgnoreColor() const +{ + return mpImplFont->GetHashValueIgnoreColor(); +} + +void Font::Merge( const vcl::Font& rFont ) +{ + if ( !rFont.GetFamilyName().isEmpty() ) + { + SetFamilyName( rFont.GetFamilyName() ); + SetStyleName( rFont.GetStyleName() ); + SetCharSet( GetCharSet() ); + SetLanguageTag( rFont.GetLanguageTag() ); + SetCJKContextLanguageTag( rFont.GetCJKContextLanguageTag() ); + // don't use access methods here, might lead to AskConfig(), if DONTKNOW + SetFamily( rFont.mpImplFont->GetFamilyTypeNoAsk() ); + SetPitch( rFont.mpImplFont->GetPitchNoAsk() ); + } + + // don't use access methods here, might lead to AskConfig(), if DONTKNOW + if ( rFont.mpImplFont->GetWeightNoAsk() != WEIGHT_DONTKNOW ) + SetWeight( rFont.GetWeight() ); + if ( rFont.mpImplFont->GetItalicNoAsk() != ITALIC_DONTKNOW ) + SetItalic( rFont.GetItalic() ); + if ( rFont.mpImplFont->GetWidthTypeNoAsk() != WIDTH_DONTKNOW ) + SetWidthType( rFont.GetWidthType() ); + + if ( rFont.GetFontSize().Height() ) + SetFontSize( rFont.GetFontSize() ); + if ( rFont.GetUnderline() != LINESTYLE_DONTKNOW ) + { + SetUnderline( rFont.GetUnderline() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + if ( rFont.GetOverline() != LINESTYLE_DONTKNOW ) + { + SetOverline( rFont.GetOverline() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + if ( rFont.GetStrikeout() != STRIKEOUT_DONTKNOW ) + { + SetStrikeout( rFont.GetStrikeout() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + + // Defaults? + SetOrientation( rFont.GetOrientation() ); + SetVertical( rFont.IsVertical() ); + SetEmphasisMark( rFont.GetEmphasisMark() ); + SetKerning( rFont.IsKerning() ? FontKerning::FontSpecific : FontKerning::NONE ); + SetOutline( rFont.IsOutline() ); + SetShadow( rFont.IsShadow() ); + SetRelief( rFont.GetRelief() ); +} + +void Font::GetFontAttributes( FontAttributes& rAttrs ) const +{ + rAttrs.SetFamilyName( mpImplFont->GetFamilyName() ); + rAttrs.SetStyleName( mpImplFont->maStyleName ); + rAttrs.SetFamilyType( mpImplFont->GetFamilyTypeNoAsk() ); + rAttrs.SetPitch( mpImplFont->GetPitchNoAsk() ); + rAttrs.SetItalic( mpImplFont->GetItalicNoAsk() ); + rAttrs.SetWeight( mpImplFont->GetWeightNoAsk() ); + rAttrs.SetWidthType( WIDTH_DONTKNOW ); + rAttrs.SetSymbolFlag( mpImplFont->GetCharSet() == RTL_TEXTENCODING_SYMBOL ); +} + +// tdf#127471 for corrections on EMF/WMF we need the AvgFontWidth in Windows-specific notation +tools::Long Font::GetOrCalculateAverageFontWidth() const +{ + if(0 == mpImplFont->GetCalculatedAverageFontWidth()) + { + // VirtualDevice is not thread safe + SolarMutexGuard aGuard; + + // create unscaled copy of font (this), a VirtualDevice and set it there + vcl::Font aUnscaledFont(*this); + ScopedVclPtr pTempVirtualDevice(VclPtr::Create()); + aUnscaledFont.SetAverageFontWidth(0); + pTempVirtualDevice->SetFont(aUnscaledFont); + +#ifdef _WIN32 + // on Windows systems use FontMetric to get/create AverageFontWidth from system + const FontMetric aMetric(pTempVirtualDevice->GetFontMetric()); + const_cast(this)->mpImplFont->SetCalculatedAverageFontWidth(aMetric.GetAverageFontWidth()); +#else + // On non-Windows systems we need to calculate AvgFontWidth + // as close as possible (discussion see documentation in task), + // so calculate it. For discussion of method used, see task + // buffer measure string creation, will always use the same + static constexpr OUStringLiteral aMeasureString + = u"\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027" + "\u0028\u0029\u002A\u002B\u002C\u002D\u002E\u002F" + "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037" + "\u0038\u0039\u003A\u003B\u003C\u003D\u003E\u003F" + "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047" + "\u0048\u0049\u004A\u004B\u004C\u004D\u004E\u004F" + "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057" + "\u0058\u0059\u005A\u005B\u005C\u005D\u005E\u005F" + "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067" + "\u0068\u0069\u006A\u006B\u006C\u006D\u006E\u006F" + "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077" + "\u0078\u0079\u007A\u007B\u007C\u007D\u007E"; + + const double fAverageFontWidth( + pTempVirtualDevice->GetTextWidth(aMeasureString) / + static_cast(aMeasureString.getLength())); + const_cast(this)->mpImplFont->SetCalculatedAverageFontWidth(basegfx::fround(fAverageFontWidth)); +#endif + } + + return mpImplFont->GetCalculatedAverageFontWidth(); +} + +SvStream& ReadImplFont( SvStream& rIStm, ImplFont& rImplFont, tools::Long& rnNormedFontScaling ) +{ + VersionCompatRead aCompat( rIStm ); + sal_uInt16 nTmp16(0); + sal_Int16 nTmps16(0); + bool bTmp(false); + sal_uInt8 nTmp8(0); + + rImplFont.SetFamilyName( rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet()) ); + rImplFont.maStyleName = rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet()); + TypeSerializer aSerializer(rIStm); + aSerializer.readSize(rImplFont.maAverageFontSize); + + static const bool bFuzzing = utl::ConfigManager::IsFuzzing(); + if (bFuzzing) + { + if (rImplFont.maAverageFontSize.Width() > 8192) + { + SAL_WARN("vcl.gdi", "suspicious average width of: " << rImplFont.maAverageFontSize.Width()); + rImplFont.maAverageFontSize.setWidth(8192); + } + } + + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetCharSet( static_cast(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetFamilyType( static_cast(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetPitch( static_cast(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetWeight( static_cast(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meUnderline = static_cast(nTmp16); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meStrikeout = static_cast(nTmp16); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetItalic( static_cast(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.maLanguageTag.reset( LanguageType(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meWidthType = static_cast(nTmp16); + + rIStm.ReadInt16( nTmps16 ); rImplFont.mnOrientation = Degree10(nTmps16); + + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbWordLine = bTmp; + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbOutline = bTmp; + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbShadow = bTmp; + rIStm.ReadUChar( nTmp8 ); rImplFont.meKerning = static_cast(nTmp8); + + if( aCompat.GetVersion() >= 2 ) + { + rIStm.ReadUChar( nTmp8 ); rImplFont.meRelief = static_cast(nTmp8); + rIStm.ReadUInt16( nTmp16 ); rImplFont.maCJKLanguageTag.reset( LanguageType(nTmp16) ); + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbVertical = bTmp; + rIStm.ReadUInt16( nTmp16 ); rImplFont.meEmphasisMark = static_cast(nTmp16); + } + + if( aCompat.GetVersion() >= 3 ) + { + rIStm.ReadUInt16( nTmp16 ); rImplFont.meOverline = static_cast(nTmp16); + } + + // tdf#127471 read NormedFontScaling + if( aCompat.GetVersion() >= 4 ) + { + sal_Int32 nNormedFontScaling(0); + rIStm.ReadInt32(nNormedFontScaling); + rnNormedFontScaling = nNormedFontScaling; + } + + // Relief + // CJKContextLanguage + + return rIStm; +} + +SvStream& WriteImplFont( SvStream& rOStm, const ImplFont& rImplFont, tools::Long nNormedFontScaling ) +{ + // tdf#127471 increase to version 4 + VersionCompatWrite aCompat( rOStm, 4 ); + + 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(rImplFont.maLanguageTag.getLanguageType( false)) ); + rOStm.WriteUInt16( rImplFont.GetWidthTypeNoAsk() ); + + rOStm.WriteInt16( rImplFont.mnOrientation.get() ); + + rOStm.WriteBool( rImplFont.mbWordLine ); + rOStm.WriteBool( rImplFont.mbOutline ); + rOStm.WriteBool( rImplFont.mbShadow ); + rOStm.WriteUChar( static_cast(rImplFont.meKerning) ); + + // new in version 2 + rOStm.WriteUChar( static_cast(rImplFont.meRelief) ); + rOStm.WriteUInt16( static_cast(rImplFont.maCJKLanguageTag.getLanguageType( false)) ); + rOStm.WriteBool( rImplFont.mbVertical ); + rOStm.WriteUInt16( static_cast(rImplFont.meEmphasisMark) ); + + // new in version 3 + rOStm.WriteUInt16( rImplFont.meOverline ); + + // new in version 4, NormedFontScaling + rOStm.WriteInt32(nNormedFontScaling); + + return rOStm; +} + +SvStream& ReadFont( SvStream& rIStm, vcl::Font& rFont ) +{ + // tdf#127471 try to read NormedFontScaling + tools::Long nNormedFontScaling(0); + SvStream& rRetval(ReadImplFont( rIStm, *rFont.mpImplFont, nNormedFontScaling )); + + if (nNormedFontScaling > 0) + { +#ifdef _WIN32 + // we run on windows and a NormedFontScaling was written + if(rFont.GetFontSize().getWidth() == nNormedFontScaling) + { + // the writing producer was running on a non-windows system, adapt to needed windows + // system-specific pre-multiply + const tools::Long nHeight(std::max(rFont.GetFontSize().getHeight(), 0)); + sal_uInt32 nScaledWidth(0); + + if(nHeight > 0) + { + vcl::Font aUnscaledFont(rFont); + aUnscaledFont.SetAverageFontWidth(0); + const FontMetric aUnscaledFontMetric(Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont)); + + if (nHeight > 0) + { + const double fScaleFactor(static_cast(nNormedFontScaling) / static_cast(nHeight)); + nScaledWidth = basegfx::fround(static_cast(aUnscaledFontMetric.GetAverageFontWidth()) * fScaleFactor); + } + } + + rFont.SetAverageFontWidth(nScaledWidth); + } + else + { + // the writing producer was on a windows system, correct pre-multiplied value + // is already set, nothing to do. Ignore 2nd value. Here a check + // could be done if adapting the 2nd, NormedFontScaling value would be similar to + // the set value for plausibility reasons + } +#else + // we do not run on windows and a NormedFontScaling was written + if(rFont.GetFontSize().getWidth() == nNormedFontScaling) + { + // the writing producer was not on a windows system, correct value + // already set, nothing to do + } + else + { + // the writing producer was on a windows system, correct FontScaling. + // The correct non-pre-multiplied value is the 2nd one, use it + rFont.SetAverageFontWidth(nNormedFontScaling); + } +#endif + } + + return rRetval; +} + +SvStream& WriteFont( SvStream& rOStm, const vcl::Font& rFont ) +{ + // tdf#127471 prepare NormedFontScaling for additional export + tools::Long nNormedFontScaling(rFont.GetFontSize().getWidth()); + + // FontScaling usage at vcl-Font is detected by checking that FontWidth != 0 + if (nNormedFontScaling > 0) + { + const tools::Long nHeight(std::max(rFont.GetFontSize().getHeight(), 0)); + + // check for negative height + if(0 == nHeight) + { + nNormedFontScaling = 0; + } + else + { +#ifdef _WIN32 + // for WIN32 the value is pre-multiplied with AverageFontWidth + // which makes it system-dependent. Turn that back to have the + // normed non-windows form of it for export as 2nd value + vcl::Font aUnscaledFont(rFont); + aUnscaledFont.SetAverageFontWidth(0); + const FontMetric aUnscaledFontMetric( + Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont)); + + if (aUnscaledFontMetric.GetAverageFontWidth() > 0) + { + const double fScaleFactor( + static_cast(nNormedFontScaling) + / static_cast(aUnscaledFontMetric.GetAverageFontWidth())); + nNormedFontScaling = static_cast(fScaleFactor * nHeight); + } +#endif + } + } + + return WriteImplFont( rOStm, *rFont.mpImplFont, nNormedFontScaling ); +} + +namespace +{ + bool identifyTrueTypeFont( const void* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult ) + { + bool bResult = false; + TrueTypeFont* pTTF = nullptr; + if( OpenTTFontBuffer( i_pBuffer, i_nSize, 0, &pTTF ) == SFErrCodes::Ok ) + { + TTGlobalFontInfo aInfo; + GetTTGlobalFontInfo( pTTF, &aInfo ); + // most importantly: the family name + if( aInfo.ufamily ) + o_rResult.SetFamilyName( OUString(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; + } + + struct WeightSearchEntry + { + const char* string; + int string_len; + FontWeight weight; + + bool operator<( const WeightSearchEntry& rRight ) const + { + return rtl_str_compareIgnoreAsciiCase_WithLength( string, string_len, rRight.string, rRight.string_len ) < 0; + } + } + const weight_table[] = + { + { "black", 5, WEIGHT_BLACK }, + { "bold", 4, WEIGHT_BOLD }, + { "book", 4, WEIGHT_LIGHT }, + { "demi", 4, WEIGHT_SEMIBOLD }, + { "heavy", 5, WEIGHT_BLACK }, + { "light", 5, WEIGHT_LIGHT }, + { "medium", 6, WEIGHT_MEDIUM }, + { "regular", 7, WEIGHT_NORMAL }, + { "super", 5, WEIGHT_ULTRABOLD }, + { "thin", 4, WEIGHT_THIN } + }; + + bool identifyType1Font( const char* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult ) + { + // might be a type1, find eexec + const char* pStream = i_pBuffer; + const char* const pExec = "eexec"; + const char* pExecPos = std::search( pStream, pStream+i_nSize, pExec, pExec+5 ); + if( pExecPos != pStream+i_nSize) + { + // find /FamilyName entry + static const char* const pFam = "/FamilyName"; + const char* pFamPos = std::search( pStream, pExecPos, pFam, pFam+11 ); + if( pFamPos != pExecPos ) + { + // extract the string value behind /FamilyName + const char* pOpen = pFamPos+11; + while( pOpen < pExecPos && *pOpen != '(' ) + pOpen++; + const char* pClose = pOpen; + while( pClose < pExecPos && *pClose != ')' ) + pClose++; + if( pClose - pOpen > 1 ) + { + o_rResult.SetFamilyName( OStringToOUString( std::string_view( pOpen+1, pClose-pOpen-1 ), RTL_TEXTENCODING_ASCII_US ) ); + } + } + + // parse /ItalicAngle + static const char* const pItalic = "/ItalicAngle"; + const char* pItalicPos = std::search( pStream, pExecPos, pItalic, pItalic+12 ); + if( pItalicPos != pExecPos ) + { + const char* pItalicEnd = pItalicPos + 12; + auto nItalic = rtl_str_toInt64_WithLength(pItalicEnd, 10, pExecPos - pItalicEnd); + o_rResult.SetItalic( (nItalic != 0) ? ITALIC_NORMAL : ITALIC_NONE ); + } + + // parse /Weight + static const char* const pWeight = "/Weight"; + const char* pWeightPos = std::search( pStream, pExecPos, pWeight, pWeight+7 ); + if( pWeightPos != pExecPos ) + { + // extract the string value behind /Weight + const char* pOpen = pWeightPos+7; + while( pOpen < pExecPos && *pOpen != '(' ) + pOpen++; + const char* pClose = pOpen; + while( pClose < pExecPos && *pClose != ')' ) + pClose++; + if( pClose - pOpen > 1 ) + { + WeightSearchEntry aEnt; + aEnt.string = pOpen+1; + aEnt.string_len = (pClose-pOpen)-1; + aEnt.weight = WEIGHT_NORMAL; + WeightSearchEntry const * pFound = std::lower_bound( std::begin(weight_table), std::end(weight_table), aEnt ); + if( pFound != std::end(weight_table) && + rtl_str_compareIgnoreAsciiCase_WithLength( pFound->string, pFound->string_len, aEnt.string, aEnt.string_len) == 0 ) + o_rResult.SetWeight( pFound->weight ); + } + } + + // parse isFixedPitch + static const char* const pFixed = "/isFixedPitch"; + const char* pFixedPos = std::search( pStream, pExecPos, pFixed, pFixed+13 ); + if( pFixedPos != pExecPos ) + { + // skip whitespace + while( pFixedPos < pExecPos-4 && + ( *pFixedPos == ' ' || + *pFixedPos == '\t' || + *pFixedPos == '\r' || + *pFixedPos == '\n' ) ) + { + pFixedPos++; + } + // find "true" value + if( rtl_str_compareIgnoreAsciiCase_WithLength( pFixedPos, 4, "true", 4 ) == 0 ) + o_rResult.SetPitch( PITCH_FIXED ); + else + o_rResult.SetPitch( PITCH_VARIABLE ); + } + } + return false; + } +} + +Font Font::identifyFont( const void* i_pBuffer, sal_uInt32 i_nSize ) +{ + Font aResult; + if( ! identifyTrueTypeFont( i_pBuffer, i_nSize, aResult ) ) + { + const char* pStream = static_cast(i_pBuffer); + if( pStream && i_nSize > 100 && + *pStream == '%' && pStream[1] == '!' ) + { + identifyType1Font( pStream, i_nSize, aResult ); + } + } + + return aResult; +} + +// The inlines from the font.hxx header are now instantiated for pImpl-ification +const Color& Font::GetColor() const { return mpImplFont->maColor; } +const Color& Font::GetFillColor() const { return mpImplFont->maFillColor; } +bool Font::IsTransparent() const { return mpImplFont->mbTransparent; } + +TextAlign Font::GetAlignment() const { return mpImplFont->GetAlignment(); } + +const OUString& Font::GetFamilyName() const { return mpImplFont->GetFamilyName(); } +const OUString& Font::GetStyleName() const { return mpImplFont->maStyleName; } + +const Size& Font::GetFontSize() const { return mpImplFont->GetFontSize(); } +void Font::SetFontHeight( tools::Long nHeight ) { SetFontSize( Size( std::as_const(mpImplFont)->GetFontSize().Width(), nHeight ) ); } +tools::Long Font::GetFontHeight() const { return mpImplFont->GetFontSize().Height(); } +void Font::SetAverageFontWidth( tools::Long nWidth ) { SetFontSize( Size( nWidth, std::as_const(mpImplFont)->GetFontSize().Height() ) ); } +tools::Long Font::GetAverageFontWidth() const { return mpImplFont->GetFontSize().Width(); } + +rtl_TextEncoding Font::GetCharSet() const { return mpImplFont->GetCharSet(); } + +const LanguageTag& Font::GetLanguageTag() const { return mpImplFont->maLanguageTag; } +const LanguageTag& Font::GetCJKContextLanguageTag() const { return mpImplFont->maCJKLanguageTag; } +LanguageType Font::GetLanguage() const { return mpImplFont->maLanguageTag.getLanguageType( false); } +LanguageType Font::GetCJKContextLanguage() const { return mpImplFont->maCJKLanguageTag.getLanguageType( false); } + +Degree10 Font::GetOrientation() const { return mpImplFont->mnOrientation; } +bool Font::IsVertical() const { return mpImplFont->mbVertical; } +FontKerning Font::GetKerning() const { return mpImplFont->meKerning; } + +FontPitch Font::GetPitch() { return mpImplFont->GetPitch(); } +FontWeight Font::GetWeight() { return mpImplFont->GetWeight(); } +FontWidth Font::GetWidthType() { return mpImplFont->GetWidthType(); } +FontItalic Font::GetItalic() { return mpImplFont->GetItalic(); } +FontFamily Font::GetFamilyType() { return mpImplFont->GetFamilyType(); } + +FontPitch Font::GetPitch() const { return mpImplFont->GetPitchNoAsk(); } +FontWeight Font::GetWeight() const { return mpImplFont->GetWeightNoAsk(); } +FontWidth Font::GetWidthType() const { return mpImplFont->GetWidthTypeNoAsk(); } +FontItalic Font::GetItalic() const { return mpImplFont->GetItalicNoAsk(); } +FontFamily Font::GetFamilyType() const { return mpImplFont->GetFamilyTypeNoAsk(); } + +int Font::GetQuality() const { return mpImplFont->GetQuality(); } +void Font::SetQuality( int nQuality ) { mpImplFont->SetQuality( nQuality ); } +void Font::IncreaseQualityBy( int nQualityAmount ) { mpImplFont->IncreaseQualityBy( nQualityAmount ); } +void Font::DecreaseQualityBy( int nQualityAmount ) { mpImplFont->DecreaseQualityBy( nQualityAmount ); } + +bool Font::IsOutline() const { return mpImplFont->mbOutline; } +bool Font::IsShadow() const { return mpImplFont->mbShadow; } +FontRelief Font::GetRelief() const { return mpImplFont->meRelief; } +FontLineStyle Font::GetUnderline() const { return mpImplFont->meUnderline; } +FontLineStyle Font::GetOverline() const { return mpImplFont->meOverline; } +FontStrikeout Font::GetStrikeout() const { return mpImplFont->meStrikeout; } +FontEmphasisMark Font::GetEmphasisMark() const { return mpImplFont->meEmphasisMark; } +bool Font::IsWordLineMode() const { return mpImplFont->mbWordLine; } +bool Font::IsSameInstance( const vcl::Font& rFont ) const { return (mpImplFont == rFont.mpImplFont); } + + +ImplFont::ImplFont() : + meWeight( WEIGHT_DONTKNOW ), + meFamily( FAMILY_DONTKNOW ), + mePitch( PITCH_DONTKNOW ), + meWidthType( WIDTH_DONTKNOW ), + meItalic( ITALIC_NONE ), + meAlign( ALIGN_TOP ), + meUnderline( LINESTYLE_NONE ), + meOverline( LINESTYLE_NONE ), + meStrikeout( STRIKEOUT_NONE ), + meRelief( FontRelief::NONE ), + meEmphasisMark( FontEmphasisMark::NONE ), + meKerning( FontKerning::FontSpecific ), + 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 ), + mnCalculatedAverageFontWidth( 0 ) +{} + +ImplFont::ImplFont( const ImplFont& rImplFont ) : + maFamilyName( rImplFont.maFamilyName ), + maStyleName( rImplFont.maStyleName ), + meWeight( rImplFont.meWeight ), + meFamily( rImplFont.meFamily ), + mePitch( rImplFont.mePitch ), + meWidthType( rImplFont.meWidthType ), + meItalic( rImplFont.meItalic ), + meAlign( rImplFont.meAlign ), + meUnderline( rImplFont.meUnderline ), + meOverline( rImplFont.meOverline ), + meStrikeout( rImplFont.meStrikeout ), + meRelief( rImplFont.meRelief ), + meEmphasisMark( rImplFont.meEmphasisMark ), + meKerning( rImplFont.meKerning ), + 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 ), + mnCalculatedAverageFontWidth( rImplFont.mnCalculatedAverageFontWidth ) +{} + +bool ImplFont::operator==( const ImplFont& rOther ) const +{ + if(!EqualIgnoreColor( rOther )) + return false; + + if( (maColor != rOther.maColor) + || (maFillColor != rOther.maFillColor) ) + return false; + + return true; +} + +bool ImplFont::EqualIgnoreColor( const ImplFont& rOther ) const +{ + // equality tests split up for easier debugging + if( (meWeight != rOther.meWeight) + || (meItalic != rOther.meItalic) + || (meFamily != rOther.meFamily) + || (mePitch != rOther.mePitch) ) + return false; + + if( (meCharSet != rOther.meCharSet) + || (maLanguageTag != rOther.maLanguageTag) + || (maCJKLanguageTag != rOther.maCJKLanguageTag) + || (meAlign != rOther.meAlign) ) + return false; + + if( (maAverageFontSize != rOther.maAverageFontSize) + || (mnOrientation != rOther.mnOrientation) + || (mbVertical != rOther.mbVertical) ) + return false; + + if( (maFamilyName != rOther.maFamilyName) + || (maStyleName != rOther.maStyleName) ) + return false; + + if( (meUnderline != rOther.meUnderline) + || (meOverline != rOther.meOverline) + || (meStrikeout != rOther.meStrikeout) + || (meRelief != rOther.meRelief) + || (meEmphasisMark != rOther.meEmphasisMark) + || (mbWordLine != rOther.mbWordLine) + || (mbOutline != rOther.mbOutline) + || (mbShadow != rOther.mbShadow) + || (meKerning != rOther.meKerning) + || (mbTransparent != rOther.mbTransparent) ) + return false; + + return true; +} + +size_t ImplFont::GetHashValue() const +{ + size_t hash = GetHashValueIgnoreColor(); + o3tl::hash_combine( hash, static_cast( maColor )); + o3tl::hash_combine( hash, static_cast( maFillColor )); + return hash; +} + +size_t ImplFont::GetHashValueIgnoreColor() const +{ + size_t hash = 0; + + o3tl::hash_combine( hash, meWeight ); + o3tl::hash_combine( hash, meItalic ); + o3tl::hash_combine( hash, meFamily ); + o3tl::hash_combine( hash, mePitch ); + + o3tl::hash_combine( hash, meCharSet ); + o3tl::hash_combine( hash, maLanguageTag.getLanguageType( false ).get()); + o3tl::hash_combine( hash, maCJKLanguageTag.getLanguageType( false ).get()); + o3tl::hash_combine( hash, meAlign ); + + o3tl::hash_combine( hash, maAverageFontSize.GetHashValue()); + o3tl::hash_combine( hash, mnOrientation.get()); + o3tl::hash_combine( hash, mbVertical ); + + o3tl::hash_combine( hash, maFamilyName ); + o3tl::hash_combine( hash, maStyleName ); + + o3tl::hash_combine( hash, meUnderline ); + o3tl::hash_combine( hash, meOverline ); + o3tl::hash_combine( hash, meStrikeout ); + o3tl::hash_combine( hash, meRelief ); + o3tl::hash_combine( hash, meEmphasisMark ); + o3tl::hash_combine( hash, mbWordLine ); + o3tl::hash_combine( hash, mbOutline ); + o3tl::hash_combine( hash, mbShadow ); + o3tl::hash_combine( hash, meKerning ); + o3tl::hash_combine( hash, mbTransparent ); + + return hash; +} + +void ImplFont::AskConfig() +{ + if( mbConfigLookup ) + return; + + mbConfigLookup = true; + + // prepare the FontSubst configuration lookup + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + + OUString aShortName; + OUString aFamilyName; + ImplFontAttrs nType = ImplFontAttrs::None; + FontWeight eWeight = WEIGHT_DONTKNOW; + FontWidth eWidthType = WIDTH_DONTKNOW; + OUString aMapName = GetEnglishSearchFontName( maFamilyName ); + + utl::FontSubstConfiguration::getMapName( aMapName, + aShortName, aFamilyName, eWeight, eWidthType, nType ); + + // lookup the font name in the configuration + const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( aMapName ); + + // if the direct lookup failed try again with an alias name + if ( !pFontAttr && (aShortName != aMapName) ) + pFontAttr = rFontSubst.getSubstInfo( aShortName ); + + if( pFontAttr ) + { + // the font was found in the configuration + if( meFamily == FAMILY_DONTKNOW ) + { + if ( pFontAttr->Type & ImplFontAttrs::Serif ) + meFamily = FAMILY_ROMAN; + else if ( pFontAttr->Type & ImplFontAttrs::SansSerif ) + meFamily = FAMILY_SWISS; + else if ( pFontAttr->Type & ImplFontAttrs::Typewriter ) + meFamily = FAMILY_MODERN; + else if ( pFontAttr->Type & ImplFontAttrs::Italic ) + meFamily = FAMILY_SCRIPT; + else if ( pFontAttr->Type & ImplFontAttrs::Decorative ) + meFamily = FAMILY_DECORATIVE; + } + + if( mePitch == PITCH_DONTKNOW ) + { + if ( pFontAttr->Type & ImplFontAttrs::Fixed ) + mePitch = PITCH_FIXED; + } + } + + // if some attributes are still unknown then use the FontSubst magic + if( meFamily == FAMILY_DONTKNOW ) + { + if( nType & ImplFontAttrs::Serif ) + meFamily = FAMILY_ROMAN; + else if( nType & ImplFontAttrs::SansSerif ) + meFamily = FAMILY_SWISS; + else if( nType & ImplFontAttrs::Typewriter ) + meFamily = FAMILY_MODERN; + else if( nType & ImplFontAttrs::Italic ) + meFamily = FAMILY_SCRIPT; + else if( nType & ImplFontAttrs::Decorative ) + meFamily = FAMILY_DECORATIVE; + } + + if( GetWeight() == WEIGHT_DONTKNOW ) + SetWeight( eWeight ); + if( meWidthType == WIDTH_DONTKNOW ) + meWidthType = eWidthType; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontattributes.cxx b/vcl/source/font/fontattributes.cxx new file mode 100644 index 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::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..9a87d02bc --- /dev/null +++ b/vcl/source/font/fontcache.cxx @@ -0,0 +1,279 @@ +/* -*- 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 + +#include + +#include +#include +#include +#include +#include + +using namespace vcl::font; + +size_t ImplFontCache::IFSD_Hash::operator()( const vcl::font::FontSelectPattern& rFSD ) const +{ + return rFSD.hashCode(); +} + +bool ImplFontCache::IFSD_Equal::operator()(const vcl::font::FontSelectPattern& rA, const vcl::font::FontSelectPattern& rB) const +{ + // check normalized font family name + if( rA.maSearchName != rB.maSearchName ) + return false; + + // check font transformation + if( (rA.mnHeight != rB.mnHeight) + || (rA.mnWidth != rB.mnWidth) + || (rA.mnOrientation != rB.mnOrientation) ) + return false; + + // check mapping relevant attributes + if( (rA.mbVertical != rB.mbVertical) + || (rA.meLanguage != rB.meLanguage) ) + return false; + + // check font face attributes + if( (rA.GetWeight() != rB.GetWeight()) + || (rA.GetItalic() != rB.GetItalic()) +// || (rA.meFamily != rB.meFamily) // TODO: remove this mostly obsolete member + || (rA.GetPitch() != rB.GetPitch()) ) + return false; + + // check style name + if( rA.GetStyleName() != rB.GetStyleName() ) + return false; + + // Symbol fonts may recode from one type to another So they are only + // safely equivalent for equal targets + if (rA.IsSymbolFont() || rB.IsSymbolFont()) + { + if (rA.maTargetName != rB.maTargetName) + return false; + } + + // check for features + if ((rA.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX) + != -1 || + rB.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX) + != -1) && rA.maTargetName != rB.maTargetName) + return false; + + if (rA.mbEmbolden != rB.mbEmbolden) + return false; + + if (rA.maItalicMatrix != rB.maItalicMatrix) + return false; + + return true; +} + +ImplFontCache::ImplFontCache() + : mpLastHitCacheEntry( nullptr ) + , maFontInstanceList(std::numeric_limits::max()) // "unlimited", i.e. no cleanup + // The cache limit is set by the rough number of characters needed to read your average Asian newspaper. + , m_aBoundRectCache(3000) +{} + +ImplFontCache::~ImplFontCache() +{ + for (const auto & rLFI : maFontInstanceList) + { + rLFI.second->mpFontCache = nullptr; + } +} + +rtl::Reference ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList, + const vcl::Font& rFont, const Size& rSize, float fExactHeight, bool bNonAntialias ) +{ + // initialize internal font request object + vcl::font::FontSelectPattern aFontSelData(rFont, rFont.GetFamilyName(), rSize, fExactHeight, bNonAntialias); + return GetFontInstance( pFontList, aFontSelData ); +} + +rtl::Reference ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList, + vcl::font::FontSelectPattern& aFontSelData ) +{ + rtl::Reference pFontInstance; + PhysicalFontFamily* pFontFamily = nullptr; + + // check if a directly matching logical font instance is already cached, + // the most recently used font usually has a hit rate of >50% + if (mpLastHitCacheEntry && IFSD_Equal()(aFontSelData, mpLastHitCacheEntry->GetFontSelectPattern())) + pFontInstance = mpLastHitCacheEntry; + else + { + FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData ); + if( it != maFontInstanceList.end() ) + pFontInstance = (*it).second; + } + + if( !pFontInstance ) // no direct cache hit + { + // find the best matching logical font family and update font selector accordingly + pFontFamily = pFontList->FindFontFamily( aFontSelData ); + SAL_WARN_IF( (pFontFamily == nullptr), "vcl", "ImplFontCache::Get() No logical font found!" ); + if( pFontFamily ) + { + aFontSelData.maSearchName = pFontFamily->GetSearchName(); + + // check if an indirectly matching logical font instance is already cached + FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData ); + if( it != maFontInstanceList.end() ) + pFontInstance = (*it).second; + } + } + + if( !pFontInstance && pFontFamily) // still no cache hit => create a new font instance + { + vcl::font::PhysicalFontFace* pFontData = pFontFamily->FindBestFontFace(aFontSelData); + + // create a new logical font instance from this physical font face + pFontInstance = pFontData->CreateFontInstance( aFontSelData ); + pFontInstance->mpFontCache = this; + + // if we're substituting from or to a symbol font we may need a symbol + // conversion table + if( pFontData->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( u"Symbol", u"AppleSymbol" ); + } +#endif + + static const size_t FONTCACHE_MAX = getenv("LO_TESTNAME") ? 1 : 50; + + if (maFontInstanceList.size() >= FONTCACHE_MAX) + { + struct limit_exception : public std::exception {}; + try + { + maFontInstanceList.remove_if([this] (FontInstanceList::key_value_pair_t const& rFontPair) + { + if (maFontInstanceList.size() < FONTCACHE_MAX) + throw limit_exception(); + LogicalFontInstance* pFontEntry = rFontPair.second.get(); + if (pFontEntry->m_nCount > 1) + return false; + m_aBoundRectCache.remove_if([&pFontEntry] (GlyphBoundRectCache::key_value_pair_t const& rGlyphPair) + { return rGlyphPair.first.m_pFont == pFontEntry; }); + if (mpLastHitCacheEntry == pFontEntry) + mpLastHitCacheEntry = nullptr; + return true; + }); + } + catch (limit_exception&) {} + } + + assert(pFontInstance); + // add the new entry to the cache + maFontInstanceList.insert({aFontSelData, pFontInstance.get()}); + } + + mpLastHitCacheEntry = pFontInstance.get(); + return pFontInstance; +} + +rtl::Reference ImplFontCache::GetGlyphFallbackFont( PhysicalFontCollection const * pFontCollection, + vcl::font::FontSelectPattern& rFontSelData, LogicalFontInstance* pFontInstance, int nFallbackLevel, OUString& rMissingCodes ) +{ + // get a candidate font for glyph fallback + // unless the previously selected font got a device specific substitution + // e.g. PsPrint Arial->Helvetica for udiaeresis when Helvetica doesn't support it + if( nFallbackLevel >= 1) + { + PhysicalFontFamily* pFallbackData = nullptr; + + //fdo#33898 If someone has EUDC installed then they really want that to + //be used as the first-choice glyph fallback seeing as it's filled with + //private area codes with don't make any sense in any other font so + //prioritize it here if it's available. Ideally we would remove from + //rMissingCodes all the glyphs which it is able to resolve as an + //optimization, but that's tricky to achieve cross-platform without + //sufficient heavy-weight code that's likely to undo the value of the + //optimization + if (nFallbackLevel == 1) + pFallbackData = pFontCollection->FindFontFamily(u"EUDC"); + if (!pFallbackData) + pFallbackData = pFontCollection->GetGlyphFallbackFont(rFontSelData, pFontInstance, rMissingCodes, nFallbackLevel-1); + // escape when there are no font candidates + if( !pFallbackData ) + return nullptr; + // override the font name + rFontSelData.SetFamilyName( pFallbackData->GetFamilyName() ); + // clear the cached normalized name + rFontSelData.maSearchName.clear(); + } + + rtl::Reference 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..7ca3e56a2 --- /dev/null +++ b/vcl/source/font/fontcharmap.cxx @@ -0,0 +1,639 @@ +/* + * 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 +#include +#include +#include +#include + +#include +#include +#include + +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; +const sal_UCS4 aDefaultUnicodeRanges[] = {0x0020,0xD800, 0xE000,0xFFF0}; +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 ) + , m_bSymbolic(rCR.mbSymbolic) +{ + 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 = std::size(aDefaultUnicodeRanges); + if( bSymbols ) + { + pRangeCodes = aDefaultSymbolRanges; + nCodesCount = std::size(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((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) || (nSubTables > (nLength - 24) / 8) ) + 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 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(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(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 + o3tl::sorted_vector aSupportedCodePoints; + aSupportedCodePoints.reserve(256); + + static const int NINSIZE = 64; + static const int NOUTSIZE = 64; + std::vector 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(cMin >> 8)); + if( (cMin >= 0x0100) || (cMin < 0x00A0) ) + cCharsInp.push_back(static_cast(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 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(); +} + +bool FontCharMap::isSymbolic() const { return mpImplFontCharMap->m_bSymbolic; } + +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..0907d657a --- /dev/null +++ b/vcl/source/font/fontinstance.cxx @@ -0,0 +1,192 @@ +/* -*- 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 + +#include +#include + +#include +#include +#include + +LogicalFontInstance::LogicalFontInstance(const vcl::font::PhysicalFontFace& rFontFace, const vcl::font::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(rFontFace)) +{ +} + +LogicalFontInstance::~LogicalFontInstance() +{ + maUnicodeFallbackList.clear(); + 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() const +{ + hb_font_t* pHbFont = const_cast(this)->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) const +{ + hb_face_t* pHbFace = hb_font_get_face(const_cast(this)->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, + bool bEmbolden, const ItalicMatrix& rMatrix) +{ + MapEntry& rEntry = maUnicodeFallbackList[ std::pair< sal_UCS4, FontWeight >(cChar,eWeight) ]; + rEntry.sFontName = rFontName; + rEntry.bEmbolden = bEmbolden; + rEntry.aItalicMatrix = rMatrix; +} + +bool LogicalFontInstance::GetFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight, + OUString* pFontName, bool* pEmbolden, ItalicMatrix* pMatrix) const +{ + UnicodeFallbackList::const_iterator it = maUnicodeFallbackList.find( std::pair< sal_UCS4, FontWeight >(cChar,eWeight) ); + if( it == maUnicodeFallbackList.end() ) + return false; + + const MapEntry& rEntry = (*it).second; + *pFontName = rEntry.sFontName; + *pEmbolden = rEntry.bEmbolden; + *pMatrix = rEntry.aItalicMatrix; + return true; +} + +void LogicalFontInstance::IgnoreFallbackForUnicode( sal_UCS4 cChar, FontWeight eWeight, std::u16string_view rFontName ) +{ + UnicodeFallbackList::iterator it = maUnicodeFallbackList.find( std::pair< sal_UCS4,FontWeight >(cChar,eWeight) ); + if( it == maUnicodeFallbackList.end() ) + return; + const MapEntry& rEntry = (*it).second; + if (rEntry.sFontName == rFontName) + maUnicodeFallbackList.erase( it ); +} + +bool LogicalFontInstance::GetGlyphBoundRect(sal_GlyphId nID, tools::Rectangle &rRect, bool bVertical) const +{ + if (mpFontCache && mpFontCache->GetCachedGlyphBoundRect(this, nID, rRect)) + return true; + + 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; +} + +bool LogicalFontInstance::NeedOffsetCorrection(sal_Int32 nYOffset) +{ + if (!m_xeFontFamilyEnum) + { + char familyname[10]; + unsigned int familyname_size = 10; + + m_xeFontFamilyEnum = FontFamilyEnum::Unclassified; + + if (hb_ot_name_get_utf8 (hb_font_get_face(GetHbFont()), + HB_OT_NAME_ID_FONT_FAMILY , HB_LANGUAGE_INVALID, &familyname_size, familyname) == 8) + { + // DFKai-SB (ukai.ttf) is a built-in font under traditional Chinese + // Windows. It has wrong extent values in glyf table. The problem results + // in wrong positioning of glyphs in vertical writing. + // Check https://github.com/harfbuzz/harfbuzz/issues/3521 for reference. + if (!strncmp("DFKai-SB", familyname, 8)) + m_xeFontFamilyEnum = FontFamilyEnum::DFKaiSB; + } + } + + bool bRet = true; + + switch (*m_xeFontFamilyEnum) + { + case FontFamilyEnum::DFKaiSB: + // -839: optimization for one third of ukai.ttf + if (nYOffset == -839) + bRet = false; + break; + default: + bRet = false; + } + + return bRet; +} + +/* 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..428af2e46 --- /dev/null +++ b/vcl/source/font/fontmetric.cxx @@ -0,0 +1,468 @@ +/* -*- 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 + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::rtl; +using namespace ::utl; + +FontMetric::FontMetric() +: mnAscent( 0 ), + mnDescent( 0 ), + mnIntLeading( 0 ), + mnExtLeading( 0 ), + mnLineHeight( 0 ), + mnSlant( 0 ), + mnBulletOffset( 0 ), + mnHangingBaseline( 0 ), + mbFullstopCentered( false ) +{} + +FontMetric::FontMetric( const FontMetric& rFontMetric ) = default; + +FontMetric::FontMetric(vcl::font::PhysicalFontFace const& rFace) + : FontMetric() +{ + SetFamilyName(rFace.GetFamilyName()); + SetStyleName(rFace.GetStyleName()); + SetCharSet(rFace.GetCharSet()); + SetFamily(rFace.GetFamilyType()); + SetPitch(rFace.GetPitch()); + SetWeight(rFace.GetWeight()); + SetItalic(rFace.GetItalic()); + SetAlignment(TextAlign::ALIGN_TOP); + SetWidthType(rFace.GetWidthType()); + SetQuality(rFace.GetQuality() ); +} + +FontMetric::~FontMetric() +{ +} + +FontMetric& FontMetric::operator=(const FontMetric& rFontMetric) = default; + +FontMetric& FontMetric::operator=(FontMetric&& rFontMetric) = default; + +bool FontMetric::EqualNoBase( const FontMetric& r ) const +{ + if (mbFullstopCentered != r.mbFullstopCentered) + return false; + if( mnAscent != r.mnAscent ) + return false; + if( mnDescent != r.mnDescent ) + return false; + if( mnIntLeading != r.mnIntLeading ) + return false; + if( mnExtLeading != r.mnExtLeading ) + return false; + if( mnSlant != r.mnSlant ) + return false; + + return true; +} + +bool FontMetric::operator==( const FontMetric& r ) const +{ + if( Font::operator!=(r) ) + return false; + return EqualNoBase(r); +} + +bool FontMetric::EqualIgnoreColor( const FontMetric& r ) const +{ + if( !Font::EqualIgnoreColor(r) ) + return false; + return EqualNoBase(r); +} + +size_t FontMetric::GetHashValueNoBase() const +{ + size_t hash = 0; + o3tl::hash_combine( hash, mbFullstopCentered ); + o3tl::hash_combine( hash, mnAscent ); + o3tl::hash_combine( hash, mnDescent ); + o3tl::hash_combine( hash, mnIntLeading ); + o3tl::hash_combine( hash, mnExtLeading ); + o3tl::hash_combine( hash, mnSlant ); + return hash; +} + +size_t FontMetric::GetHashValueIgnoreColor() const +{ + size_t hash = GetHashValueNoBase(); + o3tl::hash_combine( hash, Font::GetHashValueIgnoreColor()); + return hash; +} + +ImplFontMetricData::ImplFontMetricData( const vcl::font::FontSelectPattern& rFontSelData ) + : FontAttributes( rFontSelData ) + , mnHeight ( rFontSelData.mnHeight ) + , mnWidth ( rFontSelData.mnWidth ) + , mnOrientation( static_cast(rFontSelData.mnOrientation) ) + , mnAscent( 0 ) + , mnDescent( 0 ) + , mnIntLeading( 0 ) + , mnExtLeading( 0 ) + , mnSlant( 0 ) + , mnMinKashida( 0 ) + , mnHangingBaseline( 0 ) + , mbFullstopCentered( false ) + , mnBulletOffset( 0 ) + , mnUnderlineSize( 0 ) + , mnUnderlineOffset( 0 ) + , mnBUnderlineSize( 0 ) + , mnBUnderlineOffset( 0 ) + , mnDUnderlineSize( 0 ) + , mnDUnderlineOffset1( 0 ) + , mnDUnderlineOffset2( 0 ) + , mnWUnderlineSize( 0 ) + , mnWUnderlineOffset( 0 ) + , mnAboveUnderlineSize( 0 ) + , mnAboveUnderlineOffset( 0 ) + , mnAboveBUnderlineSize( 0 ) + , mnAboveBUnderlineOffset( 0 ) + , mnAboveDUnderlineSize( 0 ) + , mnAboveDUnderlineOffset1( 0 ) + , mnAboveDUnderlineOffset2( 0 ) + , mnAboveWUnderlineSize( 0 ) + , mnAboveWUnderlineOffset( 0 ) + , mnStrikeoutSize( 0 ) + , mnStrikeoutOffset( 0 ) + , mnBStrikeoutSize( 0 ) + , mnBStrikeoutOffset( 0 ) + , mnDStrikeoutSize( 0 ) + , mnDStrikeoutOffset1( 0 ) + , mnDStrikeoutOffset2( 0 ) +{ + // initialize the used font name + sal_Int32 nTokenPos = 0; + SetFamilyName( OUString(GetNextFontToken( rFontSelData.GetFamilyName(), nTokenPos )) ); + SetStyleName( rFontSelData.GetStyleName() ); +} + +void ImplFontMetricData::ImplInitTextLineSize( const OutputDevice* pDev ) +{ + tools::Long nDescent = mnDescent; + if ( nDescent <= 0 ) + { + nDescent = mnAscent / 10; + if ( !nDescent ) + nDescent = 1; + } + + // #i55341# for some fonts it is not a good idea to calculate + // their text line metrics from the real font descent + // => work around this problem just for these fonts + if( 3*nDescent > mnAscent ) + nDescent = mnAscent / 3; + + tools::Long nLineHeight = ((nDescent*25)+50) / 100; + if ( !nLineHeight ) + nLineHeight = 1; + tools::Long nLineHeight2 = nLineHeight / 2; + if ( !nLineHeight2 ) + nLineHeight2 = 1; + + tools::Long nBLineHeight = ((nDescent*50)+50) / 100; + if ( nBLineHeight == nLineHeight ) + nBLineHeight++; + tools::Long nBLineHeight2 = nBLineHeight/2; + if ( !nBLineHeight2 ) + nBLineHeight2 = 1; + + tools::Long n2LineHeight = ((nDescent*16)+50) / 100; + if ( !n2LineHeight ) + n2LineHeight = 1; + tools::Long n2LineDY = n2LineHeight; + /* #117909# + * add some pixels to minimum double line distance on higher resolution devices + */ + tools::Long nMin2LineDY = 1 + pDev->GetDPIY()/150; + if ( n2LineDY < nMin2LineDY ) + n2LineDY = nMin2LineDY; + tools::Long n2LineDY2 = n2LineDY/2; + if ( !n2LineDY2 ) + n2LineDY2 = 1; + + const vcl::Font& rFont ( pDev->GetFont() ); + bool bCJKVertical = MsLangId::isCJK(rFont.GetLanguage()) && rFont.IsVertical(); + tools::Long nUnderlineOffset = bCJKVertical ? mnDescent : (mnDescent/2 + 1); + tools::Long nStrikeoutOffset = rFont.IsVertical() ? -((mnAscent - mnDescent) / 2) : -((mnAscent - mnIntLeading) / 3); + + mnUnderlineSize = nLineHeight; + mnUnderlineOffset = nUnderlineOffset - nLineHeight2; + + mnBUnderlineSize = nBLineHeight; + mnBUnderlineOffset = nUnderlineOffset - nBLineHeight2; + + mnDUnderlineSize = n2LineHeight; + mnDUnderlineOffset1 = nUnderlineOffset - n2LineDY2 - n2LineHeight; + mnDUnderlineOffset2 = mnDUnderlineOffset1 + n2LineDY + n2LineHeight; + + tools::Long nWCalcSize = mnDescent; + if ( nWCalcSize < 6 ) + { + if ( (nWCalcSize == 1) || (nWCalcSize == 2) ) + mnWUnderlineSize = nWCalcSize; + else + mnWUnderlineSize = 3; + } + else + mnWUnderlineSize = ((nWCalcSize*50)+50) / 100; + + + // Don't assume that wavelines are never placed below the descent, because for most fonts the waveline + // is drawn into the text + mnWUnderlineOffset = nUnderlineOffset; + + mnStrikeoutSize = nLineHeight; + mnStrikeoutOffset = nStrikeoutOffset - nLineHeight2; + + mnBStrikeoutSize = nBLineHeight; + mnBStrikeoutOffset = nStrikeoutOffset - nBLineHeight2; + + mnDStrikeoutSize = n2LineHeight; + mnDStrikeoutOffset1 = nStrikeoutOffset - n2LineDY2 - n2LineHeight; + mnDStrikeoutOffset2 = mnDStrikeoutOffset1 + n2LineDY + n2LineHeight; + + mnBulletOffset = ( pDev->GetTextWidth( OUString( u' ' ) ) - pDev->GetTextWidth( OUString( u'\x00b7' ) ) ) >> 1 ; + +} + + +void ImplFontMetricData::ImplInitAboveTextLineSize() +{ + tools::Long nIntLeading = mnIntLeading; + // TODO: assess usage of nLeading below (changed in extleading CWS) + // if no leading is available, we assume 15% of the ascent + if ( nIntLeading <= 0 ) + { + nIntLeading = mnAscent*15/100; + if ( !nIntLeading ) + nIntLeading = 1; + } + + tools::Long nLineHeight = ((nIntLeading*25)+50) / 100; + if ( !nLineHeight ) + nLineHeight = 1; + + tools::Long nBLineHeight = ((nIntLeading*50)+50) / 100; + if ( nBLineHeight == nLineHeight ) + nBLineHeight++; + + tools::Long n2LineHeight = ((nIntLeading*16)+50) / 100; + if ( !n2LineHeight ) + n2LineHeight = 1; + + tools::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; + + tools::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())) + { + tools::Rectangle aRect; + pDev->GetTextBoundRect( aRect, u"\x3001" ); // Fullwidth fullstop + const auto nH = rFont.GetFontSize().Height(); + const auto nB = aRect.Left(); + // Use 18.75% as a threshold to define a centered fullwidth fullstop. + // In general, nB/nH < 5% for most Japanese fonts. + bCentered = nB > (((nH >> 1)+nH)>>3); + } + SetFullstopCenteredFlag( bCentered ); +} + +bool ImplFontMetricData::ShouldUseWinMetrics(const vcl::TTGlobalFontInfo& rInfo) const +{ + 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 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(hb_blob_get_data(pHhea, nullptr)), hb_blob_get_length(pHhea), + reinterpret_cast(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 + ); +} + +void ImplFontMetricData::ImplInitBaselines(LogicalFontInstance *pFontInstance) +{ + hb_font_t* pHbFont = pFontInstance->GetHbFont(); + hb_face_t* pHbFace = hb_font_get_face(pHbFont); + double nUPEM = hb_face_get_upem(pHbFace); + double fScale = mnHeight / nUPEM; + hb_position_t nBaseline = 0; + + if (hb_ot_layout_get_baseline(pHbFont, + HB_OT_LAYOUT_BASELINE_TAG_HANGING, + HB_DIRECTION_INVALID, + HB_SCRIPT_UNKNOWN, + HB_TAG_NONE, + &nBaseline)) + { + mnHangingBaseline = nBaseline * fScale; + } + else + { + mnHangingBaseline = 0; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ -- cgit v1.2.3