[Cocoa] Add SPI to disallow user-installed fonts
[WebKit-https.git] / Source / WebCore / platform / graphics / FontCache.h
1 /*
2  * Copyright (C) 2006, 2008 Apple Inc.  All rights reserved.
3  * Copyright (C) 2007-2008 Torch Mobile, Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #pragma once
31
32 #include "FontDescription.h"
33 #include "FontPlatformData.h"
34 #include "Timer.h"
35 #include <array>
36 #include <limits.h>
37 #include <wtf/Forward.h>
38 #include <wtf/RefPtr.h>
39 #include <wtf/Vector.h>
40 #include <wtf/text/AtomicStringHash.h>
41 #include <wtf/text/WTFString.h>
42
43 #if PLATFORM(COCOA)
44 #include <CoreText/CTFont.h>
45 #endif
46
47 #if OS(WINDOWS)
48 #include <windows.h>
49 #include <objidl.h>
50 #include <mlang.h>
51 #endif
52
53 namespace WebCore {
54
55 class FontCascade;
56 class FontPlatformData;
57 class FontSelector;
58 class OpenTypeVerticalData;
59 class Font;
60
61 #if PLATFORM(WIN)
62 #if USE(IMLANG_FONT_LINK2)
63 typedef IMLangFontLink2 IMLangFontLinkType;
64 #else
65 typedef IMLangFontLink IMLangFontLinkType;
66 #endif
67 #endif
68
69 // This key contains the FontDescription fields other than family that matter when fetching FontDatas (platform fonts).
70 struct FontDescriptionKey {
71     FontDescriptionKey() = default;
72
73     FontDescriptionKey(const FontDescription& description)
74         : m_size(description.computedPixelSize())
75         , m_fontSelectionRequest(description.fontSelectionRequest())
76         , m_flags(makeFlagsKey(description))
77         , m_locale(description.locale())
78         , m_featureSettings(description.featureSettings())
79 #if ENABLE(VARIATION_FONTS)
80         , m_variationSettings(description.variationSettings())
81 #endif
82     { }
83
84     explicit FontDescriptionKey(WTF::HashTableDeletedValueType)
85         : m_size(cHashTableDeletedSize)
86     { }
87
88     bool operator==(const FontDescriptionKey& other) const
89     {
90         return m_size == other.m_size
91             && m_fontSelectionRequest == other.m_fontSelectionRequest
92             && m_flags == other.m_flags
93             && m_locale == other.m_locale
94 #if ENABLE(VARIATION_FONTS)
95             && m_variationSettings == other.m_variationSettings
96 #endif
97             && m_featureSettings == other.m_featureSettings;
98     }
99
100     bool operator!=(const FontDescriptionKey& other) const
101     {
102         return !(*this == other);
103     }
104
105     bool isHashTableDeletedValue() const { return m_size == cHashTableDeletedSize; }
106
107     inline unsigned computeHash() const
108     {
109         IntegerHasher hasher;
110         hasher.add(m_size);
111         hasher.add(m_fontSelectionRequest.weight);
112         hasher.add(m_fontSelectionRequest.width);
113         hasher.add(m_fontSelectionRequest.slope);
114         hasher.add(m_locale.existingHash());
115         for (unsigned flagItem : m_flags)
116             hasher.add(flagItem);
117         hasher.add(m_featureSettings.hash());
118 #if ENABLE(VARIATION_FONTS)
119         hasher.add(m_variationSettings.hash());
120 #endif
121         return hasher.hash();
122     }
123
124 private:
125     static std::array<unsigned, 2> makeFlagsKey(const FontDescription& description)
126     {
127         unsigned first = static_cast<unsigned>(description.script()) << 13
128             | static_cast<unsigned>(description.fontStyleAxis() == FontStyleAxis::slnt) << 12
129             | static_cast<unsigned>(description.opticalSizing()) << 11
130             | static_cast<unsigned>(description.textRenderingMode()) << 9
131             | static_cast<unsigned>(description.fontSynthesis()) << 6
132             | static_cast<unsigned>(description.widthVariant()) << 4
133             | static_cast<unsigned>(description.nonCJKGlyphOrientation()) << 3
134             | static_cast<unsigned>(description.orientation()) << 2
135             | static_cast<unsigned>(description.renderingMode());
136         unsigned second = static_cast<unsigned>(description.variantEastAsianRuby()) << 27
137             | static_cast<unsigned>(description.variantEastAsianWidth()) << 25
138             | static_cast<unsigned>(description.variantEastAsianVariant()) << 22
139             | static_cast<unsigned>(description.variantAlternates()) << 21
140             | static_cast<unsigned>(description.variantNumericSlashedZero()) << 20
141             | static_cast<unsigned>(description.variantNumericOrdinal()) << 19
142             | static_cast<unsigned>(description.variantNumericFraction()) << 17
143             | static_cast<unsigned>(description.variantNumericSpacing()) << 15
144             | static_cast<unsigned>(description.variantNumericFigure()) << 13
145             | static_cast<unsigned>(description.variantCaps()) << 10
146             | static_cast<unsigned>(description.variantPosition()) << 8
147             | static_cast<unsigned>(description.variantContextualAlternates()) << 6
148             | static_cast<unsigned>(description.variantHistoricalLigatures()) << 4
149             | static_cast<unsigned>(description.variantDiscretionaryLigatures()) << 2
150             | static_cast<unsigned>(description.variantCommonLigatures());
151         return {{ first, second }};
152     }
153
154     static const unsigned cHashTableDeletedSize = 0xFFFFFFFFU;
155
156     // FontCascade::locale() is explicitly not included in this struct.
157     unsigned m_size { 0 };
158     FontSelectionRequest m_fontSelectionRequest;
159     std::array<unsigned, 2> m_flags {{ 0, 0 }};
160     AtomicString m_locale;
161     FontFeatureSettings m_featureSettings;
162 #if ENABLE(VARIATION_FONTS)
163     FontVariationSettings m_variationSettings;
164 #endif
165 };
166
167 struct FontDescriptionKeyHash {
168     static unsigned hash(const FontDescriptionKey& key)
169     {
170         return key.computeHash();
171     }
172
173     static bool equal(const FontDescriptionKey& a, const FontDescriptionKey& b)
174     {
175         return a == b;
176     }
177
178     static const bool safeToCompareToEmptyOrDeleted = true;
179 };
180
181 class FontCache {
182     friend class WTF::NeverDestroyed<FontCache>;
183
184     WTF_MAKE_NONCOPYABLE(FontCache); WTF_MAKE_FAST_ALLOCATED;
185 public:
186     WEBCORE_EXPORT static FontCache& singleton();
187
188     // These methods are implemented by the platform.
189     RefPtr<Font> systemFallbackForCharacters(const FontDescription&, const Font* originalFontData, bool isPlatformFont, const UChar* characters, unsigned length);
190     Vector<String> systemFontFamilies();
191     void platformInit();
192
193 #if PLATFORM(COCOA)
194     WEBCORE_EXPORT static void setFontWhitelist(const Vector<String>&);
195 #endif
196 #if PLATFORM(WIN)
197     IMLangFontLinkType* getFontLinkInterface();
198     static void comInitialize();
199     static void comUninitialize();
200     static IMultiLanguage* getMultiLanguageInterface();
201 #endif
202
203     enum class AllowUserInstalledFonts {
204         Yes,
205         No
206     };
207     // This function exists so CSSFontSelector can have a unified notion of preinstalled fonts and @font-face.
208     // It comes into play when you create an @font-face which shares a family name as a preinstalled font.
209     Vector<FontSelectionCapabilities> getFontSelectionCapabilitiesInFamily(const AtomicString&, AllowUserInstalledFonts);
210
211     WEBCORE_EXPORT RefPtr<Font> fontForFamily(const FontDescription&, const AtomicString&, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, FontSelectionSpecifiedCapabilities fontFaceCapabilities = { }, bool checkingAlternateName = false);
212     WEBCORE_EXPORT Ref<Font> lastResortFallbackFont(const FontDescription&);
213     WEBCORE_EXPORT Ref<Font> fontForPlatformData(const FontPlatformData&);
214     RefPtr<Font> similarFont(const FontDescription&, const AtomicString& family);
215
216     void addClient(FontSelector&);
217     void removeClient(FontSelector&);
218
219     unsigned short generation();
220     WEBCORE_EXPORT void invalidate();
221
222     WEBCORE_EXPORT size_t fontCount();
223     WEBCORE_EXPORT size_t inactiveFontCount();
224     WEBCORE_EXPORT void purgeInactiveFontData(unsigned count = UINT_MAX);
225     void platformPurgeInactiveFontData();
226
227 #if PLATFORM(WIN)
228     RefPtr<Font> fontFromDescriptionAndLogFont(const FontDescription&, const LOGFONT&, AtomicString& outFontFamilyName);
229 #endif
230
231 #if ENABLE(OPENTYPE_VERTICAL)
232     RefPtr<OpenTypeVerticalData> verticalData(const FontPlatformData&);
233 #endif
234
235     std::unique_ptr<FontPlatformData> createFontPlatformDataForTesting(const FontDescription&, const AtomicString& family);
236     
237     bool shouldMockBoldSystemFontForAccessibility() const { return m_shouldMockBoldSystemFontForAccessibility; }
238     void setShouldMockBoldSystemFontForAccessibility(bool shouldMockBoldSystemFontForAccessibility) { m_shouldMockBoldSystemFontForAccessibility = shouldMockBoldSystemFontForAccessibility; }
239
240 private:
241     FontCache();
242     ~FontCache() = delete;
243
244     WEBCORE_EXPORT void purgeInactiveFontDataIfNeeded();
245
246     // FIXME: This method should eventually be removed.
247     FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, FontSelectionSpecifiedCapabilities fontFaceCapabilities = { }, bool checkingAlternateName = false);
248
249     // These methods are implemented by each platform.
250 #if PLATFORM(COCOA)
251     FontPlatformData* getCustomFallbackFont(const UInt32, const FontDescription&);
252 #endif
253     WEBCORE_EXPORT std::unique_ptr<FontPlatformData> createFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings, FontSelectionSpecifiedCapabilities fontFaceCapabilities);
254     
255     static const AtomicString& alternateFamilyName(const AtomicString&);
256     static const AtomicString& platformAlternateFamilyName(const AtomicString&);
257
258     Timer m_purgeTimer;
259     
260     bool m_shouldMockBoldSystemFontForAccessibility { false };
261
262 #if PLATFORM(COCOA)
263     friend class ComplexTextController;
264 #endif
265     friend class Font;
266 };
267
268 inline std::unique_ptr<FontPlatformData> FontCache::createFontPlatformDataForTesting(const FontDescription& fontDescription, const AtomicString& family)
269 {
270     return createFontPlatformData(fontDescription, family, nullptr, nullptr, { });
271 }
272
273 #if PLATFORM(COCOA)
274
275 struct SynthesisPair {
276     SynthesisPair(bool needsSyntheticBold, bool needsSyntheticOblique)
277         : needsSyntheticBold(needsSyntheticBold)
278         , needsSyntheticOblique(needsSyntheticOblique)
279     {
280     }
281
282     std::pair<bool, bool> boldObliquePair() const
283     {
284         return std::make_pair(needsSyntheticBold, needsSyntheticOblique);
285     }
286
287     bool needsSyntheticBold;
288     bool needsSyntheticOblique;
289 };
290
291 RetainPtr<CTFontRef> preparePlatformFont(CTFontRef, const FontDescription&, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings, FontSelectionSpecifiedCapabilities fontFaceCapabilities, float size, bool applyWeightWidthSlopeVariations = true);
292 SynthesisPair computeNecessarySynthesis(CTFontRef, const FontDescription&, bool isPlatformFont = false);
293 RetainPtr<CTFontRef> platformFontWithFamilySpecialCase(const AtomicString& family, FontSelectionRequest, float size);
294 RetainPtr<CTFontRef> platformFontWithFamily(const AtomicString& family, FontSelectionRequest, TextRenderingMode, float size);
295 bool requiresCustomFallbackFont(UChar32 character);
296 FontSelectionCapabilities capabilitiesForFontDescriptor(CTFontDescriptorRef);
297
298 #else
299
300 inline void FontCache::platformPurgeInactiveFontData()
301 {
302 }
303
304 #endif
305
306 }