diff options
Diffstat (limited to 'vcl/source/font')
-rw-r--r-- | vcl/source/font/DirectFontSubstitution.cxx | 71 | ||||
-rw-r--r-- | vcl/source/font/EmphasisMark.cxx | 174 | ||||
-rw-r--r-- | vcl/source/font/Feature.cxx | 162 | ||||
-rw-r--r-- | vcl/source/font/FeatureCollector.cxx | 206 | ||||
-rw-r--r-- | vcl/source/font/FeatureParser.cxx | 67 | ||||
-rw-r--r-- | vcl/source/font/FontSelectPattern.cxx | 156 | ||||
-rw-r--r-- | vcl/source/font/LogicalFontInstance.cxx | 348 | ||||
-rw-r--r-- | vcl/source/font/OpenTypeFeatureDefinitionList.cxx | 159 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontCollection.cxx | 1279 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontFace.cxx | 510 | ||||
-rw-r--r-- | vcl/source/font/PhysicalFontFamily.cxx | 269 | ||||
-rw-r--r-- | vcl/source/font/font.cxx | 1185 | ||||
-rw-r--r-- | vcl/source/font/fontattributes.cxx | 61 | ||||
-rw-r--r-- | vcl/source/font/fontcache.cxx | 283 | ||||
-rw-r--r-- | vcl/source/font/fontcharmap.cxx | 251 | ||||
-rw-r--r-- | vcl/source/font/fontmetric.cxx | 563 |
16 files changed, 5744 insertions, 0 deletions
diff --git a/vcl/source/font/DirectFontSubstitution.cxx b/vcl/source/font/DirectFontSubstitution.cxx new file mode 100644 index 0000000000..e494fb7ce7 --- /dev/null +++ b/vcl/source/font/DirectFontSubstitution.cxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <unotools/fontdefs.hxx> + +#include <font/DirectFontSubstitution.hxx> + +#include <svdata.hxx> + +#include <string> +#include <vector> + +namespace vcl::font +{ +void DirectFontSubstitution::AddFontSubstitute(const OUString& rFontName, + const OUString& rSubstFontName, + AddFontSubstituteFlags nFlags) +{ + maFontSubstList.emplace_back(rFontName, rSubstFontName, nFlags); +} + +void DirectFontSubstitution::RemoveFontsSubstitute() { maFontSubstList.clear(); } + +bool DirectFontSubstitution::FindFontSubstitute(OUString& rSubstName, + std::u16string_view rSearchName) const +{ + // TODO: get rid of O(N) searches + std::vector<FontSubstEntry>::const_iterator it = std::find_if( + maFontSubstList.begin(), maFontSubstList.end(), [&](const FontSubstEntry& s) { + return (s.mnFlags & AddFontSubstituteFlags::ALWAYS) && (s.maSearchName == rSearchName); + }); + if (it != maFontSubstList.end()) + { + rSubstName = it->maSearchReplaceName; + return true; + } + return false; +} + +void ImplFontSubstitute(OUString& rFontName) +{ + // must be canonicalised + assert(GetEnglishSearchFontName(rFontName) == rFontName); + OUString aSubstFontName; + // apply user-configurable font replacement (eg, from the list in Tools->Options) + const DirectFontSubstitution* pSubst = ImplGetSVData()->maGDIData.mpDirectFontSubst; + if (pSubst && pSubst->FindFontSubstitute(aSubstFontName, rFontName)) + { + rFontName = aSubstFontName; + return; + } +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/EmphasisMark.cxx b/vcl/source/font/EmphasisMark.cxx new file mode 100644 index 0000000000..be1a20223e --- /dev/null +++ b/vcl/source/font/EmphasisMark.cxx @@ -0,0 +1,174 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include <sal/config.h> + +#include <font/EmphasisMark.hxx> + +namespace vcl::font +{ +EmphasisMark::EmphasisMark(FontEmphasisMark eEmphasis, tools::Long nHeight, sal_Int32 nDPIY) +{ + static const PolyFlags aAccentPolyFlags[24] = + { + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Normal, PolyFlags::Control, + PolyFlags::Normal, PolyFlags::Control, PolyFlags::Control + }; + + static const Point aAccentPos[24] = + { + { 78, 0 }, + { 348, 79 }, + { 599, 235 }, + { 843, 469 }, + { 938, 574 }, + { 990, 669 }, + { 990, 773 }, + { 990, 843 }, + { 964, 895 }, + { 921, 947 }, + { 886, 982 }, + { 860, 999 }, + { 825, 999 }, + { 764, 999 }, + { 721, 964 }, + { 686, 895 }, + { 625, 791 }, + { 556, 660 }, + { 469, 504 }, + { 400, 400 }, + { 261, 252 }, + { 61, 61 }, + { 0, 27 }, + { 9, 0 } + }; + + mnWidth = 0; + mnYOff = 0; + mbIsPolyLine = false; + + if ( !nHeight ) + return; + + FontEmphasisMark nEmphasisStyle = eEmphasis & FontEmphasisMark::Style; + tools::Long nDotSize = 0; + switch ( nEmphasisStyle ) + { + case FontEmphasisMark::Dot: + // Dot has 55% of the height + nDotSize = (nHeight*550)/1000; + if ( !nDotSize ) + nDotSize = 1; + if ( nDotSize <= 2 ) + maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) ); + else + { + tools::Long nRad = nDotSize/2; + tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad ); + maPolyPoly.Insert( aPoly ); + } + mnYOff = ((nHeight*250)/1000)/2; // Center to the another EmphasisMarks + mnWidth = nDotSize; + break; + + case FontEmphasisMark::Circle: + // Dot has 80% of the height + nDotSize = (nHeight*800)/1000; + if ( !nDotSize ) + nDotSize = 1; + if ( nDotSize <= 2 ) + maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) ); + else + { + tools::Long nRad = nDotSize/2; + tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad ); + maPolyPoly.Insert( aPoly ); + // Border mnWidth is 15% + tools::Long nBorder = (nDotSize*150)/1000; + if ( nBorder <= 1 ) + mbIsPolyLine = true; + else + { + tools::Polygon aPoly2( Point( nRad, nRad ), + nRad-nBorder, nRad-nBorder ); + maPolyPoly.Insert( aPoly2 ); + } + } + mnWidth = nDotSize; + break; + + case FontEmphasisMark::Disc: + // Dot has 80% of the height + nDotSize = (nHeight*800)/1000; + if ( !nDotSize ) + nDotSize = 1; + if ( nDotSize <= 2 ) + maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) ); + else + { + tools::Long nRad = nDotSize/2; + tools::Polygon aPoly( Point( nRad, nRad ), nRad, nRad ); + maPolyPoly.Insert( aPoly ); + } + mnWidth = nDotSize; + break; + + case FontEmphasisMark::Accent: + // Dot has 80% of the height + nDotSize = (nHeight*800)/1000; + if ( !nDotSize ) + nDotSize = 1; + if ( nDotSize <= 2 ) + { + if ( nDotSize == 1 ) + { + maRect1 = tools::Rectangle( Point(), Size( nDotSize, nDotSize ) ); + mnWidth = nDotSize; + } + else + { + maRect1 = tools::Rectangle( Point(), Size( 1, 1 ) ); + maRect2 = tools::Rectangle( Point( 1, 1 ), Size( 1, 1 ) ); + } + } + else + { + tools::Polygon aPoly( SAL_N_ELEMENTS(aAccentPos), aAccentPos, + aAccentPolyFlags ); + double dScale = static_cast<double>(nDotSize)/1000.0; + aPoly.Scale( dScale, dScale ); + tools::Polygon aTemp; + aPoly.AdaptiveSubdivide( aTemp ); + tools::Rectangle aBoundRect = aTemp.GetBoundRect(); + mnWidth = aBoundRect.GetWidth(); + nDotSize = aBoundRect.GetHeight(); + maPolyPoly.Insert( aTemp ); + } + break; + default: break; + } + + // calculate position + tools::Long nOffY = 1+(nDPIY/300); // one visible pixel space + tools::Long nSpaceY = nHeight-nDotSize; + if ( nSpaceY >= nOffY*2 ) + mnYOff += nOffY; + + if ( !(eEmphasis & FontEmphasisMark::PosBelow) ) + mnYOff += nDotSize; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/Feature.cxx b/vcl/source/font/Feature.cxx new file mode 100644 index 0000000000..ece71df8ed --- /dev/null +++ b/vcl/source/font/Feature.cxx @@ -0,0 +1,162 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#include <utility> +#include <vcl/font/Feature.hxx> +#include <svdata.hxx> + +#include <hb.h> + +namespace vcl::font +{ +OUString featureCodeAsString(uint32_t nFeature) +{ + std::vector<char> aString(5, 0); + aString[0] = char(nFeature >> 24 & 0xff); + aString[1] = char(nFeature >> 16 & 0xff); + aString[2] = char(nFeature >> 8 & 0xff); + aString[3] = char(nFeature >> 0 & 0xff); + + return OStringToOUString(aString.data(), RTL_TEXTENCODING_ASCII_US); +} + +// Feature +Feature::Feature() + : m_nCode(0) + , m_eType(FeatureType::OpenType) +{ +} + +Feature::Feature(uint32_t nCode, FeatureType eType) + : m_nCode(nCode) + , m_eType(eType) +{ +} + +// FeatureSetting +FeatureSetting::FeatureSetting(OString feature) + : m_nTag(0) + , m_nValue(0) + , m_nStart(0) + , m_nEnd(0) +{ + hb_feature_t aFeat; + if (hb_feature_from_string(feature.getStr(), feature.getLength(), &aFeat)) + { + m_nTag = aFeat.tag; + m_nValue = aFeat.value; + m_nStart = aFeat.start; + m_nEnd = aFeat.end; + } +} + +// FeatureParameter + +FeatureParameter::FeatureParameter(uint32_t nCode, OUString aDescription) + : m_nCode(nCode) + , m_sDescription(std::move(aDescription)) +{ +} + +FeatureParameter::FeatureParameter(uint32_t nCode, TranslateId pDescriptionID) + : m_nCode(nCode) + , m_pDescriptionID(pDescriptionID) +{ +} + +OUString FeatureParameter::getDescription() const +{ + OUString aReturnString; + + if (m_pDescriptionID) + aReturnString = VclResId(m_pDescriptionID); + else if (!m_sDescription.isEmpty()) + aReturnString = m_sDescription; + + return aReturnString; +} + +uint32_t FeatureParameter::getCode() const { return m_nCode; } + +// FeatureDefinition + +FeatureDefinition::FeatureDefinition() + : m_nCode(0) + , m_nDefault(-1) + , m_eType(FeatureParameterType::BOOL) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, OUString aDescription, + FeatureParameterType eType, + std::vector<FeatureParameter>&& rEnumParameters, + int32_t nDefault) + : m_sDescription(std::move(aDescription)) + , m_nCode(nCode) + , m_nDefault(nDefault) + , m_eType(eType) + , m_aEnumParameters(std::move(rEnumParameters)) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, TranslateId pDescriptionID, + OUString aNumericPart) + : m_pDescriptionID(pDescriptionID) + , m_sNumericPart(std::move(aNumericPart)) + , m_nCode(nCode) + , m_nDefault(-1) + , m_eType(FeatureParameterType::BOOL) +{ +} + +FeatureDefinition::FeatureDefinition(uint32_t nCode, TranslateId pDescriptionID, + std::vector<FeatureParameter> aEnumParameters) + : m_pDescriptionID(pDescriptionID) + , m_nCode(nCode) + , m_nDefault(-1) + , m_eType(FeatureParameterType::ENUM) + , m_aEnumParameters(std::move(aEnumParameters)) +{ +} + +const std::vector<FeatureParameter>& FeatureDefinition::getEnumParameters() const +{ + return m_aEnumParameters; +} + +OUString FeatureDefinition::getDescription() const +{ + if (m_pDescriptionID) + { + OUString sTranslatedDescription = VclResId(m_pDescriptionID); + if (!m_sNumericPart.isEmpty()) + return sTranslatedDescription.replaceFirst("%1", m_sNumericPart); + return sTranslatedDescription; + } + else if (!m_sDescription.isEmpty()) + { + return m_sDescription; + } + else + { + return vcl::font::featureCodeAsString(m_nCode); + } +} + +uint32_t FeatureDefinition::getCode() const { return m_nCode; } + +FeatureParameterType FeatureDefinition::getType() const { return m_eType; } + +FeatureDefinition::operator bool() const { return m_nCode != 0; } + +int32_t FeatureDefinition::getDefault() const { return m_nDefault; } +} // end vcl::font namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/FeatureCollector.cxx b/vcl/source/font/FeatureCollector.cxx new file mode 100644 index 0000000000..fd175eade0 --- /dev/null +++ b/vcl/source/font/FeatureCollector.cxx @@ -0,0 +1,206 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include <font/FeatureCollector.hxx> +#include <font/OpenTypeFeatureDefinitionList.hxx> +#include <i18nlangtag/languagetag.hxx> + +#include <font/OpenTypeFeatureStrings.hrc> +#include <svdata.hxx> + +#include <hb-ot.h> +#include <hb-graphite2.h> + +namespace vcl::font +{ +bool FeatureCollector::collectGraphite() +{ + gr_face* grFace = hb_graphite2_face_get_gr_face(m_pHbFace); + + if (grFace == nullptr) + return false; + + gr_uint16 nUILanguage = gr_uint16(m_rLanguageTag.getLanguageType()); + + gr_uint16 nNumberOfFeatures = gr_face_n_fref(grFace); + gr_feature_val* pfeatureValues + = gr_face_featureval_for_lang(grFace, 0); // shame we don't know which lang + + for (gr_uint16 i = 0; i < nNumberOfFeatures; ++i) + { + const gr_feature_ref* pFeatureRef = gr_face_fref(grFace, i); + gr_uint32 nFeatureCode = gr_fref_id(pFeatureRef); + + if (nFeatureCode == 0) // illegal feature code - skip + continue; + + gr_uint16 nValue = gr_fref_feature_value(pFeatureRef, pfeatureValues); + gr_uint32 nLabelLength = 0; + void* pLabel = gr_fref_label(pFeatureRef, &nUILanguage, gr_utf8, &nLabelLength); + OUString sLabel(OUString::createFromAscii(static_cast<char*>(pLabel))); + gr_label_destroy(pLabel); + + std::vector<vcl::font::FeatureParameter> aParameters; + gr_uint16 nNumberOfValues = gr_fref_n_values(pFeatureRef); + + if (nNumberOfValues > 0) + { + for (gr_uint16 j = 0; j < nNumberOfValues; ++j) + { + gr_uint32 nValueLabelLength = 0; + void* pValueLabel = gr_fref_value_label(pFeatureRef, j, &nUILanguage, gr_utf8, + &nValueLabelLength); + OUString sValueLabel(OUString::createFromAscii(static_cast<char*>(pValueLabel))); + gr_uint16 nParamValue = gr_fref_value(pFeatureRef, j); + aParameters.emplace_back(sal_uInt32(nParamValue), sValueLabel); + gr_label_destroy(pValueLabel); + } + + auto eFeatureParameterType = vcl::font::FeatureParameterType::ENUM; + + // Check if the parameters are boolean + if (aParameters.size() == 2 + && (aParameters[0].getDescription() == "True" + || aParameters[0].getDescription() == "False")) + { + eFeatureParameterType = vcl::font::FeatureParameterType::BOOL; + aParameters.clear(); + } + + m_rFontFeatures.emplace_back(nFeatureCode, vcl::font::FeatureType::Graphite); + vcl::font::Feature& rFeature = m_rFontFeatures.back(); + rFeature.m_aDefinition + = vcl::font::FeatureDefinition(nFeatureCode, sLabel, eFeatureParameterType, + std::move(aParameters), int32_t(nValue)); + } + } + gr_featureval_destroy(pfeatureValues); + return true; +} + +void FeatureCollector::collectForTable(hb_tag_t aTableTag) +{ + unsigned int nFeatureCount + = hb_ot_layout_table_get_feature_tags(m_pHbFace, aTableTag, 0, nullptr, nullptr); + std::vector<hb_tag_t> aFeatureTags(nFeatureCount); + hb_ot_layout_table_get_feature_tags(m_pHbFace, aTableTag, 0, &nFeatureCount, + aFeatureTags.data()); + aFeatureTags.resize(nFeatureCount); + + for (hb_tag_t aFeatureTag : aFeatureTags) + { + if (OpenTypeFeatureDefinitionList().isRequired(aFeatureTag)) + continue; + + m_rFontFeatures.emplace_back(); + vcl::font::Feature& rFeature = m_rFontFeatures.back(); + rFeature.m_nCode = aFeatureTag; + + FeatureDefinition aDefinition = OpenTypeFeatureDefinitionList().getDefinition(rFeature); + std::vector<vcl::font::FeatureParameter> aParameters{ + { 0, VclResId(STR_FONT_FEATURE_PARAM_NONE) } + }; + + unsigned int nFeatureIdx; + if (hb_ot_layout_language_find_feature(m_pHbFace, aTableTag, 0, + HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX, aFeatureTag, + &nFeatureIdx)) + { + // ssXX and cvXX can have name ID defined for them, check for + // them and use as appropriate. + hb_ot_name_id_t aLabelID; + hb_ot_name_id_t aFirstParameterID; + unsigned nNamedParameters; + if (hb_ot_layout_feature_get_name_ids(m_pHbFace, aTableTag, nFeatureIdx, &aLabelID, + nullptr, nullptr, &nNamedParameters, + &aFirstParameterID)) + { + OUString sLabel = m_pFace->GetName(NameID(aLabelID), m_rLanguageTag); + if (!sLabel.isEmpty()) + aDefinition = vcl::font::FeatureDefinition(aFeatureTag, sLabel); + + // cvXX features can have parameters name IDs, check for + // them and populate feature parameters as appropriate. + for (unsigned i = 0; i < nNamedParameters; i++) + { + hb_ot_name_id_t aNameID = aFirstParameterID + i; + OUString sName = m_pFace->GetName(NameID(aNameID), m_rLanguageTag); + if (!sName.isEmpty()) + aParameters.emplace_back(uint32_t(i + 1), sName); + else + aParameters.emplace_back(uint32_t(i + 1), OUString::number(i + 1)); + } + } + + unsigned int nAlternates = 0; + if (aTableTag == HB_OT_TAG_GSUB) + { + // Collect lookups in this feature, and input glyphs for each + // lookup, and calculate the max number of alternates they have. + unsigned int nLookups = hb_ot_layout_feature_get_lookups( + m_pHbFace, aTableTag, nFeatureIdx, 0, nullptr, nullptr); + std::vector<unsigned int> aLookups(nLookups); + hb_ot_layout_feature_get_lookups(m_pHbFace, aTableTag, nFeatureIdx, 0, &nLookups, + aLookups.data()); + + hb_set_t* pGlyphs = hb_set_create(); + for (unsigned int nLookupIdx : aLookups) + { + hb_set_clear(pGlyphs); + hb_ot_layout_lookup_collect_glyphs(m_pHbFace, aTableTag, nLookupIdx, nullptr, + pGlyphs, nullptr, nullptr); + hb_codepoint_t nGlyphIdx = HB_SET_VALUE_INVALID; + while (hb_set_next(pGlyphs, &nGlyphIdx)) + { + nAlternates + = std::max(nAlternates, + hb_ot_layout_lookup_get_glyph_alternates( + m_pHbFace, nLookupIdx, nGlyphIdx, 0, nullptr, nullptr)); + } + } + hb_set_destroy(pGlyphs); + } + + // Append the alternates to the feature parameters, keeping any + // existing ones calculated from cvXX features above. + for (unsigned int i = aParameters.size() - 1; i < nAlternates; i++) + aParameters.emplace_back(uint32_t(i + 1), OUString::number(i + 1)); + + if (aParameters.size() > 1) + { + aDefinition = vcl::font::FeatureDefinition( + aFeatureTag, aDefinition.getDescription(), + vcl::font::FeatureParameterType::ENUM, std::move(aParameters), 0); + } + } + + if (aDefinition) + rFeature.m_aDefinition = aDefinition; + } +} + +bool FeatureCollector::collect() +{ + gr_face* grFace = hb_graphite2_face_get_gr_face(m_pHbFace); + + if (grFace) + { + return collectGraphite(); + } + else + { + collectForTable(HB_OT_TAG_GSUB); // substitution + collectForTable(HB_OT_TAG_GPOS); // positioning + return true; + } +} + +} // end namespace vcl::font + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/FeatureParser.cxx b/vcl/source/font/FeatureParser.cxx new file mode 100644 index 0000000000..697662032f --- /dev/null +++ b/vcl/source/font/FeatureParser.cxx @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#include <vcl/font/FeatureParser.hxx> +#include <vcl/font/Feature.hxx> +#include <o3tl/string_view.hxx> + +namespace vcl::font +{ +OUString trimFontNameFeatures(OUString const& rFontName) +{ + const sal_Int32 nPrefixIdx{ rFontName.indexOf(vcl::font::FeaturePrefix) }; + + if (nPrefixIdx < 0) + return rFontName; + + return rFontName.copy(0, nPrefixIdx); +} + +FeatureParser::FeatureParser(std::u16string_view rFontName) +{ + size_t nPrefixIdx{ rFontName.find(vcl::font::FeaturePrefix) }; + + if (nPrefixIdx == std::u16string_view::npos) + return; + + std::u16string_view sName(rFontName.substr(++nPrefixIdx)); + sal_Int32 nIndex = 0; + do + { + std::u16string_view sToken = o3tl::getToken(sName, 0, vcl::font::FeatureSeparator, nIndex); + + sal_Int32 nInnerIdx{ 0 }; + std::u16string_view sID = o3tl::getToken(sToken, 0, '=', nInnerIdx); + + if (sID == u"lang") + { + m_sLanguage = o3tl::getToken(sToken, 0, '=', nInnerIdx); + } + else + { + OString sFeature = OUStringToOString(sToken, RTL_TEXTENCODING_ASCII_US); + FeatureSetting aFeature(sFeature); + if (aFeature.m_nTag != 0) + m_aFeatures.push_back(aFeature); + } + } while (nIndex >= 0); +} + +std::unordered_map<uint32_t, int32_t> FeatureParser::getFeaturesMap() const +{ + std::unordered_map<uint32_t, int32_t> aResultMap; + for (auto const& rFeat : m_aFeatures) + aResultMap.emplace(rFeat.m_nTag, rFeat.m_nValue); + return aResultMap; +} + +} // end vcl::font namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/FontSelectPattern.cxx b/vcl/source/font/FontSelectPattern.cxx new file mode 100644 index 0000000000..30c2c9aaa5 --- /dev/null +++ b/vcl/source/font/FontSelectPattern.cxx @@ -0,0 +1,156 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> +#include <o3tl/safeint.hxx> +#include <tools/gen.hxx> + +#include <utility> +#include <vcl/font.hxx> + +#include <font/FontSelectPattern.hxx> +#include <font/PhysicalFontFace.hxx> + +namespace vcl::font +{ + +// These mustn't conflict with font name lists which use ; and , +const char FontSelectPattern::FEAT_PREFIX = ':'; +const char FontSelectPattern::FEAT_SEPARATOR = '&'; + +FontSelectPattern::FontSelectPattern( const vcl::Font& rFont, + OUString aSearchName, const Size& rSize, float fExactHeight, bool bNonAntialias) + : maSearchName(std::move( aSearchName )) + , mnWidth( rSize.Width() ) + , mnHeight( rSize.Height() ) + , mfExactHeight( fExactHeight) + , mnOrientation( rFont.GetOrientation() ) + , meLanguage( rFont.GetLanguage() ) + , mbVertical( rFont.IsVertical() ) + , mbNonAntialiased(bNonAntialias) + , mbEmbolden( false ) +{ + maTargetName = GetFamilyName(); + + rFont.GetFontAttributes( *this ); + + // normalize orientation between 0 and 3600 + if( mnOrientation < 0_deg10 || mnOrientation >= 3600_deg10 ) + { + if( mnOrientation >= 0_deg10 ) + mnOrientation %= 3600_deg10; + else + mnOrientation = 3600_deg10 - (-mnOrientation % 3600_deg10); + } + + // normalize width and height + if( mnHeight < 0 ) + mnHeight = o3tl::saturating_toggle_sign(mnHeight); + if( mnWidth < 0 ) + mnWidth = o3tl::saturating_toggle_sign(mnWidth); +} + + +// NOTE: this ctor is still used on Windows. Do not remove. +#ifdef _WIN32 +FontSelectPattern::FontSelectPattern( const PhysicalFontFace& rFontData, + const Size& rSize, float fExactHeight, int nOrientation, bool bVertical ) + : FontAttributes( rFontData ) + , mnWidth( rSize.Width() ) + , mnHeight( rSize.Height() ) + , mfExactHeight( fExactHeight ) + , mnOrientation( nOrientation ) + , meLanguage( 0 ) + , mbVertical( bVertical ) + , mbNonAntialiased( false ) + , mbEmbolden( false ) +{ + maTargetName = maSearchName = GetFamilyName(); + // NOTE: no normalization for width/height/orientation +} + +#endif + +size_t FontSelectPattern::hashCode() const +{ + // TODO: does it pay off to improve this hash function? + size_t nHash; + // check for features and generate a unique hash if necessary + if (maTargetName.indexOf(FontSelectPattern::FEAT_PREFIX) + != -1) + { + nHash = maTargetName.hashCode(); + } + else + { + nHash = maSearchName.hashCode(); + } + nHash += 11U * mnHeight; + nHash += 19 * GetWeight(); + nHash += 29 * GetItalic(); + nHash += 37 * mnOrientation.get(); + nHash += 41 * static_cast<sal_uInt16>(meLanguage); + if( mbVertical ) + nHash += 53; + return nHash; +} + +bool FontSelectPattern::operator==(const FontSelectPattern& rOther) const +{ + if (!CompareDeviceIndependentFontAttributes(rOther)) + return false; + + if (maTargetName != rOther.maTargetName) + return false; + + if (maSearchName != rOther.maSearchName) + return false; + + if (mnWidth != rOther.mnWidth) + return false; + + if (mnHeight != rOther.mnHeight) + return false; + + if (mfExactHeight != rOther.mfExactHeight) + return false; + + if (mnOrientation != rOther.mnOrientation) + return false; + + if (meLanguage != rOther.meLanguage) + return false; + + if (mbVertical != rOther.mbVertical) + return false; + + if (mbNonAntialiased != rOther.mbNonAntialiased) + return false; + + if (mbEmbolden != rOther.mbEmbolden) + return false; + + if (maItalicMatrix != rOther.maItalicMatrix) + return false; + + return true; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/LogicalFontInstance.cxx b/vcl/source/font/LogicalFontInstance.cxx new file mode 100644 index 0000000000..0c21cba475 --- /dev/null +++ b/vcl/source/font/LogicalFontInstance.cxx @@ -0,0 +1,348 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <hb-ot.h> +#include <hb-graphite2.h> + +#include <font/PhysicalFontFace.hxx> +#include <font/LogicalFontInstance.hxx> +#include <impfontcache.hxx> + +LogicalFontInstance::LogicalFontInstance(const vcl::font::PhysicalFontFace& rFontFace, + const vcl::font::FontSelectPattern& rFontSelData) + : mxFontMetric(new FontMetricData(rFontSelData)) + , mpConversion(nullptr) + , mnLineHeight(0) + , mnOwnOrientation(0) + , mnOrientation(0) + , mbInit(false) + , mpFontCache(nullptr) + , m_aFontSelData(rFontSelData) + , m_pHbFont(nullptr) + , m_nAveWidthFactor(1.0f) + , m_pFontFace(&const_cast<vcl::font::PhysicalFontFace&>(rFontFace)) +{ +} + +LogicalFontInstance::~LogicalFontInstance() +{ + maUnicodeFallbackList.clear(); + mpFontCache = nullptr; + mxFontMetric = nullptr; + + if (m_pHbFont) + hb_font_destroy(m_pHbFont); + + if (m_pHbFontUntransformed) + hb_font_destroy(m_pHbFontUntransformed); + + if (m_pHbDrawFuncs) + hb_draw_funcs_destroy(m_pHbDrawFuncs); +} + +hb_font_t* LogicalFontInstance::InitHbFont() +{ + auto pFace = GetFontFace(); + hb_face_t* pHbFace = pFace->GetHbFace(); + assert(pHbFace); + auto nUPEM = pFace->UnitsPerEm(); + + hb_font_t* pHbFont = hb_font_create(pHbFace); + hb_font_set_scale(pHbFont, nUPEM, nUPEM); + hb_ot_font_set_funcs(pHbFont); + + auto aVariations = pFace->GetVariations(*this); + if (!aVariations.empty()) + hb_font_set_variations(pHbFont, aVariations.data(), aVariations.size()); + + // If we are applying artificial italic, instruct HarfBuzz to do the same + // so that mark positioning is also transformed. + if (NeedsArtificialItalic()) + hb_font_set_synthetic_slant(pHbFont, ARTIFICIAL_ITALIC_SKEW); + + ImplInitHbFont(pHbFont); + + return pHbFont; +} + +hb_font_t* LogicalFontInstance::GetHbFontUntransformed() const +{ + auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont(); + + if (NeedsArtificialItalic()) // || NeedsArtificialBold() + { + if (!m_pHbFontUntransformed) + { + m_pHbFontUntransformed = hb_font_create_sub_font(pHbFont); + // Unset slant set on parent font. + // Does not actually work: https://github.com/harfbuzz/harfbuzz/issues/3890 + hb_font_set_synthetic_slant(m_pHbFontUntransformed, 0); + } + return m_pHbFontUntransformed; + } + + return pHbFont; +} + +double LogicalFontInstance::GetKashidaWidth() const +{ + sal_GlyphId nGlyph = GetGlyphIndex(0x0640); + if (nGlyph) + return GetGlyphWidth(nGlyph); + return 0; +} + +void LogicalFontInstance::GetScale(double* nXScale, double* nYScale) const +{ + double nUPEM = GetFontFace()->UnitsPerEm(); + double nHeight(m_aFontSelData.mnHeight); + + // On Windows, mnWidth is relative to average char width not font height, + // and we need to keep it that way for GDI to correctly scale the glyphs. + // Here we compensate for this so that HarfBuzz gives us the correct glyph + // positions. + double nWidth(m_aFontSelData.mnWidth ? m_aFontSelData.mnWidth * m_nAveWidthFactor : nHeight); + + if (nYScale) + *nYScale = nHeight / nUPEM; + + if (nXScale) + *nXScale = nWidth / nUPEM; +} + +void LogicalFontInstance::AddFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight, + const OUString& rFontName, bool bEmbolden, + const ItalicMatrix& rMatrix) +{ + MapEntry& rEntry = maUnicodeFallbackList[std::pair<sal_UCS4, FontWeight>(cChar, eWeight)]; + rEntry.sFontName = rFontName; + rEntry.bEmbolden = bEmbolden; + rEntry.aItalicMatrix = rMatrix; +} + +bool LogicalFontInstance::GetFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight, + OUString* pFontName, bool* pEmbolden, + ItalicMatrix* pMatrix) const +{ + UnicodeFallbackList::const_iterator it + = maUnicodeFallbackList.find(std::pair<sal_UCS4, FontWeight>(cChar, eWeight)); + if (it == maUnicodeFallbackList.end()) + return false; + + const MapEntry& rEntry = (*it).second; + *pFontName = rEntry.sFontName; + *pEmbolden = rEntry.bEmbolden; + *pMatrix = rEntry.aItalicMatrix; + return true; +} + +void LogicalFontInstance::IgnoreFallbackForUnicode(sal_UCS4 cChar, FontWeight eWeight, + std::u16string_view rFontName) +{ + UnicodeFallbackList::iterator it + = maUnicodeFallbackList.find(std::pair<sal_UCS4, FontWeight>(cChar, eWeight)); + if (it == maUnicodeFallbackList.end()) + return; + const MapEntry& rEntry = (*it).second; + if (rEntry.sFontName == rFontName) + maUnicodeFallbackList.erase(it); +} + +bool LogicalFontInstance::GetGlyphBoundRect(sal_GlyphId nID, tools::Rectangle& rRect, + bool bVertical) const +{ + if (mpFontCache && mpFontCache->GetCachedGlyphBoundRect(this, nID, rRect)) + return true; + + auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont(); + hb_glyph_extents_t aExtents; + bool res = hb_font_get_glyph_extents(pHbFont, nID, &aExtents); + + if (res) + { + double nXScale = 0, nYScale = 0; + GetScale(&nXScale, &nYScale); + + double fMinX = aExtents.x_bearing; + double fMinY = aExtents.y_bearing; + double fMaxX = aExtents.x_bearing + aExtents.width; + double fMaxY = aExtents.y_bearing + aExtents.height; + + tools::Rectangle aRect(std::floor(fMinX * nXScale), -std::ceil(fMinY * nYScale), + std::ceil(fMaxX * nXScale), -std::floor(fMaxY * nYScale)); + if (mnOrientation && !bVertical) + { + // Apply font rotation. + const double fRad = toRadians(mnOrientation); + const double fCos = cos(fRad); + const double fSin = sin(fRad); + + rRect.SetLeft(fCos * aRect.Left() + fSin * aRect.Top()); + rRect.SetTop(-fSin * aRect.Left() - fCos * aRect.Top()); + rRect.SetRight(fCos * aRect.Right() + fSin * aRect.Bottom()); + rRect.SetBottom(-fSin * aRect.Right() - fCos * aRect.Bottom()); + } + else + rRect = aRect; + } + + if (mpFontCache && res) + mpFontCache->CacheGlyphBoundRect(this, nID, rRect); + return res; +} + +sal_GlyphId LogicalFontInstance::GetGlyphIndex(uint32_t nUnicode, uint32_t nVariationSelector) const +{ + auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont(); + sal_GlyphId nGlyph = 0; + if (hb_font_get_glyph(pHbFont, nUnicode, nVariationSelector, &nGlyph)) + return nGlyph; + return 0; +} + +double LogicalFontInstance::GetGlyphWidth(sal_GlyphId nGlyph, bool bVertical, bool bScale) const +{ + auto* pHbFont = const_cast<LogicalFontInstance*>(this)->GetHbFont(); + int nWidth; + if (bVertical) + nWidth = hb_font_get_glyph_v_advance(pHbFont, nGlyph); + else + nWidth = hb_font_get_glyph_h_advance(pHbFont, nGlyph); + + if (!bScale) + return nWidth; + + double nScale = 0; + GetScale(&nScale, nullptr); + return double(nWidth * nScale); +} + +bool LogicalFontInstance::IsGraphiteFont() +{ + if (!m_xbIsGraphiteFont.has_value()) + { + m_xbIsGraphiteFont + = hb_graphite2_face_get_gr_face(hb_font_get_face(GetHbFont())) != nullptr; + } + return *m_xbIsGraphiteFont; +} + +bool LogicalFontInstance::NeedOffsetCorrection(sal_Int32 nYOffset) +{ + if (!m_xeFontFamilyEnum) + { + m_xeFontFamilyEnum = FontFamilyEnum::Unclassified; + + // DFKai-SB (ukai.ttf) is a built-in font under traditional Chinese + // Windows. It has wrong extent values in glyf table. The problem results + // in wrong positioning of glyphs in vertical writing. + // Check https://github.com/harfbuzz/harfbuzz/issues/3521 for reference. + if (GetFontFace()->GetName(vcl::font::NAME_ID_FONT_FAMILY) == "DFKai-SB") + m_xeFontFamilyEnum = FontFamilyEnum::DFKaiSB; + } + + bool bRet = true; + + switch (*m_xeFontFamilyEnum) + { + case FontFamilyEnum::DFKaiSB: + // -839: optimization for one third of ukai.ttf + if (nYOffset == -839) + bRet = false; + break; + default: + bRet = false; + } + + return bRet; +} + +bool LogicalFontInstance::NeedsArtificialBold() const +{ + return m_aFontSelData.GetWeight() > WEIGHT_MEDIUM && m_pFontFace->GetWeight() <= WEIGHT_MEDIUM; +} + +bool LogicalFontInstance::NeedsArtificialItalic() const +{ + return m_aFontSelData.GetItalic() != ITALIC_NONE && m_pFontFace->GetItalic() == ITALIC_NONE; +} + +namespace +{ +void move_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float to_x, float to_y, + void* pUserData) +{ + auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData); + pPoly->append(basegfx::B2DPoint(to_x, -to_y)); +} + +void line_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float to_x, float to_y, + void* pUserData) +{ + auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData); + pPoly->append(basegfx::B2DPoint(to_x, -to_y)); +} + +void cubic_to_func(hb_draw_funcs_t*, void* /*pDrawData*/, hb_draw_state_t*, float control1_x, + float control1_y, float control2_x, float control2_y, float to_x, float to_y, + void* pUserData) +{ + auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData); + pPoly->appendBezierSegment(basegfx::B2DPoint(control1_x, -control1_y), + basegfx::B2DPoint(control2_x, -control2_y), + basegfx::B2DPoint(to_x, -to_y)); +} + +void close_path_func(hb_draw_funcs_t*, void* pDrawData, hb_draw_state_t*, void* pUserData) +{ + auto pPolyPoly = static_cast<basegfx::B2DPolyPolygon*>(pDrawData); + auto pPoly = static_cast<basegfx::B2DPolygon*>(pUserData); + pPolyPoly->append(*pPoly); + pPoly->clear(); +} +} + +basegfx::B2DPolyPolygon LogicalFontInstance::GetGlyphOutlineUntransformed(sal_GlyphId nGlyph) const +{ + if (!m_pHbDrawFuncs) + { + m_pHbDrawFuncs = hb_draw_funcs_create(); + auto pUserData = const_cast<basegfx::B2DPolygon*>(&m_aDrawPolygon); + hb_draw_funcs_set_move_to_func(m_pHbDrawFuncs, move_to_func, pUserData, nullptr); + hb_draw_funcs_set_line_to_func(m_pHbDrawFuncs, line_to_func, pUserData, nullptr); + hb_draw_funcs_set_cubic_to_func(m_pHbDrawFuncs, cubic_to_func, pUserData, nullptr); + // B2DPolyPolygon does not support quadratic curves, HarfBuzz will + // convert them to cubic curves for us if we don’t set a callback + // function. + //hb_draw_funcs_set_quadratic_to_func(m_pHbDrawFuncs, quadratic_to_func, pUserData, nullptr); + hb_draw_funcs_set_close_path_func(m_pHbDrawFuncs, close_path_func, pUserData, nullptr); + } + + basegfx::B2DPolyPolygon aPolyPoly; +#if HB_VERSION_ATLEAST(7, 0, 0) + hb_font_draw_glyph(GetHbFontUntransformed(), nGlyph, m_pHbDrawFuncs, &aPolyPoly); +#else + hb_font_get_glyph_shape(GetHbFontUntransformed(), nGlyph, m_pHbDrawFuncs, &aPolyPoly); +#endif + return aPolyPoly; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/OpenTypeFeatureDefinitionList.cxx b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx new file mode 100644 index 0000000000..0400833937 --- /dev/null +++ b/vcl/source/font/OpenTypeFeatureDefinitionList.cxx @@ -0,0 +1,159 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + */ + +#include <font/OpenTypeFeatureDefinitionList.hxx> +#include <font/OpenTypeFeatureStrings.hrc> + +#include <rtl/character.hxx> + +#include <algorithm> + +namespace vcl::font +{ +OpenTypeFeatureDefinitionListPrivate& OpenTypeFeatureDefinitionList() +{ + static OpenTypeFeatureDefinitionListPrivate SINGLETON; + return SINGLETON; +}; + +OpenTypeFeatureDefinitionListPrivate::OpenTypeFeatureDefinitionListPrivate() { init(); } + +void OpenTypeFeatureDefinitionListPrivate::init() +{ + m_aFeatureDefinition.assign({ + { featureCode("aalt"), STR_FONT_FEATURE_ID_AALT }, + { featureCode("afrc"), STR_FONT_FEATURE_ID_AFRC }, + { featureCode("alig"), STR_FONT_FEATURE_ID_ALIG }, + { featureCode("c2pc"), STR_FONT_FEATURE_ID_C2PC }, + { featureCode("c2sc"), STR_FONT_FEATURE_ID_C2SC }, + { featureCode("calt"), STR_FONT_FEATURE_ID_CALT }, + { featureCode("case"), STR_FONT_FEATURE_ID_CASE }, + { featureCode("clig"), STR_FONT_FEATURE_ID_CLIG }, + { featureCode("cpct"), STR_FONT_FEATURE_ID_CPCT }, + { featureCode("cpsp"), STR_FONT_FEATURE_ID_CPSP }, + { featureCode("cswh"), STR_FONT_FEATURE_ID_CSWH }, + { featureCode("dcap"), STR_FONT_FEATURE_ID_DCAP }, + { featureCode("dlig"), STR_FONT_FEATURE_ID_DLIG }, + { featureCode("dnom"), STR_FONT_FEATURE_ID_DNOM }, + { featureCode("dpng"), STR_FONT_FEATURE_ID_DPNG }, + { featureCode("expt"), STR_FONT_FEATURE_ID_EXPT }, + { featureCode("falt"), STR_FONT_FEATURE_ID_FALT }, + { featureCode("frac"), STR_FONT_FEATURE_ID_FRAC }, + { featureCode("fwid"), STR_FONT_FEATURE_ID_FWID }, + { featureCode("halt"), STR_FONT_FEATURE_ID_HALT }, + { featureCode("hist"), STR_FONT_FEATURE_ID_HIST }, + { featureCode("hkna"), STR_FONT_FEATURE_ID_HKNA }, + { featureCode("hlig"), STR_FONT_FEATURE_ID_HLIG }, + { featureCode("hngl"), STR_FONT_FEATURE_ID_HNGL }, + { featureCode("hojo"), STR_FONT_FEATURE_ID_HOJO }, + { featureCode("hwid"), STR_FONT_FEATURE_ID_HWID }, + { featureCode("ital"), STR_FONT_FEATURE_ID_ITAL }, + { featureCode("jalt"), STR_FONT_FEATURE_ID_JALT }, + { featureCode("jp78"), STR_FONT_FEATURE_ID_JP78 }, + { featureCode("jp83"), STR_FONT_FEATURE_ID_JP83 }, + { featureCode("jp90"), STR_FONT_FEATURE_ID_JP90 }, + { featureCode("jp04"), STR_FONT_FEATURE_ID_JP04 }, + { featureCode("kern"), STR_FONT_FEATURE_ID_KERN }, + { featureCode("lfbd"), STR_FONT_FEATURE_ID_LFBD }, + { featureCode("liga"), STR_FONT_FEATURE_ID_LIGA }, + { featureCode("lnum"), STR_FONT_FEATURE_ID_LNUM }, + { featureCode("mgrk"), STR_FONT_FEATURE_ID_MGRK }, + { featureCode("nalt"), STR_FONT_FEATURE_ID_NALT }, + { featureCode("nlck"), STR_FONT_FEATURE_ID_NLCK }, + { featureCode("numr"), STR_FONT_FEATURE_ID_NUMR }, + { featureCode("onum"), STR_FONT_FEATURE_ID_ONUM }, + { featureCode("opbd"), STR_FONT_FEATURE_ID_OPBD }, + { featureCode("ordn"), STR_FONT_FEATURE_ID_ORDN }, + { featureCode("ornm"), STR_FONT_FEATURE_ID_ORNM }, + { featureCode("palt"), STR_FONT_FEATURE_ID_PALT }, + { featureCode("pcap"), STR_FONT_FEATURE_ID_PCAP }, + { featureCode("pkna"), STR_FONT_FEATURE_ID_PKNA }, + { featureCode("pnum"), STR_FONT_FEATURE_ID_PNUM }, + { featureCode("pwid"), STR_FONT_FEATURE_ID_PWID }, + { featureCode("qwid"), STR_FONT_FEATURE_ID_QWID }, + { featureCode("rtbd"), STR_FONT_FEATURE_ID_RTBD }, + { featureCode("ruby"), STR_FONT_FEATURE_ID_RUBY }, + { featureCode("salt"), STR_FONT_FEATURE_ID_SALT }, + { featureCode("sinf"), STR_FONT_FEATURE_ID_SINF }, + { featureCode("smcp"), STR_FONT_FEATURE_ID_SMCP }, + { featureCode("smpl"), STR_FONT_FEATURE_ID_SMPL }, + { featureCode("subs"), STR_FONT_FEATURE_ID_SUBS }, + { featureCode("sups"), STR_FONT_FEATURE_ID_SUPS }, + { featureCode("swsh"), STR_FONT_FEATURE_ID_SWSH }, + { featureCode("titl"), STR_FONT_FEATURE_ID_TITL }, + { featureCode("tnam"), STR_FONT_FEATURE_ID_TNAM }, + { featureCode("tnum"), STR_FONT_FEATURE_ID_TNUM }, + { featureCode("trad"), STR_FONT_FEATURE_ID_TRAD }, + { featureCode("twid"), STR_FONT_FEATURE_ID_TWID }, + { featureCode("unic"), STR_FONT_FEATURE_ID_UNIC }, + { featureCode("valt"), STR_FONT_FEATURE_ID_VALT }, + { featureCode("vhal"), STR_FONT_FEATURE_ID_VHAL }, + { featureCode("vkna"), STR_FONT_FEATURE_ID_VKNA }, + { featureCode("vkrn"), STR_FONT_FEATURE_ID_VKRN }, + { featureCode("vpal"), STR_FONT_FEATURE_ID_VPAL }, + { featureCode("vrt2"), STR_FONT_FEATURE_ID_VRT2 }, + { featureCode("vrtr"), STR_FONT_FEATURE_ID_VRTR }, + { featureCode("zero"), STR_FONT_FEATURE_ID_ZERO }, + }); + + for (size_t i = 0; i < m_aFeatureDefinition.size(); ++i) + { + m_aCodeToIndex.emplace(m_aFeatureDefinition[i].getCode(), i); + } + + m_aRequiredFeatures.assign({ + featureCode("abvf"), featureCode("abvm"), featureCode("abvs"), featureCode("akhn"), + featureCode("blwf"), featureCode("blwm"), featureCode("blws"), featureCode("ccmp"), + featureCode("cfar"), featureCode("cjct"), featureCode("curs"), featureCode("dist"), + featureCode("dtls"), featureCode("fin2"), featureCode("fin3"), featureCode("fina"), + featureCode("flac"), featureCode("half"), featureCode("haln"), featureCode("init"), + featureCode("isol"), featureCode("ljmo"), featureCode("locl"), featureCode("ltra"), + featureCode("ltrm"), featureCode("mark"), featureCode("med2"), featureCode("medi"), + featureCode("mkmk"), featureCode("mset"), featureCode("nukt"), featureCode("pref"), + featureCode("pres"), featureCode("pstf"), featureCode("psts"), featureCode("rand"), + featureCode("rclt"), featureCode("rkrf"), featureCode("rlig"), featureCode("rphf"), + featureCode("rtla"), featureCode("rtlm"), featureCode("rvrn"), featureCode("size"), + featureCode("ssty"), featureCode("stch"), featureCode("tjmo"), featureCode("vatu"), + featureCode("vert"), featureCode("vjmo"), + }); +} + +FeatureDefinition OpenTypeFeatureDefinitionListPrivate::getDefinition(vcl::font::Feature& rFeature) +{ + if (rFeature.isCharacterVariant() || rFeature.isStylisticSet()) + { + FeatureDefinition aFeatureDefinition; + OUString sNumericPart = OUStringChar(char((rFeature.m_nCode >> 8) & 0xFF)) + + OUStringChar(char((rFeature.m_nCode >> 0) & 0xFF)); + if (rFeature.isCharacterVariant()) + aFeatureDefinition = { rFeature.m_nCode, STR_FONT_FEATURE_ID_CVXX, sNumericPart }; + else if (rFeature.isStylisticSet()) + aFeatureDefinition = { rFeature.m_nCode, STR_FONT_FEATURE_ID_SSXX, sNumericPart }; + return aFeatureDefinition; + } + + auto nFeatureCode = rFeature.m_nCode; + if (m_aCodeToIndex.find(nFeatureCode) != m_aCodeToIndex.end()) + { + size_t nIndex = m_aCodeToIndex.at(nFeatureCode); + return m_aFeatureDefinition[nIndex]; + } + return FeatureDefinition(); +} + +bool OpenTypeFeatureDefinitionListPrivate::isRequired(sal_uInt32 nFeatureCode) +{ + return std::find(m_aRequiredFeatures.begin(), m_aRequiredFeatures.end(), nFeatureCode) + != m_aRequiredFeatures.end(); +} + +} // end vcl::font namespace + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/PhysicalFontCollection.cxx b/vcl/source/font/PhysicalFontCollection.cxx new file mode 100644 index 0000000000..04b031ad6b --- /dev/null +++ b/vcl/source/font/PhysicalFontCollection.cxx @@ -0,0 +1,1279 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <memory> + +#include <i18nlangtag/languagetag.hxx> +#include <i18nlangtag/mslangid.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/fontdefs.hxx> +#include <o3tl/sorted_vector.hxx> + +#include <font/PhysicalFontFaceCollection.hxx> +#include <font/PhysicalFontCollection.hxx> +#include <font/fontsubstitution.hxx> + +static ImplFontAttrs lcl_IsCJKFont( std::u16string_view rFontName ) +{ + // Test, if Fontname includes CJK characters --> In this case we + // mention that it is a CJK font + for(size_t i = 0; i < rFontName.size(); i++) + { + const sal_Unicode ch = rFontName[i]; + // japanese + if ( ((ch >= 0x3040) && (ch <= 0x30FF)) || + ((ch >= 0x3190) && (ch <= 0x319F)) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_JP; + + // korean + if ( ((ch >= 0xAC00) && (ch <= 0xD7AF)) || + ((ch >= 0xA960) && (ch <= 0xA97F)) || + ((ch >= 0xD7B0) && (ch <= 0xD7FF)) || + ((ch >= 0x3130) && (ch <= 0x318F)) || + ((ch >= 0x1100) && (ch <= 0x11FF)) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_KR; + + // chinese + if ( (ch >= 0x3400) && (ch <= 0x9FFF) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_TC|ImplFontAttrs::CJK_SC; + + // cjk + if ( ((ch >= 0x3000) && (ch <= 0xD7AF)) || + ((ch >= 0xFF00) && (ch <= 0xFFEE)) ) + return ImplFontAttrs::CJK; + + } + + return ImplFontAttrs::None; +} + +namespace vcl::font +{ + +PhysicalFontCollection::PhysicalFontCollection() + : mbMatchData( false ) + , mpPreMatchHook( nullptr ) + , mpFallbackHook( nullptr ) + , mnFallbackCount( -1 ) +{} + +PhysicalFontCollection::~PhysicalFontCollection() +{ + Clear(); +} + +void PhysicalFontCollection::SetPreMatchHook(PreMatchFontSubstitution* pHook) +{ + mpPreMatchHook = pHook; +} + +void PhysicalFontCollection::SetFallbackHook(GlyphFallbackFontSubstitution* pHook) +{ + mpFallbackHook = pHook; +} + +void PhysicalFontCollection::Clear() +{ + // remove fallback lists + mpFallbackList.reset(); + mnFallbackCount = -1; + + // clear all entries in the device font list + maPhysicalFontFamilies.clear(); + + // match data must be recalculated too + mbMatchData = false; +} + +void PhysicalFontCollection::ImplInitGenericGlyphFallback() const +{ + // normalized family names of fonts suited for glyph fallback + // if a font is available related fonts can be ignored + // TODO: implement dynamic lists + static const char* aGlyphFallbackList[] = { + // empty strings separate the names of unrelated fonts + "eudc", "", + "arialunicodems", "cyberbit", "code2000", "", + "andalesansui", "", + "starsymbol", "opensymbol", "", + "msmincho", "fzmingti", "fzheiti", "ipamincho", "sazanamimincho", "kochimincho", "", + "sunbatang", "sundotum", "baekmukdotum", "gulim", "batang", "dotum", "", + "hgmincholightj", "msunglightsc", "msunglighttc", "hymyeongjolightk", "", + "tahoma", "dejavusans", "timesnewroman", "liberationsans", "", + "shree", "mangal", "", + "raavi", "shruti", "tunga", "", + "latha", "gautami", "kartika", "vrinda", "", + "shayyalmt", "naskmt", "scheherazade", "", + "david", "nachlieli", "lucidagrande", "", + "norasi", "angsanaupc", "", + "khmerossystem", "", + "muktinarrow", "", + "phetsarathot", "", + "padauk", "pinlonmyanmar", "", + "iskoolapota", "lklug", "", + nullptr + }; + + bool bHasEudc = false; + int nMaxLevel = 0; + int nBestQuality = 0; + std::unique_ptr<std::array<PhysicalFontFamily*,MAX_GLYPHFALLBACK>> pFallbackList; + + for( const char** ppNames = &aGlyphFallbackList[0];; ++ppNames ) + { + // advance to next sub-list when end-of-sublist marker + if( !**ppNames ) // #i46456# check for empty string, i.e., deref string itself not only ptr to it + { + if( nBestQuality > 0 ) + if( ++nMaxLevel >= MAX_GLYPHFALLBACK ) + break; + + if( !ppNames[1] ) + break; + + nBestQuality = 0; + continue; + } + + // test if the glyph fallback candidate font is available and scalable + OUString aTokenName( *ppNames, strlen(*ppNames), RTL_TEXTENCODING_UTF8 ); + PhysicalFontFamily* pFallbackFont = FindFontFamily( aTokenName ); + + if( !pFallbackFont ) + continue; + + // keep the best font of the glyph fallback sub-list + if( nBestQuality < pFallbackFont->GetMinQuality() ) + { + nBestQuality = pFallbackFont->GetMinQuality(); + // store available glyph fallback fonts + if( !pFallbackList ) + pFallbackList.reset(new std::array<PhysicalFontFamily*,MAX_GLYPHFALLBACK>); + + (*pFallbackList)[ nMaxLevel ] = pFallbackFont; + if( !bHasEudc && !nMaxLevel ) + bHasEudc = !strncmp( *ppNames, "eudc", 5 ); + } + } + + mnFallbackCount = nMaxLevel; + mpFallbackList = std::move(pFallbackList); +} + +PhysicalFontFamily* PhysicalFontCollection::GetGlyphFallbackFont(FontSelectPattern& rFontSelData, + LogicalFontInstance* pFontInstance, + OUString& rMissingCodes, + int nFallbackLevel) const +{ + PhysicalFontFamily* pFallbackData = nullptr; + + // find a matching font candidate for platform specific glyph fallback + if( mpFallbackHook ) + { + // check cache for the first matching entry + // to avoid calling the expensive fallback hook (#i83491#) + sal_UCS4 cChar = 0; + bool bCached = true; + sal_Int32 nStrIndex = 0; + while( nStrIndex < rMissingCodes.getLength() ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &rFontSelData.maSearchName, + &rFontSelData.mbEmbolden, + &rFontSelData.maItalicMatrix); + + // ignore entries which don't have a fallback + if( !bCached || !rFontSelData.maSearchName.isEmpty() ) + break; + } + + if( bCached ) + { + // there is a matching fallback in the cache + // so update rMissingCodes with codepoints not yet resolved by this fallback + int nRemainingLength = 0; + std::unique_ptr<sal_UCS4[]> const pRemainingCodes(new sal_UCS4[rMissingCodes.getLength()]); + OUString aFontName; + bool bEmbolden; + ItalicMatrix aMatrix; + + while( nStrIndex < rMissingCodes.getLength() ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + bCached = pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &aFontName, &bEmbolden, &aMatrix); + if (!bCached || rFontSelData.maSearchName != aFontName || + rFontSelData.mbEmbolden != bEmbolden || + rFontSelData.maItalicMatrix != aMatrix) + { + pRemainingCodes[ nRemainingLength++ ] = cChar; + } + } + rMissingCodes = OUString( pRemainingCodes.get(), nRemainingLength ); + } + else + { + OUString aOldMissingCodes = rMissingCodes; + + // call the hook to query the best matching glyph fallback font + if (mpFallbackHook->FindFontSubstitute(rFontSelData, pFontInstance, rMissingCodes)) + // apply outdev3.cxx specific fontname normalization + rFontSelData.maSearchName = GetEnglishSearchFontName( rFontSelData.maSearchName ); + else + rFontSelData.maSearchName.clear(); + + // Cache the result even if there was no match + // See tdf#32665 and tdf#147283 for an example where FreeSerif that has glyphs that exist + // in the bold font, but not in the bold+italic version where fontconfig suggest the bold + // font + applying a matrix to fake the missing italic. + for(;;) + { + if (!pFontInstance->GetFallbackForUnicode(cChar, rFontSelData.GetWeight(), + &rFontSelData.maSearchName, + &rFontSelData.mbEmbolden, + &rFontSelData.maItalicMatrix)) + { + pFontInstance->AddFallbackForUnicode(cChar, rFontSelData.GetWeight(), + rFontSelData.maSearchName, + rFontSelData.mbEmbolden, + rFontSelData.maItalicMatrix); + } + if( nStrIndex >= aOldMissingCodes.getLength() ) + break; + cChar = aOldMissingCodes.iterateCodePoints( &nStrIndex ); + } + if( !rFontSelData.maSearchName.isEmpty() ) + { + // remove cache entries that were still not resolved + for( nStrIndex = 0; nStrIndex < rMissingCodes.getLength(); ) + { + cChar = rMissingCodes.iterateCodePoints( &nStrIndex ); + pFontInstance->IgnoreFallbackForUnicode( cChar, rFontSelData.GetWeight(), rFontSelData.maSearchName ); + } + } + } + + // find the matching device font + if( !rFontSelData.maSearchName.isEmpty() ) + pFallbackData = FindFontFamily( rFontSelData.maSearchName ); + } + + // else find a matching font candidate for generic glyph fallback + if( !pFallbackData ) + { + // initialize font candidates for generic glyph fallback if needed + if( mnFallbackCount < 0 ) + ImplInitGenericGlyphFallback(); + + // TODO: adjust nFallbackLevel by number of levels resolved by the fallback hook + if( nFallbackLevel < mnFallbackCount ) + pFallbackData = (*mpFallbackList)[ nFallbackLevel ]; + } + + return pFallbackData; +} + +void PhysicalFontCollection::Add(PhysicalFontFace* pNewData) +{ + OUString aSearchName = GetEnglishSearchFontName( pNewData->GetFamilyName() ); + + PhysicalFontFamily* pFoundData = FindOrCreateFontFamily(aSearchName); + + pFoundData->AddFontFace( pNewData ); +} + +// find the font from the normalized font family name +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySearchName(const OUString& rSearchName) const +{ + // must be called with a normalized name. + assert( GetEnglishSearchFontName( rSearchName ) == rSearchName ); + + PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rSearchName ); + if( it == maPhysicalFontFamilies.end() ) + return nullptr; + + PhysicalFontFamily* pFoundData = (*it).second.get(); + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(std::u16string_view rFontName) const +{ + return ImplFindFontFamilyBySearchName( GetEnglishSearchFontName( rFontName ) ); +} + +PhysicalFontFamily *PhysicalFontCollection::FindOrCreateFontFamily(OUString const& rFamilyName) +{ + PhysicalFontFamilies::const_iterator it = maPhysicalFontFamilies.find( rFamilyName ); + PhysicalFontFamily* pFoundData = nullptr; + + if( it != maPhysicalFontFamilies.end() ) + pFoundData = (*it).second.get(); + + if( !pFoundData ) + { + pFoundData = new PhysicalFontFamily(rFamilyName); + maPhysicalFontFamilies[ rFamilyName ].reset(pFoundData); + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamilyByTokenNames(std::u16string_view rTokenStr) const +{ + PhysicalFontFamily* pFoundData = nullptr; + + // use normalized font name tokens to find the font + for( sal_Int32 nTokenPos = 0; nTokenPos != -1; ) + { + std::u16string_view aFamilyName = GetNextFontToken( rTokenStr, nTokenPos ); + if( aFamilyName.empty() ) + continue; + + pFoundData = FindFontFamily( aFamilyName ); + + if( pFoundData ) + break; + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyBySubstFontAttr(utl::FontNameAttr const& rFontAttr) const +{ + PhysicalFontFamily* pFoundData = nullptr; + + // use the font substitutions suggested by the FontNameAttr to find the font + for (auto const& substitution : rFontAttr.Substitutions) + { + pFoundData = FindFontFamily(substitution); + if( pFoundData ) + return pFoundData; + } + + // use known attributes from the configuration to find a matching substitute + const ImplFontAttrs nSearchType = rFontAttr.Type; + if( nSearchType != ImplFontAttrs::None ) + { + const FontWeight eSearchWeight = rFontAttr.Weight; + const FontWidth eSearchWidth = rFontAttr.Width; + const FontItalic eSearchSlant = ITALIC_DONTKNOW; + + pFoundData = FindFontFamilyByAttributes( nSearchType, + eSearchWeight, eSearchWidth, eSearchSlant, u"" ); + + if( pFoundData ) + return pFoundData; + } + + return nullptr; +} + +void PhysicalFontCollection::ImplInitMatchData() const +{ + // short circuit if already done + if( mbMatchData ) + return; + mbMatchData = true; + + if (utl::ConfigManager::IsFuzzing()) + return; + + // calculate MatchData for all entries + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + + for (auto const& family : maPhysicalFontFamilies) + { + const OUString& rSearchName = family.first; + PhysicalFontFamily* pEntry = family.second.get(); + + pEntry->InitMatchData( rFontSubst, rSearchName ); + } +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamilyByAttributes(ImplFontAttrs nSearchType, + FontWeight eSearchWeight, + FontWidth eSearchWidth, + FontItalic eSearchItalic, + std::u16string_view rSearchFamilyName ) const +{ + if( (eSearchItalic != ITALIC_NONE) && (eSearchItalic != ITALIC_DONTKNOW) ) + nSearchType |= ImplFontAttrs::Italic; + + // don't bother to match attributes if the attributes aren't worth matching + if( nSearchType == ImplFontAttrs::None + && ((eSearchWeight == WEIGHT_DONTKNOW) || (eSearchWeight == WEIGHT_NORMAL)) + && ((eSearchWidth == WIDTH_DONTKNOW) || (eSearchWidth == WIDTH_NORMAL)) ) + return nullptr; + + ImplInitMatchData(); + PhysicalFontFamily* pFoundData = nullptr; + + tools::Long nBestMatch = 40000; + ImplFontAttrs nBestType = ImplFontAttrs::None; + + for (auto const& family : maPhysicalFontFamilies) + { + PhysicalFontFamily* pData = family.second.get(); + + // Get all information about the matching font + ImplFontAttrs nMatchType = pData->GetMatchType(); + FontWeight eMatchWeight= pData->GetMatchWeight(); + FontWidth eMatchWidth = pData->GetMatchWidth(); + + // Calculate Match Value + // 1000000000 + // 100000000 + // 10000000 CJK, CTL, None-Latin, Symbol + // 1000000 FamilyName, Script, Fixed, -Special, -Decorative, + // Titling, Capitals, Outline, Shadow + // 100000 Match FamilyName, Serif, SansSerif, Italic, + // Width, Weight + // 10000 Scalable, Standard, Default, + // full, Normal, Knownfont, + // Otherstyle, +Special, +Decorative, + // 1000 Typewriter, Rounded, Gothic, Schollbook + // 100 + tools::Long nTestMatch = 0; + + // test CJK script attributes + if ( nSearchType & ImplFontAttrs::CJK ) + { + // if the matching font doesn't support any CJK languages, then + // it is not appropriate + if ( !(nMatchType & ImplFontAttrs::CJK_AllLang) ) + { + nTestMatch -= 10000000; + } + else + { + // Matching language + if ( (nSearchType & ImplFontAttrs::CJK_AllLang) + && (nMatchType & ImplFontAttrs::CJK_AllLang) ) + nTestMatch += 10000000*3; + if ( nMatchType & ImplFontAttrs::CJK ) + nTestMatch += 10000000*2; + if ( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + } + else if ( nMatchType & ImplFontAttrs::CJK ) + { + nTestMatch -= 10000000; + } + + // test CTL script attributes + if( nSearchType & ImplFontAttrs::CTL ) + { + if( nMatchType & ImplFontAttrs::CTL ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + else if ( nMatchType & ImplFontAttrs::CTL ) + { + nTestMatch -= 10000000; + } + + // test LATIN script attributes + if( nSearchType & ImplFontAttrs::NoneLatin ) + { + if( nMatchType & ImplFontAttrs::NoneLatin ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + + // test SYMBOL attributes + if ( nSearchType & ImplFontAttrs::Symbol ) + { + const OUString& rSearchName = family.first; + // prefer some special known symbol fonts + if ( rSearchName == "starsymbol" ) + { + nTestMatch += 10000000*6+(10000*3); + } + else if ( rSearchName == "opensymbol" ) + { + nTestMatch += 10000000*6; + } + else if ( rSearchName == "starbats" || + rSearchName == "wingdings" || + rSearchName == "monotypesorts" || + rSearchName == "dingbats" || + rSearchName == "zapfdingbats" ) + { + nTestMatch += 10000000*5; + } + else if (pData->GetTypeFaces() & FontTypeFaces::Symbol) + { + nTestMatch += 10000000*4; + } + else + { + if( nMatchType & ImplFontAttrs::Symbol ) + nTestMatch += 10000000*2; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000000; + } + } + else if ((pData->GetTypeFaces() & (FontTypeFaces::Symbol | FontTypeFaces::NoneSymbol)) == FontTypeFaces::Symbol) + { + nTestMatch -= 10000000; + } + else if ( nMatchType & ImplFontAttrs::Symbol ) + { + nTestMatch -= 10000; + } + + // match stripped family name + if( !rSearchFamilyName.empty() && (rSearchFamilyName == pData->GetMatchFamilyName()) ) + { + nTestMatch += 1000000*3; + } + + // match ALLSCRIPT? attribute + if( nSearchType & ImplFontAttrs::AllScript ) + { + if( nMatchType & ImplFontAttrs::AllScript ) + { + nTestMatch += 1000000*2; + } + if( nSearchType & ImplFontAttrs::AllSubscript ) + { + if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::AllSubscript) ) + nTestMatch += 1000000*2; + if( ImplFontAttrs::None != ((nSearchType ^ nMatchType) & ImplFontAttrs::BrushScript) ) + nTestMatch -= 1000000; + } + } + else if( nMatchType & ImplFontAttrs::AllScript ) + { + nTestMatch -= 1000000; + } + + // test MONOSPACE+TYPEWRITER attributes + if( nSearchType & ImplFontAttrs::Fixed ) + { + if( nMatchType & ImplFontAttrs::Fixed ) + nTestMatch += 1000000*2; + // a typewriter attribute is even better + if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Typewriter) ) + nTestMatch += 10000*2; + } + else if( nMatchType & ImplFontAttrs::Fixed ) + { + nTestMatch -= 1000000; + } + + // test SPECIAL attribute + if( nSearchType & ImplFontAttrs::Special ) + { + if( nMatchType & ImplFontAttrs::Special ) + { + nTestMatch += 10000; + } + else if( !(nSearchType & ImplFontAttrs::AllSerifStyle) ) + { + if( nMatchType & ImplFontAttrs::Serif ) + { + nTestMatch += 1000*2; + } + else if( nMatchType & ImplFontAttrs::SansSerif ) + { + nTestMatch += 1000; + } + } + } + else if( (nMatchType & ImplFontAttrs::Special) && !(nSearchType & ImplFontAttrs::Symbol) ) + { + nTestMatch -= 1000000; + } + + // test DECORATIVE attribute + if( nSearchType & ImplFontAttrs::Decorative ) + { + if( nMatchType & ImplFontAttrs::Decorative ) + { + nTestMatch += 10000; + } + else if( !(nSearchType & ImplFontAttrs::AllSerifStyle) ) + { + if( nMatchType & ImplFontAttrs::Serif ) + nTestMatch += 1000*2; + else if ( nMatchType & ImplFontAttrs::SansSerif ) + nTestMatch += 1000; + } + } + else if( nMatchType & ImplFontAttrs::Decorative ) + { + nTestMatch -= 1000000; + } + + // test TITLE+CAPITALS attributes + if( nSearchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) ) + { + if( nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) ) + { + nTestMatch += 1000000*2; + } + if( ImplFontAttrs::None == ((nSearchType^nMatchType) & ImplFontAttrs(ImplFontAttrs::Titling | ImplFontAttrs::Capitals))) + { + nTestMatch += 1000000; + } + else if( (nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals)) && + (nMatchType & (ImplFontAttrs::Standard | ImplFontAttrs::Default)) ) + { + nTestMatch += 1000000; + } + } + else if( nMatchType & (ImplFontAttrs::Titling | ImplFontAttrs::Capitals) ) + { + nTestMatch -= 1000000; + } + + // test OUTLINE+SHADOW attributes + if( nSearchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) ) + { + if( nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) ) + { + nTestMatch += 1000000*2; + } + if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs(ImplFontAttrs::Outline | ImplFontAttrs::Shadow)) ) + { + nTestMatch += 1000000; + } + else if( (nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow)) && + (nMatchType & (ImplFontAttrs::Standard | ImplFontAttrs::Default)) ) + { + nTestMatch += 1000000; + } + } + else if ( nMatchType & (ImplFontAttrs::Outline | ImplFontAttrs::Shadow) ) + { + nTestMatch -= 1000000; + } + + // test font name substrings + // TODO: calculate name matching score using e.g. Levenstein distance + if( (rSearchFamilyName.size() >= 4) && + (pData->GetMatchFamilyName().getLength() >= 4) && + ((rSearchFamilyName.find( pData->GetMatchFamilyName() ) != std::u16string_view::npos) || + (pData->GetMatchFamilyName().indexOf( rSearchFamilyName ) != -1)) ) + { + nTestMatch += 5000; + } + // test SERIF attribute + if( nSearchType & ImplFontAttrs::Serif ) + { + if( nMatchType & ImplFontAttrs::Serif ) + nTestMatch += 1000000*2; + else if( nMatchType & ImplFontAttrs::SansSerif ) + nTestMatch -= 1000000; + } + + // test SANSERIF attribute + if( nSearchType & ImplFontAttrs::SansSerif ) + { + if( nMatchType & ImplFontAttrs::SansSerif ) + nTestMatch += 1000000; + else if ( nMatchType & ImplFontAttrs::Serif ) + nTestMatch -= 1000000; + } + + // test ITALIC attribute + if( nSearchType & ImplFontAttrs::Italic ) + { + if (pData->GetTypeFaces() & FontTypeFaces::Italic) + nTestMatch += 1000000*3; + if( nMatchType & ImplFontAttrs::Italic ) + nTestMatch += 1000000; + } + else if (!(nSearchType & ImplFontAttrs::AllScript) + && ((nMatchType & ImplFontAttrs::Italic) + || !(pData->GetTypeFaces() & FontTypeFaces::NoneItalic))) + { + nTestMatch -= 1000000*2; + } + + // test WIDTH attribute + if( (eSearchWidth != WIDTH_DONTKNOW) && (eSearchWidth != WIDTH_NORMAL) ) + { + if( eSearchWidth < WIDTH_NORMAL ) + { + if( eSearchWidth == eMatchWidth ) + nTestMatch += 1000000*3; + else if( (eMatchWidth < WIDTH_NORMAL) && (eMatchWidth != WIDTH_DONTKNOW) ) + nTestMatch += 1000000; + } + else + { + if( eSearchWidth == eMatchWidth ) + nTestMatch += 1000000*3; + else if( eMatchWidth > WIDTH_NORMAL ) + nTestMatch += 1000000; + } + } + else if( (eMatchWidth != WIDTH_DONTKNOW) && (eMatchWidth != WIDTH_NORMAL) ) + { + nTestMatch -= 1000000; + } + + // test WEIGHT attribute + if( (eSearchWeight != WEIGHT_DONTKNOW) && + (eSearchWeight != WEIGHT_NORMAL) && + (eSearchWeight != WEIGHT_MEDIUM) ) + { + if( eSearchWeight < WEIGHT_NORMAL ) + { + if (pData->GetTypeFaces() & FontTypeFaces::Light) + nTestMatch += 1000000; + if( (eMatchWeight < WEIGHT_NORMAL) && (eMatchWeight != WEIGHT_DONTKNOW) ) + nTestMatch += 1000000; + } + else + { + if (pData->GetTypeFaces() & FontTypeFaces::Bold) + nTestMatch += 1000000; + if( eMatchWeight > WEIGHT_BOLD ) + nTestMatch += 1000000; + } + } + else if (((eMatchWeight != WEIGHT_DONTKNOW) + && (eMatchWeight != WEIGHT_NORMAL) + && (eMatchWeight != WEIGHT_MEDIUM)) + || !(pData->GetTypeFaces() & FontTypeFaces::Normal)) + { + nTestMatch -= 1000000; + } + + // prefer scalable fonts + if (pData->GetTypeFaces() & FontTypeFaces::Scalable) + nTestMatch += 10000*4; + else + nTestMatch -= 10000*4; + + // test STANDARD+DEFAULT+FULL+NORMAL attributes + if( nMatchType & ImplFontAttrs::Standard ) + nTestMatch += 10000*2; + if( nMatchType & ImplFontAttrs::Default ) + nTestMatch += 10000; + if( nMatchType & ImplFontAttrs::Full ) + nTestMatch += 10000; + if( nMatchType & ImplFontAttrs::Normal ) + nTestMatch += 10000; + + // test OTHERSTYLE attribute + if( ((nSearchType ^ nMatchType) & ImplFontAttrs::OtherStyle) != ImplFontAttrs::None ) + { + nTestMatch -= 10000; + } + + // test ROUNDED attribute + if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Rounded) ) + nTestMatch += 1000; + + // test TYPEWRITER attribute + if( ImplFontAttrs::None == ((nSearchType ^ nMatchType) & ImplFontAttrs::Typewriter) ) + nTestMatch += 1000; + + // test GOTHIC attribute + if( nSearchType & ImplFontAttrs::Gothic ) + { + if( nMatchType & ImplFontAttrs::Gothic ) + nTestMatch += 1000*3; + if( nMatchType & ImplFontAttrs::SansSerif ) + nTestMatch += 1000*2; + } + + // test SCHOOLBOOK attribute + if( nSearchType & ImplFontAttrs::Schoolbook ) + { + if( nMatchType & ImplFontAttrs::Schoolbook ) + nTestMatch += 1000*3; + if( nMatchType & ImplFontAttrs::Serif ) + nTestMatch += 1000*2; + } + + // compare with best matching font yet + if ( nTestMatch > nBestMatch ) + { + pFoundData = pData; + nBestMatch = nTestMatch; + nBestType = nMatchType; + } + else if( nTestMatch == nBestMatch ) + { + // some fonts are more suitable defaults + if( nMatchType & ImplFontAttrs::Default ) + { + pFoundData = pData; + nBestType = nMatchType; + } + else if( (nMatchType & ImplFontAttrs::Standard) && + !(nBestType & ImplFontAttrs::Default) ) + { + pFoundData = pData; + nBestType = nMatchType; + } + } + } + + return pFoundData; +} + +PhysicalFontFamily* PhysicalFontCollection::ImplFindFontFamilyOfDefaultFont() const +{ + // try to find one of the default fonts of the + // UNICODE, SANSSERIF, SERIF or FIXED default font lists + PhysicalFontFamily* pFoundData = nullptr; + if (!utl::ConfigManager::IsFuzzing()) + { + const utl::DefaultFontConfiguration& rDefaults = utl::DefaultFontConfiguration::get(); + LanguageTag aLanguageTag("en"); + OUString aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SANS_UNICODE ); + pFoundData = FindFontFamilyByTokenNames( aFontname ); + + if( pFoundData ) + return pFoundData; + + aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SANS ); + pFoundData = FindFontFamilyByTokenNames( aFontname ); + if( pFoundData ) + return pFoundData; + + aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::SERIF ); + pFoundData = FindFontFamilyByTokenNames( aFontname ); + if( pFoundData ) + return pFoundData; + + aFontname = rDefaults.getDefaultFont( aLanguageTag, DefaultFontType::FIXED ); + pFoundData = FindFontFamilyByTokenNames( aFontname ); + if( pFoundData ) + return pFoundData; + } + + // now try to find a reasonable non-symbol font + + ImplInitMatchData(); + + for (auto const& family : maPhysicalFontFamilies) + { + PhysicalFontFamily* pData = family.second.get(); + if( pData->GetMatchType() & ImplFontAttrs::Symbol ) + continue; + + pFoundData = pData; + if( pData->GetMatchType() & (ImplFontAttrs::Default|ImplFontAttrs::Standard) ) + break; + } + if( pFoundData ) + return pFoundData; + + // finding any font is better than finding no font at all + auto it = maPhysicalFontFamilies.begin(); + if( it != maPhysicalFontFamilies.end() ) + pFoundData = (*it).second.get(); + + return pFoundData; +} + +std::shared_ptr<PhysicalFontCollection> PhysicalFontCollection::Clone() const +{ + auto xClonedCollection = std::make_shared<PhysicalFontCollection>(); + xClonedCollection->mpPreMatchHook = mpPreMatchHook; + xClonedCollection->mpFallbackHook = mpFallbackHook; + + // TODO: clone the config-font attributes too? + xClonedCollection->mbMatchData = false; + + for (auto const& family : maPhysicalFontFamilies) + { + const PhysicalFontFamily* pFontFace = family.second.get(); + pFontFace->UpdateCloneFontList(*xClonedCollection); + } + + return xClonedCollection; +} + +std::unique_ptr<PhysicalFontFaceCollection> PhysicalFontCollection::GetFontFaceCollection() const +{ + std::unique_ptr<PhysicalFontFaceCollection> pDeviceFontList(new PhysicalFontFaceCollection); + + for (auto const& family : maPhysicalFontFamilies) + { + const PhysicalFontFamily* pFontFamily = family.second.get(); + pFontFamily->UpdateDevFontList( *pDeviceFontList ); + } + + return pDeviceFontList; +} + +// These are the metric-compatible replacement fonts that are bundled with +// LibreOffice, we prefer them over generic substitutions that might be +// provided by the system. +const std::vector<std::pair<OUString, OUString>> aMetricCompatibleMap = +{ + { "Times New Roman", "Liberation Serif" }, + { "Arial", "Liberation Sans" }, + { "Arial Narrow", "Liberation Sans Narrow" }, + { "Courier New", "Liberation Mono" }, + { "Cambria", "Caladea" }, + { "Calibri", "Carlito" }, +}; + +static bool FindMetricCompatibleFont(FontSelectPattern& rFontSelData) +{ + for (const auto& aSub : aMetricCompatibleMap) + { + if (rFontSelData.maSearchName == GetEnglishSearchFontName(aSub.first)) + { + rFontSelData.maSearchName = aSub.second; + return true; + } + } + + return false; +} + +PhysicalFontFamily* PhysicalFontCollection::FindFontFamily(FontSelectPattern& rFSD) const +{ + // give up if no fonts are available + if( !Count() ) + return nullptr; + + static bool noFontLookup = getenv("SAL_NO_FONT_LOOKUP") != nullptr; + if (noFontLookup) + { + // Hard code the use of Liberation Sans and skip font search. + sal_Int32 nIndex = 0; + rFSD.maTargetName = GetNextFontToken(rFSD.GetFamilyName(), nIndex); + rFSD.maSearchName = "liberationsans"; + PhysicalFontFamily* pFont = ImplFindFontFamilyBySearchName(rFSD.maSearchName); + assert(pFont); + return pFont; + } + + bool bMultiToken = false; + sal_Int32 nTokenPos = 0; + OUString& aSearchName = rFSD.maSearchName; // TODO: get rid of reference + for(;;) + { + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = rFSD.maTargetName; + + // Until features are properly supported, they are appended to the + // font name, so we need to strip them off so the font is found. + sal_Int32 nFeat = aSearchName.indexOf(FontSelectPattern::FEAT_PREFIX); + OUString aOrigName = rFSD.maTargetName; + OUString aBaseFontName = aSearchName.copy( 0, (nFeat != -1) ? nFeat : aSearchName.getLength() ); + + if (nFeat != -1) + { + aSearchName = aBaseFontName; + rFSD.maTargetName = aBaseFontName; + } + + aSearchName = GetEnglishSearchFontName( aSearchName ); + ImplFontSubstitute(aSearchName); + // #114999# special emboldening for Ricoh fonts + // TODO: smarter check for special cases by using PreMatch infrastructure? + if( (rFSD.GetWeight() > WEIGHT_MEDIUM) && + aSearchName.startsWithIgnoreAsciiCase( "hg" ) ) + { + OUString aBoldName; + if( aSearchName.startsWithIgnoreAsciiCase( "hggothicb" ) ) + aBoldName = "hggothice"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgpgothicb" ) ) + aBoldName = "hgpgothice"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgminchol" ) ) + aBoldName = "hgminchob"; + else if( aSearchName.startsWithIgnoreAsciiCase( "hgpminchol" ) ) + aBoldName = "hgpminchob"; + else if( aSearchName.equalsIgnoreAsciiCase( "hgminchob" ) ) + aBoldName = "hgminchoe"; + else if( aSearchName.equalsIgnoreAsciiCase( "hgpminchob" ) ) + aBoldName = "hgpminchoe"; + + if( !aBoldName.isEmpty() && ImplFindFontFamilyBySearchName( aBoldName ) ) + { + // the other font is available => use it + aSearchName = aBoldName; + // prevent synthetic emboldening of bold version + rFSD.SetWeight(WEIGHT_DONTKNOW); + } + } + + // restore the features to make the font selection data unique + rFSD.maTargetName = aOrigName; + + // check if the current font name token or its substitute is valid + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + + // some systems provide special customization + // e.g. they suggest "serif" as UI-font, but this name cannot be used directly + // because the system wants to map it to another font first, e.g. "Helvetica" + + // use the target name to search in the prematch hook + rFSD.maTargetName = aBaseFontName; + + // Related: fdo#49271 RTF files often contain weird-ass + // Win 3.1/Win95 style fontnames which attempt to put the + // charset encoding into the filename + // http://www.webcenter.ru/~kazarn/eng/fonts_ttf.htm + OUString sStrippedName = StripScriptFromName(rFSD.maTargetName); + if (sStrippedName != rFSD.maTargetName) + { + rFSD.maTargetName = sStrippedName; + aSearchName = GetEnglishSearchFontName(rFSD.maTargetName); + pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + } + + if (FindMetricCompatibleFont(rFSD) || + (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD))) + { + aSearchName = GetEnglishSearchFontName(aSearchName); + } + + // the prematch hook uses the target name to search, but we now need + // to restore the features to make the font selection data unique + rFSD.maTargetName = aOrigName; + + pFoundData = ImplFindFontFamilyBySearchName( aSearchName ); + if( pFoundData ) + return pFoundData; + + // break after last font name token was checked unsuccessfully + if( nTokenPos == -1) + break; + bMultiToken = true; + } + + // if the first font was not available find the next available font in + // the semicolon separated list of font names. A font is also considered + // available when there is a matching entry in the Tools->Options->Fonts + // dialog with neither ALWAYS nor SCREENONLY flags set and the substitution + // font is available + for( nTokenPos = 0; nTokenPos != -1; ) + { + if( bMultiToken ) + { + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = GetEnglishSearchFontName( rFSD.maTargetName ); + } + else + nTokenPos = -1; + if (FindMetricCompatibleFont(rFSD) || + (mpPreMatchHook && mpPreMatchHook->FindFontSubstitute(rFSD))) + { + aSearchName = GetEnglishSearchFontName( aSearchName ); + } + ImplFontSubstitute(aSearchName); + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchName); + if( pFoundData ) + return pFoundData; + } + + // if no font with a directly matching name is available use the + // first font name token and get its attributes to find a replacement + if ( bMultiToken ) + { + nTokenPos = 0; + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + aSearchName = GetEnglishSearchFontName( rFSD.maTargetName ); + } + + OUString aSearchShortName; + OUString aSearchFamilyName; + FontWeight eSearchWeight = rFSD.GetWeight(); + FontWidth eSearchWidth = rFSD.GetWidthType(); + ImplFontAttrs nSearchType = ImplFontAttrs::None; + utl::FontSubstConfiguration::getMapName( aSearchName, aSearchShortName, aSearchFamilyName, + eSearchWeight, eSearchWidth, nSearchType ); + + // note: the search name was already translated to english (if possible) + // use the font's shortened name if needed + if ( aSearchShortName != aSearchName ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aSearchShortName); + if( pFoundData ) + { +#ifdef UNX + /* #96738# don't use mincho as a replacement for "MS Mincho" on X11: Mincho is + a korean bitmap font that is not suitable here. Use the font replacement table, + that automatically leads to the desired "HG Mincho Light J". Same story for + MS Gothic, there are thai and korean "Gothic" fonts, so we even prefer Andale */ + if ((aSearchName != "msmincho") && (aSearchName != "msgothic")) + // TODO: add heuristic to only throw out the fake ms* fonts +#endif + { + return pFoundData; + } + } + } + + // use font fallback + const utl::FontNameAttr* pFontAttr = nullptr; + if (!aSearchName.isEmpty() && !utl::ConfigManager::IsFuzzing()) + { + // get fallback info using FontSubstConfiguration and + // the target name, it's shortened name and family name in that order + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + pFontAttr = rFontSubst.getSubstInfo( aSearchName ); + if ( !pFontAttr && (aSearchShortName != aSearchName) ) + pFontAttr = rFontSubst.getSubstInfo( aSearchShortName ); + if ( !pFontAttr && (aSearchFamilyName != aSearchShortName) ) + pFontAttr = rFontSubst.getSubstInfo( aSearchFamilyName ); + + // try the font substitutions suggested by the fallback info + if( pFontAttr ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySubstFontAttr(*pFontAttr); + if( pFoundData ) + return pFoundData; + } + } + + // if a target symbol font is not available use a default symbol font + if( rFSD.IsMicrosoftSymbolEncoded() ) + { + LanguageTag aDefaultLanguageTag("en"); + if (utl::ConfigManager::IsFuzzing()) + aSearchName = "OpenSymbol"; + else + aSearchName = utl::DefaultFontConfiguration::get().getDefaultFont( aDefaultLanguageTag, DefaultFontType::SYMBOL ); + PhysicalFontFamily* pFoundData = FindFontFamilyByTokenNames(aSearchName); + if( pFoundData ) + return pFoundData; + } + + // now try the other font name tokens + while( nTokenPos != -1 ) + { + rFSD.maTargetName = GetNextFontToken( rFSD.GetFamilyName(), nTokenPos ); + if( rFSD.maTargetName.isEmpty() ) + continue; + + aSearchName = GetEnglishSearchFontName( rFSD.maTargetName ); + + OUString aTempShortName; + OUString aTempFamilyName; + ImplFontAttrs nTempType = ImplFontAttrs::None; + FontWeight eTempWeight = rFSD.GetWeight(); + FontWidth eTempWidth = WIDTH_DONTKNOW; + utl::FontSubstConfiguration::getMapName( aSearchName, aTempShortName, aTempFamilyName, + eTempWeight, eTempWidth, nTempType ); + + // use a shortened token name if available + if( aTempShortName != aSearchName ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySearchName(aTempShortName); + if( pFoundData ) + return pFoundData; + } + + const utl::FontNameAttr* pTempFontAttr = nullptr; + if (!utl::ConfigManager::IsFuzzing()) + { + // use a font name from font fallback list to determine font attributes + // get fallback info using FontSubstConfiguration and + // the target name, it's shortened name and family name in that order + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + pTempFontAttr = rFontSubst.getSubstInfo( aSearchName ); + + if ( !pTempFontAttr && (aTempShortName != aSearchName) ) + pTempFontAttr = rFontSubst.getSubstInfo( aTempShortName ); + + if ( !pTempFontAttr && (aTempFamilyName != aTempShortName) ) + pTempFontAttr = rFontSubst.getSubstInfo( aTempFamilyName ); + } + + // try the font substitutions suggested by the fallback info + if( pTempFontAttr ) + { + PhysicalFontFamily* pFoundData = ImplFindFontFamilyBySubstFontAttr(*pTempFontAttr); + if( pFoundData ) + return pFoundData; + if( !pFontAttr ) + pFontAttr = pTempFontAttr; + } + } + + // if still needed use the font request's attributes to find a good match + if (MsLangId::isSimplifiedChinese(rFSD.meLanguage)) + nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_SC; + else if (MsLangId::isTraditionalChinese(rFSD.meLanguage)) + nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_TC; + else if (MsLangId::isKorean(rFSD.meLanguage)) + nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_KR; + else if (rFSD.meLanguage == LANGUAGE_JAPANESE) + nSearchType |= ImplFontAttrs::CJK | ImplFontAttrs::CJK_JP; + else + { + nSearchType |= lcl_IsCJKFont( rFSD.GetFamilyName() ); + if( rFSD.IsMicrosoftSymbolEncoded() ) + nSearchType |= ImplFontAttrs::Symbol; + } + + PhysicalFontFamily::CalcType(nSearchType, eSearchWeight, eSearchWidth, rFSD.GetFamilyType(), pFontAttr); + PhysicalFontFamily* pFoundData = FindFontFamilyByAttributes(nSearchType, + eSearchWeight, eSearchWidth, rFSD.GetItalic(), aSearchFamilyName); + + if( pFoundData ) + { + // overwrite font selection attributes using info from the typeface flags + if ((eSearchWeight >= WEIGHT_BOLD) + && (eSearchWeight > rFSD.GetWeight()) + && (pFoundData->GetTypeFaces() & FontTypeFaces::Bold)) + { + rFSD.SetWeight( eSearchWeight ); + } + else if ((eSearchWeight < WEIGHT_NORMAL) + && (eSearchWeight < rFSD.GetWeight()) + && (eSearchWeight != WEIGHT_DONTKNOW) + && (pFoundData->GetTypeFaces() & FontTypeFaces::Light)) + { + rFSD.SetWeight( eSearchWeight ); + } + + if ((nSearchType & ImplFontAttrs::Italic) + && ((rFSD.GetItalic() == ITALIC_DONTKNOW) + || (rFSD.GetItalic() == ITALIC_NONE)) + && (pFoundData->GetTypeFaces() & FontTypeFaces::Italic)) + { + rFSD.SetItalic( ITALIC_NORMAL ); + } + } + else + { + // if still needed fall back to default fonts + pFoundData = ImplFindFontFamilyOfDefaultFont(); + } + + return pFoundData; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/PhysicalFontFace.cxx b/vcl/source/font/PhysicalFontFace.cxx new file mode 100644 index 0000000000..aa9a9327f7 --- /dev/null +++ b/vcl/source/font/PhysicalFontFace.cxx @@ -0,0 +1,510 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/types.h> +#include <tools/fontenum.hxx> +#include <unotools/fontdefs.hxx> +#include <osl/file.hxx> +#include <osl/thread.h> + +#include <fontattributes.hxx> +#include <impfontcharmap.hxx> +#include <sft.hxx> +#include <salgdi.hxx> + +#include <font/FontSelectPattern.hxx> +#include <font/PhysicalFontFace.hxx> +#include <o3tl/string_view.hxx> + +#include <string_view> + +#include <hb-ot.h> + +namespace vcl::font +{ +PhysicalFontFace::PhysicalFontFace(const FontAttributes& rDFA) + : FontAttributes(rDFA) + , mpHbFace(nullptr) + , mpHbUnscaledFont(nullptr) +{ +} + +PhysicalFontFace::~PhysicalFontFace() +{ + if (mpHbFace) + hb_face_destroy(mpHbFace); + if (mpHbUnscaledFont) + hb_font_destroy(mpHbUnscaledFont); +} + +sal_Int32 PhysicalFontFace::CompareIgnoreSize(const PhysicalFontFace& rOther) const +{ + // compare their width, weight, italic, style name and family name + if (GetWidthType() < rOther.GetWidthType()) + return -1; + else if (GetWidthType() > rOther.GetWidthType()) + return 1; + + if (GetWeight() < rOther.GetWeight()) + return -1; + else if (GetWeight() > rOther.GetWeight()) + return 1; + + if (GetItalic() < rOther.GetItalic()) + return -1; + else if (GetItalic() > rOther.GetItalic()) + return 1; + + sal_Int32 nRet = GetFamilyName().compareTo(rOther.GetFamilyName()); + + if (nRet == 0) + { + nRet = GetStyleName().compareTo(rOther.GetStyleName()); + } + + return nRet; +} + +static int FamilyNameMatchValue(FontSelectPattern const& rFSP, std::u16string_view sFontFamily) +{ + const OUString& rFontName = rFSP.maTargetName; + + if (rFontName.equalsIgnoreAsciiCase(sFontFamily)) + return 240000; + + return 0; +} + +static int StyleNameMatchValue(FontMatchStatus const& rStatus, std::u16string_view rStyle) +{ + if (rStatus.mpTargetStyleName + && o3tl::equalsIgnoreAsciiCase(rStyle, *rStatus.mpTargetStyleName)) + return 120000; + + return 0; +} + +static int PitchMatchValue(FontSelectPattern const& rFSP, FontPitch ePitch) +{ + if ((rFSP.GetPitch() != PITCH_DONTKNOW) && (rFSP.GetPitch() == ePitch)) + return 20000; + + return 0; +} + +static int PreferNormalFontWidthMatchValue(FontWidth eWidthType) +{ + // TODO: change when the upper layers can tell their width preference + if (eWidthType == WIDTH_NORMAL) + return 400; + else if ((eWidthType == WIDTH_SEMI_EXPANDED) || (eWidthType == WIDTH_SEMI_CONDENSED)) + return 300; + + return 0; +} + +static int WeightMatchValue(FontSelectPattern const& rFSP, FontWeight eWeight) +{ + int nMatch = 0; + + if (rFSP.GetWeight() != WEIGHT_DONTKNOW) + { + // if not bold or requiring emboldening prefer light fonts to bold fonts + FontWeight ePatternWeight = rFSP.mbEmbolden ? WEIGHT_NORMAL : rFSP.GetWeight(); + + int nReqWeight = static_cast<int>(ePatternWeight); + if (ePatternWeight > WEIGHT_MEDIUM) + nReqWeight += 100; + + int nGivenWeight = static_cast<int>(eWeight); + if (eWeight > WEIGHT_MEDIUM) + nGivenWeight += 100; + + int nWeightDiff = nReqWeight - nGivenWeight; + + if (nWeightDiff == 0) + nMatch += 1000; + else if (nWeightDiff == +1 || nWeightDiff == -1) + nMatch += 700; + else if (nWeightDiff < +50 && nWeightDiff > -50) + nMatch += 200; + } + else + { + // prefer NORMAL font weight + // TODO: change when the upper layers can tell their weight preference + if (eWeight == WEIGHT_NORMAL) + nMatch += 450; + else if (eWeight == WEIGHT_MEDIUM) + nMatch += 350; + else if ((eWeight == WEIGHT_SEMILIGHT) || (eWeight == WEIGHT_SEMIBOLD)) + nMatch += 200; + else if (eWeight == WEIGHT_LIGHT) + nMatch += 150; + } + + return nMatch; +} + +static int ItalicMatchValue(FontSelectPattern const& rFSP, FontItalic eItalic) +{ + // if requiring custom matrix to fake italic, prefer upright font + FontItalic ePatternItalic + = rFSP.maItalicMatrix != ItalicMatrix() ? ITALIC_NONE : rFSP.GetItalic(); + + if (ePatternItalic == ITALIC_NONE) + { + if (eItalic == ITALIC_NONE) + return 900; + } + else + { + if (ePatternItalic == eItalic) + return 900; + else if (eItalic != ITALIC_NONE) + return 600; + } + + return 0; +} + +bool PhysicalFontFace::IsBetterMatch(const FontSelectPattern& rFSP, FontMatchStatus& rStatus) const +{ + int nMatch = FamilyNameMatchValue(rFSP, GetFamilyName()); + nMatch += StyleNameMatchValue(rStatus, GetStyleName()); + nMatch += PitchMatchValue(rFSP, GetPitch()); + nMatch += PreferNormalFontWidthMatchValue(GetWidthType()); + nMatch += WeightMatchValue(rFSP, GetWeight()); + nMatch += ItalicMatchValue(rFSP, GetItalic()); + + if (rFSP.mnOrientation != 0_deg10) + nMatch += 80; + else if (rFSP.mnWidth != 0) + nMatch += 25; + else + nMatch += 5; + + if (rStatus.mnFaceMatch > nMatch) + { + return false; + } + else if (rStatus.mnFaceMatch < nMatch) + { + rStatus.mnFaceMatch = nMatch; + return true; + } + + return true; +} + +RawFontData PhysicalFontFace::GetRawFontData(uint32_t nTag) const +{ + auto pHbFace = GetHbFace(); + // If nTag is 0, reference the whole font. + if (!nTag) + return RawFontData(hb_face_reference_blob(pHbFace)); + return RawFontData(hb_face_reference_table(pHbFace, nTag)); +} + +static hb_blob_t* getTable(hb_face_t*, hb_tag_t nTag, void* pUserData) +{ + return static_cast<const PhysicalFontFace*>(pUserData)->GetHbTable(nTag); +} + +hb_face_t* PhysicalFontFace::GetHbFace() const +{ + if (mpHbFace == nullptr) + mpHbFace + = hb_face_create_for_tables(getTable, const_cast<PhysicalFontFace*>(this), nullptr); + return mpHbFace; +} + +hb_font_t* PhysicalFontFace::GetHbUnscaledFont() const +{ + if (mpHbUnscaledFont == nullptr) + mpHbUnscaledFont = hb_font_create(GetHbFace()); + return mpHbUnscaledFont; +} + +FontCharMapRef PhysicalFontFace::GetFontCharMap() const +{ + if (mxCharMap.is()) + return mxCharMap; + + // Check if this font is using symbol cmap subtable, most likely redundant + // since HarfBuzz handles mapping symbol fonts for us. + RawFontData aData(GetRawFontData(HB_TAG('c', 'm', 'a', 'p'))); + bool bSymbol = HasMicrosoftSymbolCmap(aData.data(), aData.size()); + + hb_face_t* pHbFace = GetHbFace(); + hb_set_t* pUnicodes = hb_set_create(); + hb_face_collect_unicodes(pHbFace, pUnicodes); + + if (hb_set_get_population(pUnicodes)) + { + // Convert HarfBuzz set to code ranges. + std::vector<sal_UCS4> aRangeCodes; + hb_codepoint_t nFirst, nLast = HB_SET_VALUE_INVALID; + while (hb_set_next_range(pUnicodes, &nFirst, &nLast)) + { + aRangeCodes.push_back(nFirst); + aRangeCodes.push_back(nLast + 1); + } + + mxCharMap = new FontCharMap(bSymbol, std::move(aRangeCodes)); + } + + hb_set_destroy(pUnicodes); + + if (!mxCharMap.is()) + mxCharMap = FontCharMap::GetDefaultMap(IsMicrosoftSymbolEncoded()); + + return mxCharMap; +} + +bool PhysicalFontFace::GetFontCapabilities(vcl::FontCapabilities& rFontCapabilities) const +{ + if (!mxFontCapabilities) + { + mxFontCapabilities.emplace(); + RawFontData aData(GetRawFontData(HB_TAG('O', 'S', '/', '2'))); + getTTCoverage(mxFontCapabilities->oUnicodeRange, mxFontCapabilities->oCodePageRange, + aData.data(), aData.size()); + } + + rFontCapabilities = *mxFontCapabilities; + return rFontCapabilities.oUnicodeRange || rFontCapabilities.oCodePageRange; +} + +namespace +{ +class RawFace +{ +public: + RawFace(hb_face_t* pFace) + : mpFace(hb_face_reference(pFace)) + { + } + + RawFace(const RawFace& rOther) + : mpFace(hb_face_reference(rOther.mpFace)) + { + } + + ~RawFace() { hb_face_destroy(mpFace); } + + RawFontData GetTable(uint32_t nTag) const + { + return RawFontData(hb_face_reference_table(mpFace, nTag)); + } + +private: + hb_face_t* mpFace; +}; + +class TrueTypeFace final : public AbstractTrueTypeFont +{ + const RawFace m_aFace; + mutable std::array<RawFontData, NUM_TAGS> m_aTableList; + + const RawFontData& table(sal_uInt32 nIdx) const + { + assert(nIdx < NUM_TAGS); + static const uint32_t aTags[NUM_TAGS] = { + T_maxp, T_glyf, T_head, T_loca, T_name, T_hhea, T_hmtx, T_cmap, + T_vhea, T_vmtx, T_OS2, T_post, T_cvt, T_prep, T_fpgm, T_CFF, + }; + if (m_aTableList[nIdx].empty()) + m_aTableList[nIdx] = std::move(m_aFace.GetTable(aTags[nIdx])); + return m_aTableList[nIdx]; + } + +public: + TrueTypeFace(RawFace aFace, const FontCharMapRef rCharMap) + : AbstractTrueTypeFont(nullptr, rCharMap) + , m_aFace(std::move(aFace)) + { + } + + bool hasTable(sal_uInt32 nIdx) const override { return !table(nIdx).empty(); } + const sal_uInt8* table(sal_uInt32 nIdx, sal_uInt32& nSize) const override + { + auto& rTable = table(nIdx); + nSize = rTable.size(); + return rTable.data(); + } +}; +} + +bool PhysicalFontFace::CreateFontSubset(std::vector<sal_uInt8>& rOutBuffer, + const sal_GlyphId* pGlyphIds, const sal_uInt8* pEncoding, + const int nGlyphCount, FontSubsetInfo& rInfo) const +{ + // Prepare data for font subsetter. + TrueTypeFace aSftFont(RawFace(GetHbFace()), GetFontCharMap()); + if (aSftFont.initialize() != SFErrCodes::Ok) + return false; + + // write subset into destination file + return CreateTTFfontSubset(aSftFont, rOutBuffer, pGlyphIds, pEncoding, nGlyphCount, rInfo); +} + +bool PhysicalFontFace::HasColorLayers() const +{ + const auto pHbFace = GetHbFace(); + return hb_ot_color_has_layers(pHbFace) && hb_ot_color_has_palettes(pHbFace); +} + +const std::vector<ColorPalette>& PhysicalFontFace::GetColorPalettes() const +{ + if (!mxColorPalettes) + { + mxColorPalettes.emplace(); + const auto pHbFace = GetHbFace(); + auto nPalettes = hb_ot_color_palette_get_count(pHbFace); + mxColorPalettes->reserve(nPalettes); + for (auto nPalette = 0u; nPalette < nPalettes; nPalette++) + { + auto nColors = hb_ot_color_palette_get_colors(pHbFace, nPalette, 0, nullptr, nullptr); + ColorPalette aPalette(nColors); + for (auto nColor = 0u; nColor < nColors; nColor++) + { + uint32_t nCount = 1; + hb_color_t aColor; + hb_ot_color_palette_get_colors(pHbFace, nPalette, nColor, &nCount, &aColor); + auto a = hb_color_get_alpha(aColor); + auto r = hb_color_get_red(aColor); + auto g = hb_color_get_green(aColor); + auto b = hb_color_get_blue(aColor); + aPalette[nColor] = Color(ColorAlphaTag::ColorAlpha, a, r, g, b); + } + mxColorPalettes->push_back(aPalette); + } + } + + return *mxColorPalettes; +} + +std::vector<ColorLayer> PhysicalFontFace::GetGlyphColorLayers(sal_GlyphId nGlyphIndex) const +{ + if (!HasColorLayers()) + return {}; + + const auto pHbFace = GetHbFace(); + + auto nLayers = hb_ot_color_glyph_get_layers(pHbFace, nGlyphIndex, 0, nullptr, nullptr); + std::vector<ColorLayer> aLayers(nLayers); + for (auto nLayer = 0u; nLayer < nLayers; nLayer++) + { + hb_ot_color_layer_t aLayer; + uint32_t nCount = 1; + hb_ot_color_glyph_get_layers(pHbFace, nGlyphIndex, nLayer, &nCount, &aLayer); + aLayers[nLayer] = { aLayer.glyph, aLayer.color_index }; + } + + return aLayers; +} + +bool PhysicalFontFace::HasColorBitmaps() const { return hb_ot_color_has_png(GetHbFace()); } + +RawFontData PhysicalFontFace::GetGlyphColorBitmap(sal_GlyphId nGlyphIndex, + tools::Rectangle& rRect) const +{ + if (!HasColorBitmaps()) + return {}; + + hb_font_t* pHbFont = GetHbUnscaledFont(); + auto aData = RawFontData(hb_ot_color_glyph_reference_png(pHbFont, nGlyphIndex)); + if (!aData.empty()) + { + hb_glyph_extents_t aExtents; + if (hb_font_get_glyph_extents(pHbFont, nGlyphIndex, &aExtents)) + { + auto aPoint = Point(aExtents.x_bearing, aExtents.y_bearing + aExtents.height); + auto aSize = Size(aExtents.width, -aExtents.height); + rRect = tools::Rectangle(aPoint, aSize); + } + } + + return aData; +} + +OString PhysicalFontFace::GetGlyphName(sal_GlyphId nGlyphIndex, bool bValidate) const +{ + char aBuffer[256]; + hb_font_glyph_to_string(GetHbUnscaledFont(), nGlyphIndex, aBuffer, 256); + if (bValidate) + { + // https://learn.microsoft.com/en-us/typography/opentype/spec/post#version-20 + // Valid characters are limited to A–Z, a–z, 0–9, “.” (FULL STOP), and “_” (LOW LINE). + const char* p = aBuffer; + while ((*p >= '0' && *p <= '9') || (*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') + || *p == '.' || *p == '_') + ++p; + if (*p != '\0') + return "g" + OString::number(nGlyphIndex); + } + + return OString(aBuffer); +} + +OUString PhysicalFontFace::GetName(NameID aNameID, const LanguageTag& rLanguageTag) const +{ + auto pHbFace = GetHbFace(); + + auto aHbLang = HB_LANGUAGE_INVALID; + if (rLanguageTag.getLanguageType() != LANGUAGE_NONE) + { + auto aLanguage(rLanguageTag.getBcp47().toUtf8()); + aHbLang = hb_language_from_string(aLanguage.getStr(), aLanguage.getLength()); + } + + auto nName = hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, nullptr, nullptr); + if (!nName && aHbLang == HB_LANGUAGE_INVALID) + { + // Fallback to English if localized name is missing. + aHbLang = hb_language_from_string("en", 2); + nName = hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, nullptr, nullptr); + } + + OUString sName; + if (nName) + { + std::vector<uint16_t> aBuf(++nName); // make space for terminating NUL. + hb_ot_name_get_utf16(pHbFace, aNameID, aHbLang, &nName, aBuf.data()); + sName = OUString(reinterpret_cast<sal_Unicode*>(aBuf.data()), nName); + } + + return sName; +} + +const std::vector<hb_variation_t>& PhysicalFontFace::GetVariations(const LogicalFontInstance&) const +{ + if (!mxVariations) + { + SAL_WARN("vcl.fonts", "Getting font variations is not supported."); + mxVariations.emplace(); + } + return *mxVariations; +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ diff --git a/vcl/source/font/PhysicalFontFamily.cxx b/vcl/source/font/PhysicalFontFamily.cxx new file mode 100644 index 0000000000..6956394a59 --- /dev/null +++ b/vcl/source/font/PhysicalFontFamily.cxx @@ -0,0 +1,269 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <rtl/ustring.hxx> +#include <unotools/fontdefs.hxx> + +#include <font/PhysicalFontFaceCollection.hxx> +#include <font/PhysicalFontCollection.hxx> +#include <utility> + +namespace vcl::font +{ + +void PhysicalFontFamily::CalcType( ImplFontAttrs& rType, FontWeight& rWeight, FontWidth& rWidth, + FontFamily eFamily, const utl::FontNameAttr* pFontAttr ) +{ + if ( eFamily != FAMILY_DONTKNOW ) + { + if ( eFamily == FAMILY_SWISS ) + rType |= ImplFontAttrs::SansSerif; + else if ( eFamily == FAMILY_ROMAN ) + rType |= ImplFontAttrs::Serif; + else if ( eFamily == FAMILY_SCRIPT ) + rType |= ImplFontAttrs::Script; + else if ( eFamily == FAMILY_MODERN ) + rType |= ImplFontAttrs::Fixed; + else if ( eFamily == FAMILY_DECORATIVE ) + rType |= ImplFontAttrs::Decorative; + } + + if ( pFontAttr ) + { + rType |= pFontAttr->Type; + + if ( ((rWeight == WEIGHT_DONTKNOW) || (rWeight == WEIGHT_NORMAL)) && + (pFontAttr->Weight != WEIGHT_DONTKNOW) ) + rWeight = pFontAttr->Weight; + if ( ((rWidth == WIDTH_DONTKNOW) || (rWidth == WIDTH_NORMAL)) && + (pFontAttr->Width != WIDTH_DONTKNOW) ) + rWidth = pFontAttr->Width; + } +} + +static ImplFontAttrs lcl_IsCJKFont( std::u16string_view rFontName ) +{ + // Test, if Fontname includes CJK characters --> In this case we + // mention that it is a CJK font + for(size_t i = 0; i < rFontName.size(); i++) + { + const sal_Unicode ch = rFontName[i]; + // japanese + if ( ((ch >= 0x3040) && (ch <= 0x30FF)) || + ((ch >= 0x3190) && (ch <= 0x319F)) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_JP; + + // korean + if ( ((ch >= 0xAC00) && (ch <= 0xD7AF)) || + ((ch >= 0xA960) && (ch <= 0xA97F)) || + ((ch >= 0xD7B0) && (ch <= 0xD7FF)) || + ((ch >= 0x3130) && (ch <= 0x318F)) || + ((ch >= 0x1100) && (ch <= 0x11FF)) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_KR; + + // chinese + if ( (ch >= 0x3400) && (ch <= 0x9FFF) ) + return ImplFontAttrs::CJK|ImplFontAttrs::CJK_TC|ImplFontAttrs::CJK_SC; + + // cjk + if ( ((ch >= 0x3000) && (ch <= 0xD7AF)) || + ((ch >= 0xFF00) && (ch <= 0xFFEE)) ) + return ImplFontAttrs::CJK; + + } + + return ImplFontAttrs::None; +} + +PhysicalFontFamily::PhysicalFontFamily( OUString aSearchName ) +: maSearchName(std::move( aSearchName )), + mnTypeFaces( FontTypeFaces::NONE ), + meFamily( FAMILY_DONTKNOW ), + mePitch( PITCH_DONTKNOW ), + mnMinQuality( -1 ), + mnMatchType( ImplFontAttrs::None ), + meMatchWeight( WEIGHT_DONTKNOW ), + meMatchWidth( WIDTH_DONTKNOW ) +{} + +PhysicalFontFamily::~PhysicalFontFamily() +{ +} + +void PhysicalFontFamily::AddFontFace( PhysicalFontFace* pNewFontFace ) +{ + if( maFontFaces.empty() ) + { + maFamilyName = pNewFontFace->GetFamilyName(); + meFamily = pNewFontFace->GetFamilyType(); + mePitch = pNewFontFace->GetPitch(); + mnMinQuality = pNewFontFace->GetQuality(); + } + else + { + if( meFamily == FAMILY_DONTKNOW ) + meFamily = pNewFontFace->GetFamilyType(); + if( mePitch == PITCH_DONTKNOW ) + mePitch = pNewFontFace->GetPitch(); + if( mnMinQuality > pNewFontFace->GetQuality() ) + mnMinQuality = pNewFontFace->GetQuality(); + } + + // set attributes for attribute based font matching + mnTypeFaces |= FontTypeFaces::Scalable; + + if( pNewFontFace->IsMicrosoftSymbolEncoded() ) + mnTypeFaces |= FontTypeFaces::Symbol; + else + mnTypeFaces |= FontTypeFaces::NoneSymbol; + + if( pNewFontFace->GetWeight() != WEIGHT_DONTKNOW ) + { + if( pNewFontFace->GetWeight() >= WEIGHT_SEMIBOLD ) + mnTypeFaces |= FontTypeFaces::Bold; + else if( pNewFontFace->GetWeight() <= WEIGHT_SEMILIGHT ) + mnTypeFaces |= FontTypeFaces::Light; + else + mnTypeFaces |= FontTypeFaces::Normal; + } + + if( pNewFontFace->GetItalic() == ITALIC_NONE ) + mnTypeFaces |= FontTypeFaces::NoneItalic; + else if( (pNewFontFace->GetItalic() == ITALIC_NORMAL) + || (pNewFontFace->GetItalic() == ITALIC_OBLIQUE) ) + mnTypeFaces |= FontTypeFaces::Italic; + + // reassign name (sharing saves memory) + if( pNewFontFace->GetFamilyName() == GetFamilyName() ) + pNewFontFace->SetFamilyName( GetFamilyName() ); + + // add the new physical font face, replacing existing font face if necessary + // TODO: get rid of linear search? + auto it(maFontFaces.begin()); + for (; it != maFontFaces.end(); ++it) + { + PhysicalFontFace* pFoundFontFace = it->get(); + sal_Int32 eComp = pNewFontFace->CompareIgnoreSize( *pFoundFontFace ); + if( eComp > 0 ) + continue; + if( eComp < 0 ) + break; + + // ignore duplicate if its quality is worse + if( pNewFontFace->GetQuality() < pFoundFontFace->GetQuality() ) + return; + + // keep the device font if its quality is good enough + if( pNewFontFace->GetQuality() == pFoundFontFace->GetQuality() ) + return; + + // replace existing font face with a better one + *it = pNewFontFace; // insert at sort position + return; + } + + maFontFaces.emplace(it, pNewFontFace); // insert at sort position +} + +// get font attributes using the normalized font family name +void PhysicalFontFamily::InitMatchData( const utl::FontSubstConfiguration& rFontSubst, + const OUString& rSearchName ) +{ + OUString aShortName; + OUString aMatchFamilyName(maMatchFamilyName); + // get font attributes from the decorated font name + utl::FontSubstConfiguration::getMapName( rSearchName, aShortName, aMatchFamilyName, + meMatchWeight, meMatchWidth, mnMatchType ); + maMatchFamilyName = aMatchFamilyName; + const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( rSearchName ); + // eventually use the stripped name + if( !pFontAttr ) + if( aShortName != rSearchName ) + pFontAttr = rFontSubst.getSubstInfo( aShortName ); + CalcType( mnMatchType, meMatchWeight, meMatchWidth, meFamily, pFontAttr ); + mnMatchType |= lcl_IsCJKFont( maFamilyName ); +} + +PhysicalFontFace* PhysicalFontFamily::FindBestFontFace( const vcl::font::FontSelectPattern& rFSD ) const +{ + if( maFontFaces.empty() ) + return nullptr; + if( maFontFaces.size() == 1) + return maFontFaces[0].get(); + + // FontName+StyleName should map to FamilyName+StyleName + const OUString& rSearchName = rFSD.maTargetName; + OUString aTargetStyleName; + const OUString* pTargetStyleName = nullptr; + if((rSearchName.getLength() > maSearchName.getLength()) + && rSearchName.startsWith( maSearchName ) ) + { + aTargetStyleName = rSearchName.copy(maSearchName.getLength() + 1); + pTargetStyleName = &aTargetStyleName; + } + + // TODO: linear search improve! + PhysicalFontFace* pBestFontFace = maFontFaces[0].get(); + FontMatchStatus aFontMatchStatus = {0, pTargetStyleName}; + for (auto const& font : maFontFaces) + { + PhysicalFontFace* pFoundFontFace = font.get(); + if( pFoundFontFace->IsBetterMatch( rFSD, aFontMatchStatus ) ) + pBestFontFace = pFoundFontFace; + } + + return pBestFontFace; +} + +// update device font list with unique font faces, with uniqueness +// meaning different font attributes, but not different fonts sizes +void PhysicalFontFamily::UpdateDevFontList( vcl::font::PhysicalFontFaceCollection& rDevFontList ) const +{ + PhysicalFontFace* pPrevFace = nullptr; + for (auto const& font : maFontFaces) + { + PhysicalFontFace* pFoundFontFace = font.get(); + if( !pPrevFace || pFoundFontFace->CompareIgnoreSize( *pPrevFace ) ) + rDevFontList.Add( pFoundFontFace ); + pPrevFace = pFoundFontFace; + } +} + +void PhysicalFontFamily::UpdateCloneFontList(vcl::font::PhysicalFontCollection& rFontCollection) const +{ + OUString aFamilyName = GetEnglishSearchFontName( GetFamilyName() ); + PhysicalFontFamily* pFamily(nullptr); + + for (auto const& font : maFontFaces) + { + PhysicalFontFace *pFoundFontFace = font.get(); + + if (!pFamily) + { // tdf#98989 lazy create as family without faces won't work + pFamily = rFontCollection.FindOrCreateFontFamily(aFamilyName); + } + assert(pFamily); + pFamily->AddFontFace( pFoundFontFace ); + } +} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/font.cxx b/vcl/source/font/font.cxx new file mode 100644 index 0000000000..6dfee423a9 --- /dev/null +++ b/vcl/source/font/font.cxx @@ -0,0 +1,1185 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <tools/stream.hxx> +#include <tools/vcompat.hxx> +#include <tools/gen.hxx> +#include <unotools/configmgr.hxx> +#include <unotools/fontcfg.hxx> +#include <unotools/fontdefs.hxx> +#include <o3tl/hash_combine.hxx> +#include <i18nlangtag/mslangid.hxx> + +#include <vcl/font.hxx> +#include <vcl/svapp.hxx> +#include <vcl/outdev.hxx> +#include <vcl/virdev.hxx> + +#include <impfont.hxx> +#include <fontattributes.hxx> +#include <fontsubset.hxx> +#include <sft.hxx> + +#include <algorithm> +#include <string_view> + +#include <vcl/TypeSerializer.hxx> + +#ifdef _WIN32 +#include <vcl/metric.hxx> +#endif + +using namespace vcl; + +namespace +{ + Font::ImplType& GetGlobalDefault() + { + static Font::ImplType gDefault; + return gDefault; + } +} + +Font::Font() : mpImplFont(GetGlobalDefault()) +{ +} + +Font::Font( const vcl::Font& rFont ) : mpImplFont( rFont.mpImplFont ) +{ +} + +Font::Font( vcl::Font&& rFont ) noexcept : mpImplFont( std::move(rFont.mpImplFont) ) +{ +} + +Font::Font( const OUString& rFamilyName, const Size& rSize ) +{ + if (GetFamilyName() != rFamilyName + || GetAverageFontSize() != rSize) + { + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::Font( const OUString& rFamilyName, const OUString& rStyleName, const Size& rSize ) +{ + if (GetFamilyName() != rFamilyName + || GetStyleName() != rStyleName + || GetAverageFontSize() != rSize) + { + mpImplFont->SetFamilyName( rFamilyName ); + mpImplFont->SetStyleName( rStyleName ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::Font( FontFamily eFamily, const Size& rSize ) +{ + if (GetFontFamily() != eFamily + || GetAverageFontSize() != rSize) + { + mpImplFont->SetFamilyType( eFamily ); + mpImplFont->SetFontSize( rSize ); + } +} + +Font::~Font() +{ +} + +void Font::SetColor( const Color& rColor ) +{ + if (GetColor() != rColor) + { + mpImplFont->maColor = rColor; + } +} + +void Font::SetFillColor( const Color& rColor ) +{ + if (GetFillColor() != rColor) + { + mpImplFont->maFillColor = rColor; + if ( rColor.IsTransparent() ) + mpImplFont->mbTransparent = true; + } +} + +void Font::SetTransparent( bool bTransparent ) +{ + if (IsTransparent() != bTransparent) + mpImplFont->mbTransparent = bTransparent; +} + +void Font::SetAlignment( TextAlign eAlign ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meAlign != eAlign) + mpImplFont->SetAlignment(eAlign); +} + +void Font::SetFamilyName( const OUString& rFamilyName ) +{ + if (GetFamilyName() != rFamilyName) + mpImplFont->SetFamilyName( rFamilyName ); +} + +void Font::SetStyleName( const OUString& rStyleName ) +{ + if (GetStyleName() != rStyleName) + mpImplFont->maStyleName = rStyleName; +} + +void Font::SetFontSize( const Size& rSize ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetFontSize() != rSize) + mpImplFont->SetFontSize( rSize ); +} + +void Font::SetFamily( FontFamily eFamily ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetFamilyTypeNoAsk() != eFamily) + mpImplFont->SetFamilyType( eFamily ); +} + +void Font::SetCharSet( rtl_TextEncoding eCharSet ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetCharSet() != eCharSet) + mpImplFont->SetCharSet( eCharSet ); +} + +void Font::SetLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (GetLanguageTag() != rLanguageTag) + mpImplFont->maLanguageTag = rLanguageTag; +} + +void Font::SetCJKContextLanguageTag( const LanguageTag& rLanguageTag ) +{ + if (GetCJKContextLanguageTag() != rLanguageTag) + mpImplFont->maCJKLanguageTag = rLanguageTag; +} + +void Font::SetLanguage( LanguageType eLanguage ) +{ + if (GetLanguage() != eLanguage) + mpImplFont->maLanguageTag.reset( eLanguage); +} + +void Font::SetCJKContextLanguage( LanguageType eLanguage ) +{ + if (GetCJKContextLanguage() != eLanguage) + mpImplFont->maCJKLanguageTag.reset( eLanguage); +} + +void Font::SetPitch( FontPitch ePitch ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetPitchNoAsk() != ePitch) + mpImplFont->SetPitch( ePitch ); +} + +void Font::SetOrientation( Degree10 nOrientation ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mnOrientation != nOrientation) + mpImplFont->mnOrientation = nOrientation; +} + +void Font::SetVertical( bool bVertical ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mbVertical != bVertical) + mpImplFont->mbVertical = bVertical; +} + +void Font::SetKerning( FontKerning eKerning ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meKerning != eKerning) + mpImplFont->meKerning = eKerning; +} + +bool Font::IsKerning() const +{ + return mpImplFont->meKerning != FontKerning::NONE; +} + +void Font::SetFixKerning( short nSpacing ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mnSpacing != nSpacing) + mpImplFont->mnSpacing = nSpacing; +} + +short Font::GetFixKerning() const +{ + return mpImplFont->mnSpacing; +} + +bool Font::IsFixKerning() const +{ + return mpImplFont->mnSpacing != 0; +} + +void Font::SetWeight( FontWeight eWeight ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetWeightNoAsk() != eWeight) + mpImplFont->SetWeight( eWeight ); +} + +void Font::SetWidthType( FontWidth eWidth ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetWidthTypeNoAsk() != eWidth) + mpImplFont->SetWidthType( eWidth ); +} + +void Font::SetItalic( FontItalic eItalic ) +{ + if (const_cast<const ImplType&>(mpImplFont)->GetItalicNoAsk() != eItalic) + mpImplFont->SetItalic( eItalic ); +} + +void Font::SetOutline( bool bOutline ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mbOutline != bOutline) + mpImplFont->mbOutline = bOutline; +} + +void Font::SetShadow( bool bShadow ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mbShadow != bShadow) + mpImplFont->mbShadow = bShadow; +} + +void Font::SetUnderline( FontLineStyle eUnderline ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meUnderline != eUnderline) + mpImplFont->meUnderline = eUnderline; +} + +void Font::SetOverline( FontLineStyle eOverline ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meOverline != eOverline) + mpImplFont->meOverline = eOverline; +} + +void Font::SetStrikeout( FontStrikeout eStrikeout ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meStrikeout != eStrikeout) + mpImplFont->meStrikeout = eStrikeout; +} + +void Font::SetRelief( FontRelief eRelief ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meRelief != eRelief) + mpImplFont->meRelief = eRelief; +} + +void Font::SetEmphasisMark( FontEmphasisMark eEmphasisMark ) +{ + if (const_cast<const ImplType&>(mpImplFont)->meEmphasisMark != eEmphasisMark ) + mpImplFont->meEmphasisMark = eEmphasisMark; +} + +void Font::SetWordLineMode( bool bWordLine ) +{ + if (const_cast<const ImplType&>(mpImplFont)->mbWordLine != bWordLine) + mpImplFont->mbWordLine = bWordLine; +} + +Font& Font::operator=( const vcl::Font& rFont ) +{ + mpImplFont = rFont.mpImplFont; + return *this; +} + +Font& Font::operator=( vcl::Font&& rFont ) noexcept +{ + mpImplFont = std::move(rFont.mpImplFont); + return *this; +} + +FontEmphasisMark Font::GetEmphasisMarkStyle() const +{ + FontEmphasisMark nEmphasisMark = GetEmphasisMark(); + + // If no Position is set, then calculate the default position, which + // depends on the language + if (!(nEmphasisMark & (FontEmphasisMark::PosAbove | FontEmphasisMark::PosBelow))) + { + LanguageType eLang = GetLanguage(); + // In Chinese Simplified the EmphasisMarks are below/left + if (MsLangId::isSimplifiedChinese(eLang)) + { + nEmphasisMark |= FontEmphasisMark::PosBelow; + } + else + { + eLang = GetCJKContextLanguage(); + + // In Chinese Simplified the EmphasisMarks are below/left + if (MsLangId::isSimplifiedChinese(eLang)) + nEmphasisMark |= FontEmphasisMark::PosBelow; + else + nEmphasisMark |= FontEmphasisMark::PosAbove; + } + } + + return nEmphasisMark; +} + +bool Font::operator==( const vcl::Font& rFont ) const +{ + return mpImplFont == rFont.mpImplFont; +} + +bool Font::EqualIgnoreColor( const vcl::Font& rFont ) const +{ + return mpImplFont->EqualIgnoreColor( *rFont.mpImplFont ); +} + +size_t Font::GetHashValueIgnoreColor() const +{ + return mpImplFont->GetHashValueIgnoreColor(); +} + +void Font::Merge( const vcl::Font& rFont ) +{ + if ( !rFont.GetFamilyName().isEmpty() ) + { + SetFamilyName( rFont.GetFamilyName() ); + SetStyleName( rFont.GetStyleName() ); + SetCharSet( GetCharSet() ); + SetLanguageTag( rFont.GetLanguageTag() ); + SetCJKContextLanguageTag( rFont.GetCJKContextLanguageTag() ); + // don't use access methods here, might lead to AskConfig(), if DONTKNOW + SetFamily( rFont.mpImplFont->GetFamilyTypeNoAsk() ); + SetPitch( rFont.mpImplFont->GetPitchNoAsk() ); + } + + // don't use access methods here, might lead to AskConfig(), if DONTKNOW + if ( rFont.mpImplFont->GetWeightNoAsk() != WEIGHT_DONTKNOW ) + SetWeight( rFont.GetWeight() ); + if ( rFont.mpImplFont->GetItalicNoAsk() != ITALIC_DONTKNOW ) + SetItalic( rFont.GetItalic() ); + if ( rFont.mpImplFont->GetWidthTypeNoAsk() != WIDTH_DONTKNOW ) + SetWidthType( rFont.GetWidthType() ); + + if ( rFont.GetFontSize().Height() ) + SetFontSize( rFont.GetFontSize() ); + if ( rFont.GetUnderline() != LINESTYLE_DONTKNOW ) + { + SetUnderline( rFont.GetUnderline() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + if ( rFont.GetOverline() != LINESTYLE_DONTKNOW ) + { + SetOverline( rFont.GetOverline() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + if ( rFont.GetStrikeout() != STRIKEOUT_DONTKNOW ) + { + SetStrikeout( rFont.GetStrikeout() ); + SetWordLineMode( rFont.IsWordLineMode() ); + } + + // Defaults? + SetOrientation( rFont.GetOrientation() ); + SetVertical( rFont.IsVertical() ); + SetEmphasisMark( rFont.GetEmphasisMark() ); + SetKerning( rFont.IsKerning() ? FontKerning::FontSpecific : FontKerning::NONE ); + SetOutline( rFont.IsOutline() ); + SetShadow( rFont.IsShadow() ); + SetRelief( rFont.GetRelief() ); +} + +void Font::GetFontAttributes( FontAttributes& rAttrs ) const +{ + rAttrs.SetFamilyName( mpImplFont->GetFamilyName() ); + rAttrs.SetStyleName( mpImplFont->maStyleName ); + rAttrs.SetFamilyType( mpImplFont->GetFamilyTypeNoAsk() ); + rAttrs.SetPitch( mpImplFont->GetPitchNoAsk() ); + rAttrs.SetItalic( mpImplFont->GetItalicNoAsk() ); + rAttrs.SetWeight( mpImplFont->GetWeightNoAsk() ); + rAttrs.SetWidthType( WIDTH_DONTKNOW ); + rAttrs.SetMicrosoftSymbolEncoded( mpImplFont->GetCharSet() == RTL_TEXTENCODING_SYMBOL ); +} + +// tdf#127471 for corrections on EMF/WMF we need the AvgFontWidth in Windows-specific notation +tools::Long Font::GetOrCalculateAverageFontWidth() const +{ + if(0 == mpImplFont->GetCalculatedAverageFontWidth()) + { + // VirtualDevice is not thread safe + SolarMutexGuard aGuard; + + // create unscaled copy of font (this), a VirtualDevice and set it there + vcl::Font aUnscaledFont(*this); + ScopedVclPtr<VirtualDevice> pTempVirtualDevice(VclPtr<VirtualDevice>::Create()); + aUnscaledFont.SetAverageFontWidth(0); + pTempVirtualDevice->SetFont(aUnscaledFont); + +#ifdef _WIN32 + // on Windows systems use FontMetric to get/create AverageFontWidth from system + const FontMetric aMetric(pTempVirtualDevice->GetFontMetric()); + const_cast<Font*>(this)->mpImplFont->SetCalculatedAverageFontWidth(aMetric.GetAverageFontWidth()); +#else + // On non-Windows systems we need to calculate AvgFontWidth + // as close as possible (discussion see documentation in task), + // so calculate it. For discussion of method used, see task + // buffer measure string creation, will always use the same + static constexpr OUString aMeasureString + = u"\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027" + "\u0028\u0029\u002A\u002B\u002C\u002D\u002E\u002F" + "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037" + "\u0038\u0039\u003A\u003B\u003C\u003D\u003E\u003F" + "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047" + "\u0048\u0049\u004A\u004B\u004C\u004D\u004E\u004F" + "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057" + "\u0058\u0059\u005A\u005B\u005C\u005D\u005E\u005F" + "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067" + "\u0068\u0069\u006A\u006B\u006C\u006D\u006E\u006F" + "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077" + "\u0078\u0079\u007A\u007B\u007C\u007D\u007E"_ustr; + + const double fAverageFontWidth( + pTempVirtualDevice->GetTextWidth(aMeasureString) / + static_cast<double>(aMeasureString.getLength())); + const_cast<Font*>(this)->mpImplFont->SetCalculatedAverageFontWidth(basegfx::fround(fAverageFontWidth)); +#endif + } + + return mpImplFont->GetCalculatedAverageFontWidth(); +} + +SvStream& ReadImplFont( SvStream& rIStm, ImplFont& rImplFont, tools::Long& rnNormedFontScaling ) +{ + VersionCompatRead aCompat( rIStm ); + sal_uInt16 nTmp16(0); + sal_Int16 nTmps16(0); + bool bTmp(false); + sal_uInt8 nTmp8(0); + + rImplFont.SetFamilyName( rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet()) ); + rImplFont.maStyleName = rIStm.ReadUniOrByteString(rIStm.GetStreamCharSet()); + TypeSerializer aSerializer(rIStm); + aSerializer.readSize(rImplFont.maAverageFontSize); + + static const bool bFuzzing = utl::ConfigManager::IsFuzzing(); + if (bFuzzing) + { + if (rImplFont.maAverageFontSize.Width() > 8192) + { + SAL_WARN("vcl.gdi", "suspicious average width of: " << rImplFont.maAverageFontSize.Width()); + rImplFont.maAverageFontSize.setWidth(8192); + } + if (rImplFont.maAverageFontSize.Height() > 8192) + { + SAL_WARN("vcl.gdi", "suspicious average height of: " << rImplFont.maAverageFontSize.Height()); + rImplFont.maAverageFontSize.setHeight(8192); + } + } + + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetCharSet( static_cast<rtl_TextEncoding>(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetFamilyType( static_cast<FontFamily>(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetPitch( static_cast<FontPitch>(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetWeight( static_cast<FontWeight>(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meUnderline = static_cast<FontLineStyle>(nTmp16); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meStrikeout = static_cast<FontStrikeout>(nTmp16); + rIStm.ReadUInt16( nTmp16 ); rImplFont.SetItalic( static_cast<FontItalic>(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.maLanguageTag.reset( LanguageType(nTmp16) ); + rIStm.ReadUInt16( nTmp16 ); rImplFont.meWidthType = static_cast<FontWidth>(nTmp16); + + rIStm.ReadInt16( nTmps16 ); rImplFont.mnOrientation = Degree10(nTmps16); + + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbWordLine = bTmp; + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbOutline = bTmp; + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbShadow = bTmp; + rIStm.ReadUChar( nTmp8 ); rImplFont.meKerning = static_cast<FontKerning>(nTmp8); + + if( aCompat.GetVersion() >= 2 ) + { + rIStm.ReadUChar( nTmp8 ); rImplFont.meRelief = static_cast<FontRelief>(nTmp8); + rIStm.ReadUInt16( nTmp16 ); rImplFont.maCJKLanguageTag.reset( LanguageType(nTmp16) ); + rIStm.ReadCharAsBool( bTmp ); rImplFont.mbVertical = bTmp; + rIStm.ReadUInt16( nTmp16 ); + rImplFont.meEmphasisMark = static_cast<FontEmphasisMark>(nTmp16 & o3tl::typed_flags<FontEmphasisMark>::mask); + } + + if( aCompat.GetVersion() >= 3 ) + { + rIStm.ReadUInt16( nTmp16 ); rImplFont.meOverline = static_cast<FontLineStyle>(nTmp16); + } + + // tdf#127471 read NormedFontScaling + if( aCompat.GetVersion() >= 4 ) + { + sal_Int32 nNormedFontScaling(0); + rIStm.ReadInt32(nNormedFontScaling); + rnNormedFontScaling = nNormedFontScaling; + } + + if( aCompat.GetVersion() >= 5 ) + { + rIStm.ReadInt16( nTmps16 ); + rImplFont.mnSpacing = nTmps16; + } + + // Relief + // CJKContextLanguage + + return rIStm; +} + +SvStream& WriteImplFont( SvStream& rOStm, const ImplFont& rImplFont, tools::Long nNormedFontScaling ) +{ + // tdf#127471 increase to version 4 + // tdf#66819 increase to version 5 + VersionCompatWrite aCompat( rOStm, 5 ); + + TypeSerializer aSerializer(rOStm); + rOStm.WriteUniOrByteString( rImplFont.GetFamilyName(), rOStm.GetStreamCharSet() ); + rOStm.WriteUniOrByteString( rImplFont.GetStyleName(), rOStm.GetStreamCharSet() ); + aSerializer.writeSize(rImplFont.maAverageFontSize); + + rOStm.WriteUInt16( GetStoreCharSet( rImplFont.GetCharSet() ) ); + rOStm.WriteUInt16( rImplFont.GetFamilyTypeNoAsk() ); + rOStm.WriteUInt16( rImplFont.GetPitchNoAsk() ); + rOStm.WriteUInt16( rImplFont.GetWeightNoAsk() ); + rOStm.WriteUInt16( rImplFont.meUnderline ); + rOStm.WriteUInt16( rImplFont.meStrikeout ); + rOStm.WriteUInt16( rImplFont.GetItalicNoAsk() ); + rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.maLanguageTag.getLanguageType( false)) ); + rOStm.WriteUInt16( rImplFont.GetWidthTypeNoAsk() ); + + rOStm.WriteInt16( rImplFont.mnOrientation.get() ); + + rOStm.WriteBool( rImplFont.mbWordLine ); + rOStm.WriteBool( rImplFont.mbOutline ); + rOStm.WriteBool( rImplFont.mbShadow ); + rOStm.WriteUChar( static_cast<sal_uInt8>(rImplFont.meKerning) ); + + // new in version 2 + rOStm.WriteUChar( static_cast<unsigned char>(rImplFont.meRelief) ); + rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.maCJKLanguageTag.getLanguageType( false)) ); + rOStm.WriteBool( rImplFont.mbVertical ); + rOStm.WriteUInt16( static_cast<sal_uInt16>(rImplFont.meEmphasisMark) ); + + // new in version 3 + rOStm.WriteUInt16( rImplFont.meOverline ); + + // new in version 4, NormedFontScaling + rOStm.WriteInt32(nNormedFontScaling); + + // new in version 5 + rOStm.WriteInt16( rImplFont.mnSpacing ); + return rOStm; +} + +SvStream& ReadFont( SvStream& rIStm, vcl::Font& rFont ) +{ + // tdf#127471 try to read NormedFontScaling + tools::Long nNormedFontScaling(0); + SvStream& rRetval(ReadImplFont( rIStm, *rFont.mpImplFont, nNormedFontScaling )); + + if (nNormedFontScaling > 0) + { +#ifdef _WIN32 + // we run on windows and a NormedFontScaling was written + if(rFont.GetFontSize().getWidth() == nNormedFontScaling) + { + // the writing producer was running on a non-windows system, adapt to needed windows + // system-specific pre-multiply + const tools::Long nHeight(std::max<tools::Long>(rFont.GetFontSize().getHeight(), 0)); + sal_uInt32 nScaledWidth(0); + + if(nHeight > 0) + { + vcl::Font aUnscaledFont(rFont); + aUnscaledFont.SetAverageFontWidth(0); + const FontMetric aUnscaledFontMetric(Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont)); + + if (nHeight > 0) + { + const double fScaleFactor(static_cast<double>(nNormedFontScaling) / static_cast<double>(nHeight)); + nScaledWidth = basegfx::fround(static_cast<double>(aUnscaledFontMetric.GetAverageFontWidth()) * fScaleFactor); + } + } + + rFont.SetAverageFontWidth(nScaledWidth); + } + else + { + // the writing producer was on a windows system, correct pre-multiplied value + // is already set, nothing to do. Ignore 2nd value. Here a check + // could be done if adapting the 2nd, NormedFontScaling value would be similar to + // the set value for plausibility reasons + } +#else + // we do not run on windows and a NormedFontScaling was written + if(rFont.GetFontSize().getWidth() == nNormedFontScaling) + { + // the writing producer was not on a windows system, correct value + // already set, nothing to do + } + else + { + // the writing producer was on a windows system, correct FontScaling. + // The correct non-pre-multiplied value is the 2nd one, use it + rFont.SetAverageFontWidth(nNormedFontScaling); + } +#endif + } + + return rRetval; +} + +SvStream& WriteFont( SvStream& rOStm, const vcl::Font& rFont ) +{ + // tdf#127471 prepare NormedFontScaling for additional export + tools::Long nNormedFontScaling(rFont.GetFontSize().getWidth()); + + // FontScaling usage at vcl-Font is detected by checking that FontWidth != 0 + if (nNormedFontScaling > 0) + { + const tools::Long nHeight(std::max<tools::Long>(rFont.GetFontSize().getHeight(), 0)); + + // check for negative height + if(0 == nHeight) + { + nNormedFontScaling = 0; + } + else + { +#ifdef _WIN32 + // for WIN32 the value is pre-multiplied with AverageFontWidth + // which makes it system-dependent. Turn that back to have the + // normed non-windows form of it for export as 2nd value + vcl::Font aUnscaledFont(rFont); + aUnscaledFont.SetAverageFontWidth(0); + const FontMetric aUnscaledFontMetric( + Application::GetDefaultDevice()->GetFontMetric(aUnscaledFont)); + + if (aUnscaledFontMetric.GetAverageFontWidth() > 0) + { + const double fScaleFactor( + static_cast<double>(nNormedFontScaling) + / static_cast<double>(aUnscaledFontMetric.GetAverageFontWidth())); + nNormedFontScaling = static_cast<tools::Long>(fScaleFactor * nHeight); + } +#endif + } + } + + return WriteImplFont( rOStm, *rFont.mpImplFont, nNormedFontScaling ); +} + +namespace +{ + bool identifyTrueTypeFont( const void* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult ) + { + bool bResult = false; + TrueTypeFont* pTTF = nullptr; + if( OpenTTFontBuffer( i_pBuffer, i_nSize, 0, &pTTF ) == SFErrCodes::Ok ) + { + TTGlobalFontInfo aInfo; + GetTTGlobalFontInfo( pTTF, &aInfo ); + // most importantly: the family name + if( !aInfo.ufamily.isEmpty() ) + o_rResult.SetFamilyName( aInfo.ufamily ); + else if( !aInfo.family.isEmpty() ) + o_rResult.SetFamilyName( OStringToOUString( aInfo.family, RTL_TEXTENCODING_ASCII_US ) ); + // set weight + if( aInfo.weight ) + { + if( aInfo.weight < FW_EXTRALIGHT ) + o_rResult.SetWeight( WEIGHT_THIN ); + else if( aInfo.weight < FW_LIGHT ) + o_rResult.SetWeight( WEIGHT_ULTRALIGHT ); + else if( aInfo.weight < FW_NORMAL ) + o_rResult.SetWeight( WEIGHT_LIGHT ); + else if( aInfo.weight < FW_MEDIUM ) + o_rResult.SetWeight( WEIGHT_NORMAL ); + else if( aInfo.weight < FW_SEMIBOLD ) + o_rResult.SetWeight( WEIGHT_MEDIUM ); + else if( aInfo.weight < FW_BOLD ) + o_rResult.SetWeight( WEIGHT_SEMIBOLD ); + else if( aInfo.weight < FW_EXTRABOLD ) + o_rResult.SetWeight( WEIGHT_BOLD ); + else if( aInfo.weight < FW_BLACK ) + o_rResult.SetWeight( WEIGHT_ULTRABOLD ); + else + o_rResult.SetWeight( WEIGHT_BLACK ); + } + else + o_rResult.SetWeight( (aInfo.macStyle & 1) ? WEIGHT_BOLD : WEIGHT_NORMAL ); + // set width + if( aInfo.width ) + { + if( aInfo.width == FWIDTH_ULTRA_CONDENSED ) + o_rResult.SetAverageFontWidth( WIDTH_ULTRA_CONDENSED ); + else if( aInfo.width == FWIDTH_EXTRA_CONDENSED ) + o_rResult.SetAverageFontWidth( WIDTH_EXTRA_CONDENSED ); + else if( aInfo.width == FWIDTH_CONDENSED ) + o_rResult.SetAverageFontWidth( WIDTH_CONDENSED ); + else if( aInfo.width == FWIDTH_SEMI_CONDENSED ) + o_rResult.SetAverageFontWidth( WIDTH_SEMI_CONDENSED ); + else if( aInfo.width == FWIDTH_NORMAL ) + o_rResult.SetAverageFontWidth( WIDTH_NORMAL ); + else if( aInfo.width == FWIDTH_SEMI_EXPANDED ) + o_rResult.SetAverageFontWidth( WIDTH_SEMI_EXPANDED ); + else if( aInfo.width == FWIDTH_EXPANDED ) + o_rResult.SetAverageFontWidth( WIDTH_EXPANDED ); + else if( aInfo.width == FWIDTH_EXTRA_EXPANDED ) + o_rResult.SetAverageFontWidth( WIDTH_EXTRA_EXPANDED ); + else if( aInfo.width >= FWIDTH_ULTRA_EXPANDED ) + o_rResult.SetAverageFontWidth( WIDTH_ULTRA_EXPANDED ); + } + // set italic + o_rResult.SetItalic( (aInfo.italicAngle != 0) ? ITALIC_NORMAL : ITALIC_NONE ); + + // set pitch + o_rResult.SetPitch( (aInfo.pitch == 0) ? PITCH_VARIABLE : PITCH_FIXED ); + + // set style name + if( !aInfo.usubfamily.isEmpty() ) + o_rResult.SetStyleName( aInfo.usubfamily ); + else if( !aInfo.subfamily.isEmpty() ) + o_rResult.SetStyleName( OUString::createFromAscii( aInfo.subfamily ) ); + + // cleanup + CloseTTFont( pTTF ); + // success + bResult = true; + } + return bResult; + } + + struct WeightSearchEntry + { + const char* string; + int string_len; + FontWeight weight; + + bool operator<( const WeightSearchEntry& rRight ) const + { + return rtl_str_compareIgnoreAsciiCase_WithLength( string, string_len, rRight.string, rRight.string_len ) < 0; + } + } + const weight_table[] = + { + { "black", 5, WEIGHT_BLACK }, + { "bold", 4, WEIGHT_BOLD }, + { "book", 4, WEIGHT_LIGHT }, + { "demi", 4, WEIGHT_SEMIBOLD }, + { "heavy", 5, WEIGHT_BLACK }, + { "light", 5, WEIGHT_LIGHT }, + { "medium", 6, WEIGHT_MEDIUM }, + { "regular", 7, WEIGHT_NORMAL }, + { "super", 5, WEIGHT_ULTRABOLD }, + { "thin", 4, WEIGHT_THIN } + }; + + bool identifyType1Font( const char* i_pBuffer, sal_uInt32 i_nSize, Font& o_rResult ) + { + // might be a type1, find eexec + const char* pStream = i_pBuffer; + const char* const pExec = "eexec"; + const char* pExecPos = std::search( pStream, pStream+i_nSize, pExec, pExec+5 ); + if( pExecPos != pStream+i_nSize) + { + // find /FamilyName entry + static const char* const pFam = "/FamilyName"; + const char* pFamPos = std::search( pStream, pExecPos, pFam, pFam+11 ); + if( pFamPos != pExecPos ) + { + // extract the string value behind /FamilyName + const char* pOpen = pFamPos+11; + while( pOpen < pExecPos && *pOpen != '(' ) + pOpen++; + const char* pClose = pOpen; + while( pClose < pExecPos && *pClose != ')' ) + pClose++; + if( pClose - pOpen > 1 ) + { + o_rResult.SetFamilyName( OStringToOUString( std::string_view( pOpen+1, pClose-pOpen-1 ), RTL_TEXTENCODING_ASCII_US ) ); + } + } + + // parse /ItalicAngle + static const char* const pItalic = "/ItalicAngle"; + const char* pItalicPos = std::search( pStream, pExecPos, pItalic, pItalic+12 ); + if( pItalicPos != pExecPos ) + { + const char* pItalicEnd = pItalicPos + 12; + auto nItalic = rtl_str_toInt64_WithLength(pItalicEnd, 10, pExecPos - pItalicEnd); + o_rResult.SetItalic( (nItalic != 0) ? ITALIC_NORMAL : ITALIC_NONE ); + } + + // parse /Weight + static const char* const pWeight = "/Weight"; + const char* pWeightPos = std::search( pStream, pExecPos, pWeight, pWeight+7 ); + if( pWeightPos != pExecPos ) + { + // extract the string value behind /Weight + const char* pOpen = pWeightPos+7; + while( pOpen < pExecPos && *pOpen != '(' ) + pOpen++; + const char* pClose = pOpen; + while( pClose < pExecPos && *pClose != ')' ) + pClose++; + if( pClose - pOpen > 1 ) + { + WeightSearchEntry aEnt; + aEnt.string = pOpen+1; + aEnt.string_len = (pClose-pOpen)-1; + aEnt.weight = WEIGHT_NORMAL; + WeightSearchEntry const * pFound = std::lower_bound( std::begin(weight_table), std::end(weight_table), aEnt ); + if( pFound != std::end(weight_table) && + rtl_str_compareIgnoreAsciiCase_WithLength( pFound->string, pFound->string_len, aEnt.string, aEnt.string_len) == 0 ) + o_rResult.SetWeight( pFound->weight ); + } + } + + // parse isFixedPitch + static const char* const pFixed = "/isFixedPitch"; + const char* pFixedPos = std::search( pStream, pExecPos, pFixed, pFixed+13 ); + if( pFixedPos != pExecPos ) + { + // skip whitespace + while( pFixedPos < pExecPos-4 && + ( *pFixedPos == ' ' || + *pFixedPos == '\t' || + *pFixedPos == '\r' || + *pFixedPos == '\n' ) ) + { + pFixedPos++; + } + // find "true" value + if( rtl_str_compareIgnoreAsciiCase_WithLength( pFixedPos, 4, "true", 4 ) == 0 ) + o_rResult.SetPitch( PITCH_FIXED ); + else + o_rResult.SetPitch( PITCH_VARIABLE ); + } + } + return false; + } +} + +Font Font::identifyFont( const void* i_pBuffer, sal_uInt32 i_nSize ) +{ + Font aResult; + if( ! identifyTrueTypeFont( i_pBuffer, i_nSize, aResult ) ) + { + const char* pStream = static_cast<const char*>(i_pBuffer); + if( pStream && i_nSize > 100 && + *pStream == '%' && pStream[1] == '!' ) + { + identifyType1Font( pStream, i_nSize, aResult ); + } + } + + return aResult; +} + +// The inlines from the font.hxx header are now instantiated for pImpl-ification +const Color& Font::GetColor() const { return mpImplFont->maColor; } +const Color& Font::GetFillColor() const { return mpImplFont->maFillColor; } +bool Font::IsTransparent() const { return mpImplFont->mbTransparent; } + +TextAlign Font::GetAlignment() const { return mpImplFont->GetAlignment(); } + +const OUString& Font::GetFamilyName() const { return mpImplFont->GetFamilyName(); } +const OUString& Font::GetStyleName() const { return mpImplFont->maStyleName; } +const FontFamily& Font::GetFontFamily() const { return mpImplFont->meFamily; } + +const Size& Font::GetFontSize() const { return mpImplFont->GetFontSize(); } +void Font::SetFontHeight( tools::Long nHeight ) { SetFontSize( Size( std::as_const(mpImplFont)->GetFontSize().Width(), nHeight ) ); } +tools::Long Font::GetFontHeight() const { return mpImplFont->GetFontSize().Height(); } +void Font::SetAverageFontWidth( tools::Long nWidth ) { SetFontSize( Size( nWidth, std::as_const(mpImplFont)->GetFontSize().Height() ) ); } +tools::Long Font::GetAverageFontWidth() const { return mpImplFont->GetFontSize().Width(); } +const Size& Font::GetAverageFontSize() const { return mpImplFont->maAverageFontSize; } + +rtl_TextEncoding Font::GetCharSet() const { return mpImplFont->GetCharSet(); } + +const LanguageTag& Font::GetLanguageTag() const { return mpImplFont->maLanguageTag; } +const LanguageTag& Font::GetCJKContextLanguageTag() const { return mpImplFont->maCJKLanguageTag; } +LanguageType Font::GetLanguage() const { return mpImplFont->maLanguageTag.getLanguageType( false); } +LanguageType Font::GetCJKContextLanguage() const { return mpImplFont->maCJKLanguageTag.getLanguageType( false); } + +Degree10 Font::GetOrientation() const { return mpImplFont->mnOrientation; } +bool Font::IsVertical() const { return mpImplFont->mbVertical; } +FontKerning Font::GetKerning() const { return mpImplFont->meKerning; } + +FontPitch Font::GetPitch() { return mpImplFont->GetPitch(); } +FontWeight Font::GetWeight() { return mpImplFont->GetWeight(); } +FontWidth Font::GetWidthType() { return mpImplFont->GetWidthType(); } +FontItalic Font::GetItalic() { return mpImplFont->GetItalic(); } +FontFamily Font::GetFamilyType() { return mpImplFont->GetFamilyType(); } + +FontPitch Font::GetPitch() const { return mpImplFont->GetPitchNoAsk(); } +FontWeight Font::GetWeight() const { return mpImplFont->GetWeightNoAsk(); } +FontWidth Font::GetWidthType() const { return mpImplFont->GetWidthTypeNoAsk(); } +FontItalic Font::GetItalic() const { return mpImplFont->GetItalicNoAsk(); } +FontFamily Font::GetFamilyType() const { return mpImplFont->GetFamilyTypeNoAsk(); } + +int Font::GetQuality() const { return mpImplFont->GetQuality(); } +void Font::SetQuality( int nQuality ) { mpImplFont->SetQuality( nQuality ); } +void Font::IncreaseQualityBy( int nQualityAmount ) { mpImplFont->IncreaseQualityBy( nQualityAmount ); } +void Font::DecreaseQualityBy( int nQualityAmount ) { mpImplFont->DecreaseQualityBy( nQualityAmount ); } + +bool Font::IsOutline() const { return mpImplFont->mbOutline; } +bool Font::IsShadow() const { return mpImplFont->mbShadow; } +FontRelief Font::GetRelief() const { return mpImplFont->meRelief; } +FontLineStyle Font::GetUnderline() const { return mpImplFont->meUnderline; } +FontLineStyle Font::GetOverline() const { return mpImplFont->meOverline; } +FontStrikeout Font::GetStrikeout() const { return mpImplFont->meStrikeout; } +FontEmphasisMark Font::GetEmphasisMark() const { return mpImplFont->meEmphasisMark; } +bool Font::IsWordLineMode() const { return mpImplFont->mbWordLine; } +bool Font::IsSameInstance( const vcl::Font& rFont ) const { return (mpImplFont == rFont.mpImplFont); } + + +ImplFont::ImplFont() : + meWeight( WEIGHT_DONTKNOW ), + meFamily( FAMILY_DONTKNOW ), + mePitch( PITCH_DONTKNOW ), + meWidthType( WIDTH_DONTKNOW ), + meItalic( ITALIC_NONE ), + meAlign( ALIGN_TOP ), + meUnderline( LINESTYLE_NONE ), + meOverline( LINESTYLE_NONE ), + meStrikeout( STRIKEOUT_NONE ), + meRelief( FontRelief::NONE ), + meEmphasisMark( FontEmphasisMark::NONE ), + meKerning( FontKerning::FontSpecific ), + mnSpacing( 0 ), + meCharSet( RTL_TEXTENCODING_DONTKNOW ), + maLanguageTag( LANGUAGE_DONTKNOW ), + maCJKLanguageTag( LANGUAGE_DONTKNOW ), + mbOutline( false ), + mbConfigLookup( false ), + mbShadow( false ), + mbVertical( false ), + mbTransparent( true ), + maColor( COL_TRANSPARENT ), + maFillColor( COL_TRANSPARENT ), + mbWordLine( false ), + mnOrientation( 0 ), + mnQuality( 0 ), + mnCalculatedAverageFontWidth( 0 ) +{} + +ImplFont::ImplFont( const ImplFont& rImplFont ) : + maFamilyName( rImplFont.maFamilyName ), + maStyleName( rImplFont.maStyleName ), + meWeight( rImplFont.meWeight ), + meFamily( rImplFont.meFamily ), + mePitch( rImplFont.mePitch ), + meWidthType( rImplFont.meWidthType ), + meItalic( rImplFont.meItalic ), + meAlign( rImplFont.meAlign ), + meUnderline( rImplFont.meUnderline ), + meOverline( rImplFont.meOverline ), + meStrikeout( rImplFont.meStrikeout ), + meRelief( rImplFont.meRelief ), + meEmphasisMark( rImplFont.meEmphasisMark ), + meKerning( rImplFont.meKerning ), + mnSpacing( rImplFont.mnSpacing ), + maAverageFontSize( rImplFont.maAverageFontSize ), + meCharSet( rImplFont.meCharSet ), + maLanguageTag( rImplFont.maLanguageTag ), + maCJKLanguageTag( rImplFont.maCJKLanguageTag ), + mbOutline( rImplFont.mbOutline ), + mbConfigLookup( rImplFont.mbConfigLookup ), + mbShadow( rImplFont.mbShadow ), + mbVertical( rImplFont.mbVertical ), + mbTransparent( rImplFont.mbTransparent ), + maColor( rImplFont.maColor ), + maFillColor( rImplFont.maFillColor ), + mbWordLine( rImplFont.mbWordLine ), + mnOrientation( rImplFont.mnOrientation ), + mnQuality( rImplFont.mnQuality ), + mnCalculatedAverageFontWidth( rImplFont.mnCalculatedAverageFontWidth ) +{} + +bool ImplFont::operator==( const ImplFont& rOther ) const +{ + if(!EqualIgnoreColor( rOther )) + return false; + + if( (maColor != rOther.maColor) + || (maFillColor != rOther.maFillColor) ) + return false; + + return true; +} + +bool ImplFont::EqualIgnoreColor( const ImplFont& rOther ) const +{ + // equality tests split up for easier debugging + if( (meWeight != rOther.meWeight) + || (meItalic != rOther.meItalic) + || (meFamily != rOther.meFamily) + || (mePitch != rOther.mePitch) ) + return false; + + if( (meCharSet != rOther.meCharSet) + || (maLanguageTag != rOther.maLanguageTag) + || (maCJKLanguageTag != rOther.maCJKLanguageTag) + || (meAlign != rOther.meAlign) ) + return false; + + if( (maAverageFontSize != rOther.maAverageFontSize) + || (mnOrientation != rOther.mnOrientation) + || (mbVertical != rOther.mbVertical) ) + return false; + + if( (maFamilyName != rOther.maFamilyName) + || (maStyleName != rOther.maStyleName) ) + return false; + + if( (meUnderline != rOther.meUnderline) + || (meOverline != rOther.meOverline) + || (meStrikeout != rOther.meStrikeout) + || (meRelief != rOther.meRelief) + || (meEmphasisMark != rOther.meEmphasisMark) + || (mbWordLine != rOther.mbWordLine) + || (mbOutline != rOther.mbOutline) + || (mbShadow != rOther.mbShadow) + || (meKerning != rOther.meKerning) + || (mnSpacing != rOther.mnSpacing) + || (mbTransparent != rOther.mbTransparent) ) + return false; + + return true; +} + +size_t ImplFont::GetHashValue() const +{ + size_t hash = GetHashValueIgnoreColor(); + o3tl::hash_combine( hash, static_cast<sal_uInt32>( maColor )); + o3tl::hash_combine( hash, static_cast<sal_uInt32>( maFillColor )); + return hash; +} + +size_t ImplFont::GetHashValueIgnoreColor() const +{ + size_t hash = 0; + + o3tl::hash_combine( hash, meWeight ); + o3tl::hash_combine( hash, meItalic ); + o3tl::hash_combine( hash, meFamily ); + o3tl::hash_combine( hash, mePitch ); + + o3tl::hash_combine( hash, meCharSet ); + o3tl::hash_combine( hash, maLanguageTag.getLanguageType( false ).get()); + o3tl::hash_combine( hash, maCJKLanguageTag.getLanguageType( false ).get()); + o3tl::hash_combine( hash, meAlign ); + + o3tl::hash_combine( hash, maAverageFontSize.GetHashValue()); + o3tl::hash_combine( hash, mnOrientation.get()); + o3tl::hash_combine( hash, mbVertical ); + + o3tl::hash_combine( hash, maFamilyName ); + o3tl::hash_combine( hash, maStyleName ); + + o3tl::hash_combine( hash, meUnderline ); + o3tl::hash_combine( hash, meOverline ); + o3tl::hash_combine( hash, meStrikeout ); + o3tl::hash_combine( hash, meRelief ); + o3tl::hash_combine( hash, meEmphasisMark ); + o3tl::hash_combine( hash, mbWordLine ); + o3tl::hash_combine( hash, mbOutline ); + o3tl::hash_combine( hash, mbShadow ); + o3tl::hash_combine( hash, meKerning ); + o3tl::hash_combine( hash, mnSpacing ); + o3tl::hash_combine( hash, mbTransparent ); + + return hash; +} + +void ImplFont::AskConfig() +{ + if( mbConfigLookup ) + return; + + mbConfigLookup = true; + + // prepare the FontSubst configuration lookup + const utl::FontSubstConfiguration& rFontSubst = utl::FontSubstConfiguration::get(); + + OUString aShortName; + OUString aFamilyName; + ImplFontAttrs nType = ImplFontAttrs::None; + FontWeight eWeight = WEIGHT_DONTKNOW; + FontWidth eWidthType = WIDTH_DONTKNOW; + OUString aMapName = GetEnglishSearchFontName( maFamilyName ); + + utl::FontSubstConfiguration::getMapName( aMapName, + aShortName, aFamilyName, eWeight, eWidthType, nType ); + + // lookup the font name in the configuration + const utl::FontNameAttr* pFontAttr = rFontSubst.getSubstInfo( aMapName ); + + // if the direct lookup failed try again with an alias name + if ( !pFontAttr && (aShortName != aMapName) ) + pFontAttr = rFontSubst.getSubstInfo( aShortName ); + + if( pFontAttr ) + { + // the font was found in the configuration + if( meFamily == FAMILY_DONTKNOW ) + { + if ( pFontAttr->Type & ImplFontAttrs::Serif ) + meFamily = FAMILY_ROMAN; + else if ( pFontAttr->Type & ImplFontAttrs::SansSerif ) + meFamily = FAMILY_SWISS; + else if ( pFontAttr->Type & ImplFontAttrs::Typewriter ) + meFamily = FAMILY_MODERN; + else if ( pFontAttr->Type & ImplFontAttrs::Italic ) + meFamily = FAMILY_SCRIPT; + else if ( pFontAttr->Type & ImplFontAttrs::Decorative ) + meFamily = FAMILY_DECORATIVE; + } + + if( mePitch == PITCH_DONTKNOW ) + { + if ( pFontAttr->Type & ImplFontAttrs::Fixed ) + mePitch = PITCH_FIXED; + } + } + + // if some attributes are still unknown then use the FontSubst magic + if( meFamily == FAMILY_DONTKNOW ) + { + if( nType & ImplFontAttrs::Serif ) + meFamily = FAMILY_ROMAN; + else if( nType & ImplFontAttrs::SansSerif ) + meFamily = FAMILY_SWISS; + else if( nType & ImplFontAttrs::Typewriter ) + meFamily = FAMILY_MODERN; + else if( nType & ImplFontAttrs::Italic ) + meFamily = FAMILY_SCRIPT; + else if( nType & ImplFontAttrs::Decorative ) + meFamily = FAMILY_DECORATIVE; + } + + if( GetWeight() == WEIGHT_DONTKNOW ) + SetWeight( eWeight ); + if( meWidthType == WIDTH_DONTKNOW ) + meWidthType = eWidthType; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontattributes.cxx b/vcl/source/font/fontattributes.cxx new file mode 100644 index 0000000000..5c020d0724 --- /dev/null +++ b/vcl/source/font/fontattributes.cxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <fontattributes.hxx> + +FontAttributes::FontAttributes() +: meWeight( WEIGHT_DONTKNOW ), + meFamily( FAMILY_DONTKNOW ), + mePitch( PITCH_DONTKNOW ), + meWidthType ( WIDTH_DONTKNOW ), + meItalic ( ITALIC_NONE ), + mbMicrosoftSymbolEncoded( false ), + mnQuality( 0 ) +{} + +bool FontAttributes::CompareDeviceIndependentFontAttributes(const FontAttributes& rOther) const +{ + if (maFamilyName != rOther.maFamilyName) + return false; + + if (maStyleName != rOther.maStyleName) + return false; + + if (meWeight != rOther.meWeight) + return false; + + if (meItalic != rOther.meItalic) + return false; + + if (meFamily != rOther.meFamily) + return false; + + if (mePitch != rOther.mePitch) + return false; + + if (meWidthType != rOther.meWidthType) + return false; + + if (mbMicrosoftSymbolEncoded != rOther.mbMicrosoftSymbolEncoded) + return false; + + return true; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontcache.cxx b/vcl/source/font/fontcache.cxx new file mode 100644 index 0000000000..c0dba15350 --- /dev/null +++ b/vcl/source/font/fontcache.cxx @@ -0,0 +1,283 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <sal/log.hxx> + +#include <font/PhysicalFontCollection.hxx> +#include <font/PhysicalFontFace.hxx> +#include <font/PhysicalFontFamily.hxx> +#include <font/LogicalFontInstance.hxx> +#include <tools/debug.hxx> +#include <impfontcache.hxx> + +using namespace vcl::font; + +size_t ImplFontCache::IFSD_Hash::operator()( const vcl::font::FontSelectPattern& rFSD ) const +{ + return rFSD.hashCode(); +} + +bool ImplFontCache::IFSD_Equal::operator()(const vcl::font::FontSelectPattern& rA, const vcl::font::FontSelectPattern& rB) const +{ + // check normalized font family name + if( rA.maSearchName != rB.maSearchName ) + return false; + + // check font transformation + if( (rA.mnHeight != rB.mnHeight) + || (rA.mnWidth != rB.mnWidth) + || (rA.mnOrientation != rB.mnOrientation) ) + return false; + + // check mapping relevant attributes + if( (rA.mbVertical != rB.mbVertical) + || (rA.meLanguage != rB.meLanguage) ) + return false; + + // check font face attributes + if( (rA.GetWeight() != rB.GetWeight()) + || (rA.GetItalic() != rB.GetItalic()) +// || (rA.meFamily != rB.meFamily) // TODO: remove this mostly obsolete member + || (rA.GetPitch() != rB.GetPitch()) ) + return false; + + // check style name + if( rA.GetStyleName() != rB.GetStyleName() ) + return false; + + // Symbol fonts may recode from one type to another So they are only + // safely equivalent for equal targets + if (rA.IsMicrosoftSymbolEncoded() || rB.IsMicrosoftSymbolEncoded()) + { + if (rA.maTargetName != rB.maTargetName) + return false; + } + + // check for features + if ((rA.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX) + != -1 || + rB.maTargetName.indexOf(vcl::font::FontSelectPattern::FEAT_PREFIX) + != -1) && rA.maTargetName != rB.maTargetName) + return false; + + if (rA.mbEmbolden != rB.mbEmbolden) + return false; + + if (rA.maItalicMatrix != rB.maItalicMatrix) + return false; + + return true; +} + +ImplFontCache::ImplFontCache() + : mpLastHitCacheEntry( nullptr ) + , maFontInstanceList(std::numeric_limits<size_t>::max()) // "unlimited", i.e. no cleanup + // The cache limit is set by the rough number of characters needed to read your average Asian newspaper. + , m_aBoundRectCache(3000) +{} + +ImplFontCache::~ImplFontCache() +{ + DBG_TESTSOLARMUTEX(); + for (const auto & rLFI : maFontInstanceList) + { + rLFI.second->mpFontCache = nullptr; + } +} + +rtl::Reference<LogicalFontInstance> ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList, + const vcl::Font& rFont, const Size& rSize, float fExactHeight, bool bNonAntialias ) +{ + // initialize internal font request object + vcl::font::FontSelectPattern aFontSelData(rFont, rFont.GetFamilyName(), rSize, fExactHeight, bNonAntialias); + return GetFontInstance( pFontList, aFontSelData ); +} + +rtl::Reference<LogicalFontInstance> ImplFontCache::GetFontInstance( PhysicalFontCollection const * pFontList, + vcl::font::FontSelectPattern& aFontSelData ) +{ + DBG_TESTSOLARMUTEX(); + rtl::Reference<LogicalFontInstance> pFontInstance; + PhysicalFontFamily* pFontFamily = nullptr; + + // check if a directly matching logical font instance is already cached, + // the most recently used font usually has a hit rate of >50% + if (mpLastHitCacheEntry && IFSD_Equal()(aFontSelData, mpLastHitCacheEntry->GetFontSelectPattern())) + pFontInstance = mpLastHitCacheEntry; + else + { + FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData ); + if( it != maFontInstanceList.end() ) + pFontInstance = (*it).second; + } + + if( !pFontInstance ) // no direct cache hit + { + // find the best matching logical font family and update font selector accordingly + pFontFamily = pFontList->FindFontFamily( aFontSelData ); + SAL_WARN_IF( (pFontFamily == nullptr), "vcl", "ImplFontCache::Get() No logical font found!" ); + if( pFontFamily ) + { + aFontSelData.maSearchName = pFontFamily->GetSearchName(); + + // check if an indirectly matching logical font instance is already cached + FontInstanceList::const_iterator it = maFontInstanceList.find( aFontSelData ); + if( it != maFontInstanceList.end() ) + pFontInstance = (*it).second; + } + } + + if( !pFontInstance && pFontFamily) // still no cache hit => create a new font instance + { + vcl::font::PhysicalFontFace* pFontData = pFontFamily->FindBestFontFace(aFontSelData); + + // create a new logical font instance from this physical font face + pFontInstance = pFontData->CreateFontInstance( aFontSelData ); + pFontInstance->mpFontCache = this; + + // if we're substituting from or to a symbol font we may need a symbol + // conversion table + if( pFontData->IsMicrosoftSymbolEncoded() || aFontSelData.IsMicrosoftSymbolEncoded() || IsOpenSymbol(aFontSelData.maSearchName) ) + { + if( aFontSelData.maTargetName != aFontSelData.maSearchName ) + pFontInstance->mpConversion = ConvertChar::GetRecodeData( aFontSelData.maTargetName, aFontSelData.maSearchName ); + } + +#ifdef MACOSX + //It might be better to dig out the font version of the target font + //to see if it's a modern re-coded apple symbol font in case that + //font shows up on a different platform + if (!pFontInstance->mpConversion && + aFontSelData.maTargetName.equalsIgnoreAsciiCase("symbol") && + aFontSelData.maSearchName.equalsIgnoreAsciiCase("symbol")) + { + pFontInstance->mpConversion = ConvertChar::GetRecodeData( u"Symbol", u"AppleSymbol" ); + } +#endif + + static const size_t FONTCACHE_MAX = getenv("LO_TESTNAME") ? 1 : 50; + + if (maFontInstanceList.size() >= FONTCACHE_MAX) + { + struct limit_exception : public std::exception {}; + try + { + maFontInstanceList.remove_if([this] (FontInstanceList::key_value_pair_t const& rFontPair) + { + if (maFontInstanceList.size() < FONTCACHE_MAX) + throw limit_exception(); + LogicalFontInstance* pFontEntry = rFontPair.second.get(); + if (pFontEntry->m_nCount > 1) + return false; + m_aBoundRectCache.remove_if([&pFontEntry] (GlyphBoundRectCache::key_value_pair_t const& rGlyphPair) + { return rGlyphPair.first.m_pFont == pFontEntry; }); + if (mpLastHitCacheEntry == pFontEntry) + mpLastHitCacheEntry = nullptr; + return true; + }); + } + catch (limit_exception&) {} + } + + assert(pFontInstance); + // add the new entry to the cache + maFontInstanceList.insert({aFontSelData, pFontInstance.get()}); + } + + mpLastHitCacheEntry = pFontInstance.get(); + return pFontInstance; +} + +rtl::Reference<LogicalFontInstance> ImplFontCache::GetGlyphFallbackFont( PhysicalFontCollection const * pFontCollection, + vcl::font::FontSelectPattern& rFontSelData, LogicalFontInstance* pFontInstance, int nFallbackLevel, OUString& rMissingCodes ) +{ + // get a candidate font for glyph fallback + // unless the previously selected font got a device specific substitution + // e.g. PsPrint Arial->Helvetica for udiaeresis when Helvetica doesn't support it + if( nFallbackLevel >= 1) + { + PhysicalFontFamily* pFallbackData = nullptr; + + //fdo#33898 If someone has EUDC installed then they really want that to + //be used as the first-choice glyph fallback seeing as it's filled with + //private area codes with don't make any sense in any other font so + //prioritize it here if it's available. Ideally we would remove from + //rMissingCodes all the glyphs which it is able to resolve as an + //optimization, but that's tricky to achieve cross-platform without + //sufficient heavy-weight code that's likely to undo the value of the + //optimization + if (nFallbackLevel == 1) + pFallbackData = pFontCollection->FindFontFamily(u"EUDC"); + if (!pFallbackData) + pFallbackData = pFontCollection->GetGlyphFallbackFont(rFontSelData, pFontInstance, rMissingCodes, nFallbackLevel-1); + // escape when there are no font candidates + if( !pFallbackData ) + return nullptr; + // override the font name + rFontSelData.SetFamilyName( pFallbackData->GetFamilyName() ); + // clear the cached normalized name + rFontSelData.maSearchName.clear(); + } + + rtl::Reference<LogicalFontInstance> pFallbackFont = GetFontInstance( pFontCollection, rFontSelData ); + return pFallbackFont; +} + +void ImplFontCache::Invalidate() +{ + DBG_TESTSOLARMUTEX(); + // #112304# make sure the font cache is really clean + mpLastHitCacheEntry = nullptr; + for (auto const & pair : maFontInstanceList) + pair.second->mpFontCache = nullptr; + maFontInstanceList.clear(); + m_aBoundRectCache.clear(); +} + +bool ImplFontCache::GetCachedGlyphBoundRect(const LogicalFontInstance *pFont, sal_GlyphId nID, tools::Rectangle &rRect) +{ + if (!pFont->GetFontCache()) + return false; + assert(pFont->GetFontCache() == this); + if (pFont->GetFontCache() != this) + return false; + + auto it = m_aBoundRectCache.find({pFont, nID}); + if (it != m_aBoundRectCache.end()) + { + rRect = it->second; + return true; + } + return false; +} + +void ImplFontCache::CacheGlyphBoundRect(const LogicalFontInstance *pFont, sal_GlyphId nID, tools::Rectangle &rRect) +{ + if (!pFont->GetFontCache()) + return; + assert(pFont->GetFontCache() == this); + if (pFont->GetFontCache() != this) + return; + + m_aBoundRectCache.insert({{pFont, nID}, rRect}); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontcharmap.cxx b/vcl/source/font/fontcharmap.cxx new file mode 100644 index 0000000000..1a149bcc7d --- /dev/null +++ b/vcl/source/font/fontcharmap.cxx @@ -0,0 +1,251 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +#include <utility> +#include <vcl/fontcharmap.hxx> +#include <impfontcharmap.hxx> +#include <sal/log.hxx> + +#include <algorithm> +#include <vector> + +static ImplFontCharMapRef g_pDefaultImplFontCharMap; +const std::vector<sal_uInt32> aDefaultUnicodeRanges = { 0x0020, 0xD800, 0xE000, 0xFFF0 }; +const std::vector<sal_uInt32> aDefaultSymbolRanges = { 0x0020, 0x0100, 0xF020, 0xF100 }; + +ImplFontCharMap::~ImplFontCharMap() +{ +} + +ImplFontCharMap::ImplFontCharMap(bool bMicrosoftSymbolMap, std::vector<sal_uInt32> aRangeCodes) +: maRangeCodes(std::move(aRangeCodes)) +, mnCharCount( 0 ) +, m_bMicrosoftSymbolMap(bMicrosoftSymbolMap) +{ + for (size_t i = 0; i < maRangeCodes.size(); i += 2) + { + sal_UCS4 cFirst = maRangeCodes[i]; + sal_UCS4 cLast = maRangeCodes[i + 1]; + mnCharCount += cLast - cFirst; + } +} + +ImplFontCharMapRef const & ImplFontCharMap::getDefaultMap(bool bMicrosoftSymbolMap) +{ + const auto& rRanges = bMicrosoftSymbolMap ? aDefaultSymbolRanges : aDefaultUnicodeRanges; + g_pDefaultImplFontCharMap = ImplFontCharMapRef(new ImplFontCharMap(bMicrosoftSymbolMap, rRanges)); + return g_pDefaultImplFontCharMap; +} + +bool ImplFontCharMap::isDefaultMap() const +{ + const bool bIsDefault = (maRangeCodes == aDefaultUnicodeRanges) || (maRangeCodes == aDefaultSymbolRanges); + return bIsDefault; +} + +static unsigned GetUShort(const unsigned char* p) { return((p[0]<<8) | p[1]);} + +bool HasMicrosoftSymbolCmap(const unsigned char* pCmap, int nLength) +{ + // parse the table header and check for validity + if( !pCmap || (nLength < 24) ) + return false; + + if( GetUShort( pCmap ) != 0x0000 ) // simple check for CMAP corruption + return false; + + int nSubTables = GetUShort(pCmap + 2); + if( (nSubTables <= 0) || (nSubTables > (nLength - 24) / 8) ) + return false; + + for (const unsigned char* p = pCmap + 4; --nSubTables >= 0; p += 8) + { + int nPlatform = GetUShort(p); + int nEncoding = GetUShort(p + 2); + // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html + // When the platformID is 3 (Windows), an encoding of 0 is Symbol + if (nPlatform == 3 && nEncoding == 0) + return true; + } + + return false; +} + +FontCharMap::FontCharMap() + : mpImplFontCharMap( ImplFontCharMap::getDefaultMap() ) +{ +} + +FontCharMap::FontCharMap( ImplFontCharMapRef pIFCMap ) + : mpImplFontCharMap(std::move( pIFCMap )) +{ +} + +FontCharMap::FontCharMap(bool bMicrosoftSymbolMap, std::vector<sal_uInt32> aRangeCodes) + : mpImplFontCharMap(new ImplFontCharMap(bMicrosoftSymbolMap, std::move(aRangeCodes))) +{ +} + +FontCharMap::~FontCharMap() +{ + mpImplFontCharMap = nullptr; +} + +FontCharMapRef FontCharMap::GetDefaultMap(bool bMicrosoftSymbolMap) +{ + FontCharMapRef xFontCharMap( new FontCharMap( ImplFontCharMap::getDefaultMap(bMicrosoftSymbolMap) ) ); + return xFontCharMap; +} + +bool FontCharMap::IsDefaultMap() const +{ + return mpImplFontCharMap->isDefaultMap(); +} + +bool FontCharMap::isMicrosoftSymbolMap() const { return mpImplFontCharMap->m_bMicrosoftSymbolMap; } + +int FontCharMap::GetCharCount() const +{ + return mpImplFontCharMap->mnCharCount; +} + +int FontCharMap::CountCharsInRange( sal_UCS4 cMin, sal_UCS4 cMax ) const +{ + const auto& rRanges = mpImplFontCharMap->maRangeCodes; + int nCount = 0; + + // find and adjust range and char count for cMin + int nRangeMin = findRangeIndex( cMin ); + if( nRangeMin & 1 ) + ++nRangeMin; + else if (cMin > rRanges[nRangeMin]) + nCount -= cMin - rRanges[nRangeMin]; + + // find and adjust range and char count for cMax + int nRangeMax = findRangeIndex( cMax ); + if( nRangeMax & 1 ) + --nRangeMax; + else + nCount -= rRanges[nRangeMax + 1] - cMax - 1; + + // count chars in complete ranges between cMin and cMax + for( int i = nRangeMin; i <= nRangeMax; i+=2 ) + nCount += rRanges[i + 1] - rRanges[i]; + + return nCount; +} + +bool FontCharMap::HasChar( sal_UCS4 cChar ) const +{ + const int nRange = findRangeIndex( cChar ); + if (nRange==0 && cChar < mpImplFontCharMap->maRangeCodes[0]) + return false; + return ((nRange & 1) == 0); // inside a range +} + +sal_UCS4 FontCharMap::GetFirstChar() const +{ + return mpImplFontCharMap->maRangeCodes.front(); +} + +sal_UCS4 FontCharMap::GetLastChar() const +{ + return mpImplFontCharMap->maRangeCodes.back() - 1; +} + +sal_UCS4 FontCharMap::GetNextChar( sal_UCS4 cChar ) const +{ + if( cChar < GetFirstChar() ) + return GetFirstChar(); + if( cChar >= GetLastChar() ) + return GetLastChar(); + + int nRange = findRangeIndex( cChar + 1 ); + if( nRange & 1 ) // outside of range? + return mpImplFontCharMap->maRangeCodes[nRange + 1]; // => first in next range + return (cChar + 1); +} + +sal_UCS4 FontCharMap::GetPrevChar( sal_UCS4 cChar ) const +{ + if( cChar <= GetFirstChar() ) + return GetFirstChar(); + if( cChar > GetLastChar() ) + return GetLastChar(); + + int nRange = findRangeIndex( cChar - 1 ); + if( nRange & 1 ) // outside a range? + return mpImplFontCharMap->maRangeCodes[nRange] - 1; // => last in prev range + return (cChar - 1); +} + +int FontCharMap::GetIndexFromChar( sal_UCS4 cChar ) const +{ + // TODO: improve linear walk? + int nCharIndex = 0; + const auto& rRanges = mpImplFontCharMap->maRangeCodes; + for (size_t i = 0; i < rRanges.size(); i += 2) + { + sal_UCS4 cFirst = rRanges[i]; + sal_UCS4 cLast = rRanges[i + 1]; + if( cChar >= cLast ) + nCharIndex += cLast - cFirst; + else if( cChar >= cFirst ) + return nCharIndex + (cChar - cFirst); + else + break; + } + + return -1; +} + +sal_UCS4 FontCharMap::GetCharFromIndex( int nIndex ) const +{ + // TODO: improve linear walk? + const auto& rRanges = mpImplFontCharMap->maRangeCodes; + for (size_t i = 0; i < rRanges.size(); i += 2) + { + sal_UCS4 cFirst = rRanges[i]; + sal_UCS4 cLast = rRanges[i + 1]; + nIndex -= cLast - cFirst; + if( nIndex < 0 ) + return (cLast + nIndex); + } + + // we can only get here with an out-of-bounds charindex + return mpImplFontCharMap->maRangeCodes.front(); +} + +int FontCharMap::findRangeIndex( sal_UCS4 cChar ) const +{ + const auto& rRanges = mpImplFontCharMap->maRangeCodes; + int nLower = 0; + int nMid = rRanges.size() / 2; + int nUpper = rRanges.size() - 1; + while( nLower < nUpper ) + { + if (cChar >= rRanges[nMid]) + nLower = nMid; + else + nUpper = nMid - 1; + nMid = (nLower + nUpper + 1) / 2; + } + + return nMid; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/vcl/source/font/fontmetric.cxx b/vcl/source/font/fontmetric.cxx new file mode 100644 index 0000000000..115b3da6fb --- /dev/null +++ b/vcl/source/font/fontmetric.cxx @@ -0,0 +1,563 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include <sal/config.h> + +#include <i18nlangtag/mslangid.hxx> +#include <officecfg/Office/Common.hxx> +#include <sal/log.hxx> +#include <tools/stream.hxx> +#include <unotools/configmgr.hxx> +#include <vcl/metric.hxx> +#include <vcl/outdev.hxx> + +#include <font/FontSelectPattern.hxx> +#include <font/PhysicalFontFace.hxx> +#include <font/LogicalFontInstance.hxx> +#include <font/FontMetricData.hxx> +#include <sft.hxx> + +#include <com/sun/star/uno/Sequence.hxx> +#include <comphelper/sequence.hxx> +#include <hb-ot.h> + +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::rtl; +using namespace ::utl; + +FontMetric::FontMetric() +: mnAscent( 0 ), + mnDescent( 0 ), + mnIntLeading( 0 ), + mnExtLeading( 0 ), + mnLineHeight( 0 ), + mnSlant( 0 ), + mnBulletOffset( 0 ), + mnHangingBaseline( 0 ), + mbFullstopCentered( false ) +{} + +FontMetric::FontMetric( const FontMetric& rFontMetric ) = default; + +FontMetric::FontMetric(vcl::font::PhysicalFontFace const& rFace) + : FontMetric() +{ + SetFamilyName(rFace.GetFamilyName()); + SetStyleName(rFace.GetStyleName()); + SetCharSet(rFace.IsMicrosoftSymbolEncoded() ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE); + SetFamily(rFace.GetFamilyType()); + SetPitch(rFace.GetPitch()); + SetWeight(rFace.GetWeight()); + SetItalic(rFace.GetItalic()); + SetAlignment(TextAlign::ALIGN_TOP); + SetWidthType(rFace.GetWidthType()); + SetQuality(rFace.GetQuality() ); +} + +FontMetric::~FontMetric() +{ +} + +FontMetric& FontMetric::operator=(const FontMetric& rFontMetric) = default; + +FontMetric& FontMetric::operator=(FontMetric&& rFontMetric) = default; + +bool FontMetric::EqualNoBase( const FontMetric& r ) const +{ + if (mbFullstopCentered != r.mbFullstopCentered) + return false; + if( mnAscent != r.mnAscent ) + return false; + if( mnDescent != r.mnDescent ) + return false; + if( mnIntLeading != r.mnIntLeading ) + return false; + if( mnExtLeading != r.mnExtLeading ) + return false; + if( mnSlant != r.mnSlant ) + return false; + + return true; +} + +bool FontMetric::operator==( const FontMetric& r ) const +{ + if( Font::operator!=(r) ) + return false; + return EqualNoBase(r); +} + +bool FontMetric::EqualIgnoreColor( const FontMetric& r ) const +{ + if( !Font::EqualIgnoreColor(r) ) + return false; + return EqualNoBase(r); +} + +size_t FontMetric::GetHashValueNoBase() const +{ + size_t hash = 0; + o3tl::hash_combine( hash, mbFullstopCentered ); + o3tl::hash_combine( hash, mnAscent ); + o3tl::hash_combine( hash, mnDescent ); + o3tl::hash_combine( hash, mnIntLeading ); + o3tl::hash_combine( hash, mnExtLeading ); + o3tl::hash_combine( hash, mnSlant ); + return hash; +} + +size_t FontMetric::GetHashValueIgnoreColor() const +{ + size_t hash = GetHashValueNoBase(); + o3tl::hash_combine( hash, Font::GetHashValueIgnoreColor()); + return hash; +} + +FontMetricData::FontMetricData( const vcl::font::FontSelectPattern& rFontSelData ) + : FontAttributes( rFontSelData ) + , mnHeight ( rFontSelData.mnHeight ) + , mnWidth ( rFontSelData.mnWidth ) + , mnOrientation( static_cast<short>(rFontSelData.mnOrientation) ) + , mnAscent( 0 ) + , mnDescent( 0 ) + , mnIntLeading( 0 ) + , mnExtLeading( 0 ) + , mnSlant( 0 ) + , mnMinKashida( 0 ) + , mnHangingBaseline( 0 ) + , mbFullstopCentered( false ) + , mnBulletOffset( 0 ) + , mnUnderlineSize( 0 ) + , mnUnderlineOffset( 0 ) + , mnBUnderlineSize( 0 ) + , mnBUnderlineOffset( 0 ) + , mnDUnderlineSize( 0 ) + , mnDUnderlineOffset1( 0 ) + , mnDUnderlineOffset2( 0 ) + , mnWUnderlineSize( 0 ) + , mnWUnderlineOffset( 0 ) + , mnAboveUnderlineSize( 0 ) + , mnAboveUnderlineOffset( 0 ) + , mnAboveBUnderlineSize( 0 ) + , mnAboveBUnderlineOffset( 0 ) + , mnAboveDUnderlineSize( 0 ) + , mnAboveDUnderlineOffset1( 0 ) + , mnAboveDUnderlineOffset2( 0 ) + , mnAboveWUnderlineSize( 0 ) + , mnAboveWUnderlineOffset( 0 ) + , mnStrikeoutSize( 0 ) + , mnStrikeoutOffset( 0 ) + , mnBStrikeoutSize( 0 ) + , mnBStrikeoutOffset( 0 ) + , mnDStrikeoutSize( 0 ) + , mnDStrikeoutOffset1( 0 ) + , mnDStrikeoutOffset2( 0 ) +{ + // initialize the used font name + sal_Int32 nTokenPos = 0; + SetFamilyName( OUString(GetNextFontToken( rFontSelData.GetFamilyName(), nTokenPos )) ); + SetStyleName( rFontSelData.GetStyleName() ); +} + +bool FontMetricData::ShouldNotUseUnderlineMetrics() const +{ + if (utl::ConfigManager::IsFuzzing()) + return false; + + css::uno::Sequence<OUString> rNoUnderlineMetricsList( + officecfg::Office::Common::Misc::FontsDontUseUnderlineMetrics::get()); + if (comphelper::findValue(rNoUnderlineMetricsList, GetFamilyName()) != -1) + { + SAL_INFO("vcl.gdi.fontmetric", "Not using underline metrics for: " << GetFamilyName()); + return true; + } + return false; +} + +bool FontMetricData::ImplInitTextLineSizeHarfBuzz(LogicalFontInstance* pFont) +{ + if (ShouldNotUseUnderlineMetrics()) + return false; + + auto* pHbFont = pFont->GetHbFont(); + + hb_position_t nUnderlineSize; + if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_UNDERLINE_SIZE, &nUnderlineSize)) + return false; + hb_position_t nUnderlineOffset; + if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_UNDERLINE_OFFSET, &nUnderlineOffset)) + return false; + hb_position_t nStrikeoutSize; + if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_STRIKEOUT_SIZE, &nStrikeoutSize)) + return false; + hb_position_t nStrikeoutOffset; + if (!hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_STRIKEOUT_OFFSET, &nStrikeoutOffset)) + return false; + + double fScale = 0; + pFont->GetScale(nullptr, &fScale); + + double nOffset = -nUnderlineOffset * fScale; + double nSize = nUnderlineSize * fScale; + double nSize2 = nSize / 2.; + double nBSize = nSize * 2.; + double n2Size = nBSize / 3.; + + mnUnderlineSize = std::ceil(nSize); + mnUnderlineOffset = std::ceil(nOffset); + + mnBUnderlineSize = std::ceil(nBSize); + mnBUnderlineOffset = std::ceil(nOffset - nSize2); + + mnDUnderlineSize = std::ceil(n2Size); + mnDUnderlineOffset1 = mnBUnderlineOffset; + mnDUnderlineOffset2 = mnBUnderlineOffset + mnDUnderlineSize * 2; + + mnWUnderlineSize = mnBUnderlineSize; + mnWUnderlineOffset = std::ceil(nOffset + nSize); + + nOffset = -nStrikeoutOffset * fScale; + nSize = nStrikeoutSize * fScale; + nSize2 = nSize / 2.; + nBSize = nSize * 2.; + n2Size = nBSize / 3.; + + mnStrikeoutSize = std::ceil(nSize); + mnStrikeoutOffset = std::ceil(nOffset); + + mnBStrikeoutSize = std::ceil(nBSize); + mnBStrikeoutOffset = std::round(nOffset - nSize2); + + mnDStrikeoutSize = std::ceil(n2Size); + mnDStrikeoutOffset1 = mnBStrikeoutOffset; + mnDStrikeoutOffset2 = mnBStrikeoutOffset + mnDStrikeoutSize * 2; + + return true; +} + +void FontMetricData::ImplInitTextLineSize( const OutputDevice* pDev ) +{ + mnBulletOffset = ( pDev->GetTextWidth( OUString( u' ' ) ) - pDev->GetTextWidth( OUString( u'\x00b7' ) ) ) >> 1 ; + + if (ImplInitTextLineSizeHarfBuzz(const_cast<LogicalFontInstance*>(pDev->GetFontInstance()))) + return; + + tools::Long nDescent = mnDescent; + if ( nDescent <= 0 ) + { + nDescent = mnAscent / 10; + if ( !nDescent ) + nDescent = 1; + } + + // #i55341# for some fonts it is not a good idea to calculate + // their text line metrics from the real font descent + // => work around this problem just for these fonts + if( 3*nDescent > mnAscent ) + nDescent = mnAscent / 3; + + tools::Long nLineHeight = ((nDescent*25)+50) / 100; + if ( !nLineHeight ) + nLineHeight = 1; + tools::Long nLineHeight2 = nLineHeight / 2; + if ( !nLineHeight2 ) + nLineHeight2 = 1; + + tools::Long nBLineHeight = ((nDescent*50)+50) / 100; + if ( nBLineHeight == nLineHeight ) + nBLineHeight++; + tools::Long nBLineHeight2 = nBLineHeight/2; + if ( !nBLineHeight2 ) + nBLineHeight2 = 1; + + tools::Long n2LineHeight = ((nDescent*16)+50) / 100; + if ( !n2LineHeight ) + n2LineHeight = 1; + tools::Long n2LineDY = n2LineHeight; + /* #117909# + * add some pixels to minimum double line distance on higher resolution devices + */ + tools::Long nMin2LineDY = 1 + pDev->GetDPIY()/150; + if ( n2LineDY < nMin2LineDY ) + n2LineDY = nMin2LineDY; + tools::Long n2LineDY2 = n2LineDY/2; + if ( !n2LineDY2 ) + n2LineDY2 = 1; + + const vcl::Font& rFont ( pDev->GetFont() ); + bool bCJKVertical = MsLangId::isCJK(rFont.GetLanguage()) && rFont.IsVertical(); + tools::Long nUnderlineOffset = bCJKVertical ? mnDescent : (mnDescent/2 + 1); + tools::Long nStrikeoutOffset = rFont.IsVertical() ? -((mnAscent - mnDescent) / 2) : -((mnAscent - mnIntLeading) / 3); + + mnUnderlineSize = nLineHeight; + mnUnderlineOffset = nUnderlineOffset - nLineHeight2; + + mnBUnderlineSize = nBLineHeight; + mnBUnderlineOffset = nUnderlineOffset - nBLineHeight2; + + mnDUnderlineSize = n2LineHeight; + mnDUnderlineOffset1 = nUnderlineOffset - n2LineDY2 - n2LineHeight; + mnDUnderlineOffset2 = mnDUnderlineOffset1 + n2LineDY + n2LineHeight; + + tools::Long nWCalcSize = mnDescent; + if ( nWCalcSize < 6 ) + { + if ( (nWCalcSize == 1) || (nWCalcSize == 2) ) + mnWUnderlineSize = nWCalcSize; + else + mnWUnderlineSize = 3; + } + else + mnWUnderlineSize = ((nWCalcSize*50)+50) / 100; + + + // Don't assume that wavelines are never placed below the descent, because for most fonts the waveline + // is drawn into the text + mnWUnderlineOffset = nUnderlineOffset; + + mnStrikeoutSize = nLineHeight; + mnStrikeoutOffset = nStrikeoutOffset - nLineHeight2; + + mnBStrikeoutSize = nBLineHeight; + mnBStrikeoutOffset = nStrikeoutOffset - nBLineHeight2; + + mnDStrikeoutSize = n2LineHeight; + mnDStrikeoutOffset1 = nStrikeoutOffset - n2LineDY2 - n2LineHeight; + mnDStrikeoutOffset2 = mnDStrikeoutOffset1 + n2LineDY + n2LineHeight; + +} + + +void FontMetricData::ImplInitAboveTextLineSize( const OutputDevice* pDev ) +{ + ImplInitTextLineSize(pDev); + + tools::Long nIntLeading = mnIntLeading; + // TODO: assess usage of nLeading below (changed in extleading CWS) + // if no leading is available, we assume 15% of the ascent + if ( nIntLeading <= 0 ) + { + nIntLeading = mnAscent*15/100; + if ( !nIntLeading ) + nIntLeading = 1; + } + + tools::Long nCeiling = -mnAscent; + + mnAboveUnderlineSize = mnUnderlineSize; + mnAboveUnderlineOffset = nCeiling + (nIntLeading - mnUnderlineSize + 1) / 2; + + mnAboveBUnderlineSize = mnBUnderlineSize; + mnAboveBUnderlineOffset = nCeiling + (nIntLeading - mnBUnderlineSize + 1) / 2; + + mnAboveDUnderlineSize = mnDUnderlineSize; + mnAboveDUnderlineOffset1 = nCeiling + (nIntLeading - 3*mnDUnderlineSize + 1) / 2; + mnAboveDUnderlineOffset2 = nCeiling + (nIntLeading + mnDUnderlineSize + 1) / 2; + + mnAboveWUnderlineSize = mnWUnderlineSize; + mnAboveWUnderlineOffset = nCeiling + (nIntLeading + 1) / 2; +} + +void FontMetricData::ImplInitFlags( const OutputDevice* pDev ) +{ + const vcl::Font& rFont ( pDev->GetFont() ); + bool bCentered = true; + if (MsLangId::isCJK(rFont.GetLanguage())) + { + tools::Rectangle aRect; + pDev->GetTextBoundRect( aRect, u"\x3001"_ustr ); // Fullwidth fullstop + const auto nH = rFont.GetFontSize().Height(); + const auto nB = aRect.Left(); + // Use 18.75% as a threshold to define a centered fullwidth fullstop. + // In general, nB/nH < 5% for most Japanese fonts. + bCentered = nB > (((nH >> 1)+nH)>>3); + } + SetFullstopCenteredFlag( bCentered ); +} + +bool FontMetricData::ShouldUseWinMetrics(int nAscent, int nDescent, int nTypoAscent, + int nTypoDescent, int nWinAscent, + int nWinDescent) const +{ + if (utl::ConfigManager::IsFuzzing()) + return false; + + OUString aFontIdentifier( + GetFamilyName() + "," + + OUString::number(nAscent) + "," + OUString::number(nDescent) + "," + + OUString::number(nTypoAscent) + "," + OUString::number(nTypoDescent) + "," + + OUString::number(nWinAscent) + "," + OUString::number(nWinDescent)); + + css::uno::Sequence<OUString> rWinMetricFontList( + officecfg::Office::Common::Misc::FontsUseWinMetrics::get()); + if (comphelper::findValue(rWinMetricFontList, aFontIdentifier) != -1) + { + SAL_INFO("vcl.gdi.fontmetric", "Using win metrics for: " << aFontIdentifier); + return true; + } + return false; +} + +// These are “private” HarfBuzz metrics tags, they are supported by not exposed +// in the public header. They are safe to use, HarfBuzz just does not want to +// advertise them. +constexpr auto ASCENT_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'a', 's', 'c')); +constexpr auto DESCENT_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'd', 's', 'c')); +constexpr auto LINEGAP_OS2 = static_cast<hb_ot_metrics_tag_t>(HB_TAG('O', 'l', 'g', 'p')); +constexpr auto ASCENT_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'a', 's', 'c')); +constexpr auto DESCENT_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'd', 's', 'c')); +constexpr auto LINEGAP_HHEA = static_cast<hb_ot_metrics_tag_t>(HB_TAG('H', 'l', 'g', 'p')); + +void FontMetricData::ImplCalcLineSpacing(LogicalFontInstance* pFontInstance) +{ + mnAscent = mnDescent = mnExtLeading = mnIntLeading = 0; + auto* pFace = pFontInstance->GetFontFace(); + auto* pHbFont = pFontInstance->GetHbFont(); + + double fScale = 0; + pFontInstance->GetScale(nullptr, &fScale); + double fAscent = 0, fDescent = 0, fExtLeading = 0; + + auto aFvar(pFace->GetRawFontData(HB_TAG('f', 'v', 'a', 'r'))); + if (!aFvar.empty()) + { + // This is a variable font, trust HarfBuzz to give us the right metrics + // and apply variations to them. + hb_position_t nAscent, nDescent, nLineGap; + if (hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_ASCENDER, &nAscent) + && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_DESCENDER, + &nDescent) + && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_LINE_GAP, + &nLineGap)) + { + fAscent = nAscent * fScale; + fDescent = -nDescent * fScale; + fExtLeading = nLineGap * fScale; + } + } + else + { + // This is not a variable font, we try to choose the best metrics + // ourselves for backward comparability: + // + // - hhea metrics should be used, since hhea is a mandatory font table + // and should always be present. + // - But if OS/2 is present, it should be used since it is mandatory in + // Windows. + // OS/2 has Typo and Win metrics, but the later was meant to control + // text clipping not line spacing and can be ridiculously large. + // Unfortunately many Windows application incorrectly use the Win + // metrics (thanks to GDI’s TEXTMETRIC) and old fonts might be + // designed with this in mind, so OpenType introduced a flag for + // fonts to indicate that they really want to use Typo metrics. So + // for best backward compatibility: + // - Use Win metrics if available. + // - Unless USE_TYPO_METRICS flag is set, in which case use Typo + // metrics. + + // Try hhea table first. + hb_position_t nAscent = 0, nDescent = 0, nLineGap = 0; + if (hb_ot_metrics_get_position(pHbFont, ASCENT_HHEA, &nAscent) + && hb_ot_metrics_get_position(pHbFont, DESCENT_HHEA, &nDescent) + && hb_ot_metrics_get_position(pHbFont, LINEGAP_HHEA, &nLineGap)) + { + // tdf#107605: Some fonts have weird values here, so check that + // ascender is +ve and descender is -ve as they normally should. + if (nAscent >= 0 && nDescent <= 0) + { + fAscent = nAscent * fScale; + fDescent = -nDescent * fScale; + fExtLeading = nLineGap * fScale; + } + } + + // But if OS/2 is present, prefer it. + hb_position_t nTypoAscent, nTypoDescent, nTypoLineGap, nWinAscent, nWinDescent; + if (hb_ot_metrics_get_position(pHbFont, ASCENT_OS2, &nTypoAscent) + && hb_ot_metrics_get_position(pHbFont, DESCENT_OS2, &nTypoDescent) + && hb_ot_metrics_get_position(pHbFont, LINEGAP_OS2, &nTypoLineGap) + && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_ASCENT, + &nWinAscent) + && hb_ot_metrics_get_position(pHbFont, HB_OT_METRICS_TAG_HORIZONTAL_CLIPPING_DESCENT, + &nWinDescent)) + { + if ((fAscent == 0.0 && fDescent == 0.0) + || ShouldUseWinMetrics(nAscent, nDescent, nTypoAscent, nTypoDescent, nWinAscent, + nWinDescent)) + { + fAscent = nWinAscent * fScale; + fDescent = nWinDescent * fScale; + fExtLeading = 0; + } + + bool bUseTypoMetrics = false; + { + // TODO: Use HarfBuzz API instead of raw access + // https://github.com/harfbuzz/harfbuzz/issues/1920 + sal_uInt16 fsSelection = 0; + auto aOS2(pFace->GetRawFontData(HB_TAG('O', 'S', '/', '2'))); + SvMemoryStream aStream(const_cast<uint8_t*>(aOS2.data()), aOS2.size(), + StreamMode::READ); + // Font data are big endian. + aStream.SetEndian(SvStreamEndian::BIG); + if (aStream.Seek(vcl::OS2_fsSelection_offset) == vcl::OS2_fsSelection_offset) + aStream.ReadUInt16(fsSelection); + bUseTypoMetrics = fsSelection & (1 << 7); + } + if (bUseTypoMetrics && nTypoAscent >= 0 && nTypoDescent <= 0) + { + fAscent = nTypoAscent * fScale; + fDescent = -nTypoDescent * fScale; + fExtLeading = nTypoLineGap * fScale; + } + } + } + + mnAscent = round(fAscent); + mnDescent = round(fDescent); + mnExtLeading = round(fExtLeading); + + if (mnAscent || mnDescent) + mnIntLeading = mnAscent + mnDescent - mnHeight; +} + +void FontMetricData::ImplInitBaselines(LogicalFontInstance *pFontInstance) +{ + hb_font_t* pHbFont = pFontInstance->GetHbFont(); + double fScale = 0; + pFontInstance->GetScale(nullptr, &fScale); + hb_position_t nBaseline = 0; + + if (hb_ot_layout_get_baseline(pHbFont, + HB_OT_LAYOUT_BASELINE_TAG_HANGING, + HB_DIRECTION_INVALID, + HB_SCRIPT_UNKNOWN, + HB_TAG_NONE, + &nBaseline)) + { + mnHangingBaseline = nBaseline * fScale; + } + else + { + mnHangingBaseline = 0; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |