d40d3b9b23d7502bf16e240a60f4c310b28c16fd
[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 "FontTaggedSettings.h"
35 #include "Timer.h"
36 #include <array>
37 #include <limits.h>
38 #include <wtf/Forward.h>
39 #include <wtf/ListHashSet.h>
40 #include <wtf/RefPtr.h>
41 #include <wtf/Vector.h>
42 #include <wtf/WorkQueue.h>
43 #include <wtf/text/AtomicStringHash.h>
44 #include <wtf/text/WTFString.h>
45
46 #if PLATFORM(COCOA)
47 #include "FontCacheCoreText.h"
48 #endif
49
50 #if OS(WINDOWS)
51 #include <windows.h>
52 #include <objidl.h>
53 #include <mlang.h>
54 #endif
55
56 namespace WebCore {
57
58 class FontCascade;
59 class FontPlatformData;
60 class FontSelector;
61 class OpenTypeVerticalData;
62 class Font;
63
64 #if PLATFORM(WIN)
65 #if USE(IMLANG_FONT_LINK2)
66 typedef IMLangFontLink2 IMLangFontLinkType;
67 #else
68 typedef IMLangFontLink IMLangFontLinkType;
69 #endif
70 #endif
71
72 // This key contains the FontDescription fields other than family that matter when fetching FontDatas (platform fonts).
73 struct FontDescriptionKey {
74     FontDescriptionKey() = default;
75
76     FontDescriptionKey(const FontDescription& description)
77         : m_size(description.computedPixelSize())
78         , m_fontSelectionRequest(description.fontSelectionRequest())
79         , m_flags(makeFlagsKey(description))
80         , m_locale(description.locale())
81         , m_featureSettings(description.featureSettings())
82 #if ENABLE(VARIATION_FONTS)
83         , m_variationSettings(description.variationSettings())
84 #endif
85     { }
86
87     explicit FontDescriptionKey(WTF::HashTableDeletedValueType)
88         : m_size(cHashTableDeletedSize)
89     { }
90
91     bool operator==(const FontDescriptionKey& other) const
92     {
93         return m_size == other.m_size
94             && m_fontSelectionRequest == other.m_fontSelectionRequest
95             && m_flags == other.m_flags
96             && m_locale == other.m_locale
97 #if ENABLE(VARIATION_FONTS)
98             && m_variationSettings == other.m_variationSettings
99 #endif
100             && m_featureSettings == other.m_featureSettings;
101     }
102
103     bool operator!=(const FontDescriptionKey& other) const
104     {
105         return !(*this == other);
106     }
107
108     bool isHashTableDeletedValue() const { return m_size == cHashTableDeletedSize; }
109
110     inline unsigned computeHash() const
111     {
112         IntegerHasher hasher;
113         hasher.add(m_size);
114         hasher.add(m_fontSelectionRequest.weight);
115         hasher.add(m_fontSelectionRequest.width);
116         hasher.add(m_fontSelectionRequest.slope.value_or(normalItalicValue()));
117         hasher.add(m_locale.existingHash());
118         for (unsigned flagItem : m_flags)
119             hasher.add(flagItem);
120         hasher.add(m_featureSettings.hash());
121 #if ENABLE(VARIATION_FONTS)
122         hasher.add(m_variationSettings.hash());
123 #endif
124         return hasher.hash();
125     }
126
127 private:
128     static std::array<unsigned, 2> makeFlagsKey(const FontDescription& description)
129     {
130         unsigned first = static_cast<unsigned>(description.script()) << 14
131             | static_cast<unsigned>(description.shouldAllowUserInstalledFonts()) << 13
132             | static_cast<unsigned>(description.fontStyleAxis() == FontStyleAxis::slnt) << 12
133             | static_cast<unsigned>(description.opticalSizing()) << 11
134             | static_cast<unsigned>(description.textRenderingMode()) << 9
135             | static_cast<unsigned>(description.fontSynthesis()) << 6
136             | static_cast<unsigned>(description.widthVariant()) << 4
137             | static_cast<unsigned>(description.nonCJKGlyphOrientation()) << 3
138             | static_cast<unsigned>(description.orientation()) << 2
139             | static_cast<unsigned>(description.renderingMode());
140         unsigned second = static_cast<unsigned>(description.variantEastAsianRuby()) << 27
141             | static_cast<unsigned>(description.variantEastAsianWidth()) << 25
142             | static_cast<unsigned>(description.variantEastAsianVariant()) << 22
143             | static_cast<unsigned>(description.variantAlternates()) << 21
144             | static_cast<unsigned>(description.variantNumericSlashedZero()) << 20
145             | static_cast<unsigned>(description.variantNumericOrdinal()) << 19
146             | static_cast<unsigned>(description.variantNumericFraction()) << 17
147             | static_cast<unsigned>(description.variantNumericSpacing()) << 15
148             | static_cast<unsigned>(description.variantNumericFigure()) << 13
149             | static_cast<unsigned>(description.variantCaps()) << 10
150             | static_cast<unsigned>(description.variantPosition()) << 8
151             | static_cast<unsigned>(description.variantContextualAlternates()) << 6
152             | static_cast<unsigned>(description.variantHistoricalLigatures()) << 4
153             | static_cast<unsigned>(description.variantDiscretionaryLigatures()) << 2
154             | static_cast<unsigned>(description.variantCommonLigatures());
155         return {{ first, second }};
156     }
157
158     static const unsigned cHashTableDeletedSize = 0xFFFFFFFFU;
159
160     // FontCascade::locale() is explicitly not included in this struct.
161     unsigned m_size { 0 };
162     FontSelectionRequest m_fontSelectionRequest;
163     std::array<unsigned, 2> m_flags {{ 0, 0 }};
164     AtomicString m_locale;
165     FontFeatureSettings m_featureSettings;
166 #if ENABLE(VARIATION_FONTS)
167     FontVariationSettings m_variationSettings;
168 #endif
169 };
170
171 struct FontDescriptionKeyHash {
172     static unsigned hash(const FontDescriptionKey& key)
173     {
174         return key.computeHash();
175     }
176
177     static bool equal(const FontDescriptionKey& a, const FontDescriptionKey& b)
178     {
179         return a == b;
180     }
181
182     static const bool safeToCompareToEmptyOrDeleted = true;
183 };
184
185 class FontCache {
186     friend class WTF::NeverDestroyed<FontCache>;
187
188     WTF_MAKE_NONCOPYABLE(FontCache); WTF_MAKE_FAST_ALLOCATED;
189 public:
190     WEBCORE_EXPORT static FontCache& singleton();
191
192     // These methods are implemented by the platform.
193     RefPtr<Font> systemFallbackForCharacters(const FontDescription&, const Font* originalFontData, bool isPlatformFont, const UChar* characters, unsigned length);
194     Vector<String> systemFontFamilies();
195     void platformInit();
196
197 #if PLATFORM(COCOA)
198     WEBCORE_EXPORT static void setFontWhitelist(const Vector<String>&);
199 #endif
200 #if PLATFORM(WIN)
201     IMLangFontLinkType* getFontLinkInterface();
202     static void comInitialize();
203     static void comUninitialize();
204     static IMultiLanguage* getMultiLanguageInterface();
205 #endif
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     struct PrewarmInformation {
241         Vector<String> seenFamilies;
242         Vector<String> fontNamesRequiringSystemFallback;
243
244         bool isEmpty() const;
245         PrewarmInformation isolatedCopy() const;
246
247         template<class Encoder> void encode(Encoder&) const;
248         template<class Decoder> static Optional<PrewarmInformation> decode(Decoder&);
249     };
250     PrewarmInformation collectPrewarmInformation() const;
251     void prewarm(const PrewarmInformation&);
252
253 private:
254     FontCache();
255     ~FontCache() = delete;
256
257     WEBCORE_EXPORT void purgeInactiveFontDataIfNeeded();
258
259     // FIXME: This method should eventually be removed.
260     FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, FontSelectionSpecifiedCapabilities fontFaceCapabilities = { }, bool checkingAlternateName = false);
261
262     // These methods are implemented by each platform.
263 #if PLATFORM(COCOA)
264     FontPlatformData* getCustomFallbackFont(const UInt32, const FontDescription&);
265 #endif
266     WEBCORE_EXPORT std::unique_ptr<FontPlatformData> createFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings, FontSelectionSpecifiedCapabilities fontFaceCapabilities);
267     
268     static const AtomicString& alternateFamilyName(const AtomicString&);
269     static const AtomicString& platformAlternateFamilyName(const AtomicString&);
270
271     Timer m_purgeTimer;
272     
273     bool m_shouldMockBoldSystemFontForAccessibility { false };
274
275 #if PLATFORM(COCOA)
276     ListHashSet<String> m_seenFamiliesForPrewarming;
277     ListHashSet<String> m_fontNamesRequiringSystemFallbackForPrewarming;
278     RefPtr<WorkQueue> m_prewarmQueue;
279
280     friend class ComplexTextController;
281 #endif
282     friend class Font;
283 };
284
285 inline std::unique_ptr<FontPlatformData> FontCache::createFontPlatformDataForTesting(const FontDescription& fontDescription, const AtomicString& family)
286 {
287     return createFontPlatformData(fontDescription, family, nullptr, nullptr, { });
288 }
289
290 #if !PLATFORM(COCOA)
291
292 inline void FontCache::platformPurgeInactiveFontData()
293 {
294 }
295
296 #endif
297
298
299 inline bool FontCache::PrewarmInformation::isEmpty() const
300 {
301     return seenFamilies.isEmpty() && fontNamesRequiringSystemFallback.isEmpty();
302 }
303
304 inline FontCache::PrewarmInformation FontCache::PrewarmInformation::isolatedCopy() const
305 {
306     return { seenFamilies.isolatedCopy(), fontNamesRequiringSystemFallback.isolatedCopy() };
307 }
308
309 template<class Encoder>
310 void FontCache::PrewarmInformation::encode(Encoder& encoder) const
311 {
312     encoder << seenFamilies;
313     encoder << fontNamesRequiringSystemFallback;
314 }
315
316 template<class Decoder>
317 Optional<FontCache::PrewarmInformation> FontCache::PrewarmInformation::decode(Decoder& decoder)
318 {
319     PrewarmInformation prewarmInformation;
320     if (!decoder.decode(prewarmInformation.seenFamilies))
321         return { };
322     if (!decoder.decode(prewarmInformation.fontNamesRequiringSystemFallback))
323         return { };
324
325     return prewarmInformation;
326 }
327
328 }