Implement font-optical-sizing
[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_featureSettings(description.featureSettings())
78 #if ENABLE(VARIATION_FONTS)
79         , m_variationSettings(description.variationSettings())
80 #endif
81     { }
82
83     explicit FontDescriptionKey(WTF::HashTableDeletedValueType)
84         : m_size(cHashTableDeletedSize)
85     { }
86
87     bool operator==(const FontDescriptionKey& other) const
88     {
89         return m_size == other.m_size
90             && m_fontSelectionRequest == other.m_fontSelectionRequest
91             && m_flags == other.m_flags
92 #if ENABLE(VARIATION_FONTS)
93             && m_variationSettings == other.m_variationSettings
94 #endif
95             && m_featureSettings == other.m_featureSettings;
96     }
97
98     bool operator!=(const FontDescriptionKey& other) const
99     {
100         return !(*this == other);
101     }
102
103     bool isHashTableDeletedValue() const { return m_size == cHashTableDeletedSize; }
104
105     inline unsigned computeHash() const
106     {
107         IntegerHasher hasher;
108         hasher.add(m_size);
109         hasher.add(m_fontSelectionRequest.weight);
110         hasher.add(m_fontSelectionRequest.width);
111         hasher.add(m_fontSelectionRequest.slope);
112         for (unsigned flagItem : m_flags)
113             hasher.add(flagItem);
114         hasher.add(m_featureSettings.hash());
115 #if ENABLE(VARIATION_FONTS)
116         hasher.add(m_variationSettings.hash());
117 #endif
118         return hasher.hash();
119     }
120
121 private:
122     static std::array<unsigned, 2> makeFlagsKey(const FontDescription& description)
123     {
124         static_assert(USCRIPT_CODE_LIMIT < 0x1000, "Script code must fit in an unsigned along with the other flags");
125         unsigned first = static_cast<unsigned>(description.script()) << 12
126             | static_cast<unsigned>(description.opticalSizing()) << 11
127             | static_cast<unsigned>(description.textRenderingMode()) << 9
128             | static_cast<unsigned>(description.fontSynthesis()) << 6
129             | static_cast<unsigned>(description.widthVariant()) << 4
130             | static_cast<unsigned>(description.nonCJKGlyphOrientation()) << 3
131             | static_cast<unsigned>(description.orientation()) << 2
132             | static_cast<unsigned>(description.renderingMode());
133         unsigned second = static_cast<unsigned>(description.variantEastAsianRuby()) << 27
134             | static_cast<unsigned>(description.variantEastAsianWidth()) << 25
135             | static_cast<unsigned>(description.variantEastAsianVariant()) << 22
136             | static_cast<unsigned>(description.variantAlternates()) << 21
137             | static_cast<unsigned>(description.variantNumericSlashedZero()) << 20
138             | static_cast<unsigned>(description.variantNumericOrdinal()) << 19
139             | static_cast<unsigned>(description.variantNumericFraction()) << 17
140             | static_cast<unsigned>(description.variantNumericSpacing()) << 15
141             | static_cast<unsigned>(description.variantNumericFigure()) << 13
142             | static_cast<unsigned>(description.variantCaps()) << 10
143             | static_cast<unsigned>(description.variantPosition()) << 8
144             | static_cast<unsigned>(description.variantContextualAlternates()) << 6
145             | static_cast<unsigned>(description.variantHistoricalLigatures()) << 4
146             | static_cast<unsigned>(description.variantDiscretionaryLigatures()) << 2
147             | static_cast<unsigned>(description.variantCommonLigatures());
148         return {{ first, second }};
149     }
150
151     static const unsigned cHashTableDeletedSize = 0xFFFFFFFFU;
152
153     // FontCascade::locale() is explicitly not included in this struct.
154     unsigned m_size { 0 };
155     FontSelectionRequest m_fontSelectionRequest;
156     std::array<unsigned, 2> m_flags {{ 0, 0 }};
157     FontFeatureSettings m_featureSettings;
158 #if ENABLE(VARIATION_FONTS)
159     FontVariationSettings m_variationSettings;
160 #endif
161 };
162
163 struct FontDescriptionKeyHash {
164     static unsigned hash(const FontDescriptionKey& key)
165     {
166         return key.computeHash();
167     }
168
169     static bool equal(const FontDescriptionKey& a, const FontDescriptionKey& b)
170     {
171         return a == b;
172     }
173
174     static const bool safeToCompareToEmptyOrDeleted = true;
175 };
176
177 class FontCache {
178     friend class WTF::NeverDestroyed<FontCache>;
179
180     WTF_MAKE_NONCOPYABLE(FontCache); WTF_MAKE_FAST_ALLOCATED;
181 public:
182     WEBCORE_EXPORT static FontCache& singleton();
183
184     // These methods are implemented by the platform.
185     RefPtr<Font> systemFallbackForCharacters(const FontDescription&, const Font* originalFontData, bool isPlatformFont, const UChar* characters, unsigned length);
186     Vector<String> systemFontFamilies();
187     void platformInit();
188
189 #if PLATFORM(COCOA)
190     WEBCORE_EXPORT static void setFontWhitelist(const Vector<String>&);
191 #endif
192 #if PLATFORM(WIN)
193     IMLangFontLinkType* getFontLinkInterface();
194     static void comInitialize();
195     static void comUninitialize();
196     static IMultiLanguage* getMultiLanguageInterface();
197 #endif
198
199     // This function exists so CSSFontSelector can have a unified notion of preinstalled fonts and @font-face.
200     // It comes into play when you create an @font-face which shares a family name as a preinstalled font.
201     Vector<FontSelectionCapabilities> getFontSelectionCapabilitiesInFamily(const AtomicString&);
202
203     WEBCORE_EXPORT RefPtr<Font> fontForFamily(const FontDescription&, const AtomicString&, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, bool checkingAlternateName = false);
204     WEBCORE_EXPORT Ref<Font> lastResortFallbackFont(const FontDescription&);
205     Ref<Font> lastResortFallbackFontForEveryCharacter(const FontDescription&);
206     WEBCORE_EXPORT Ref<Font> fontForPlatformData(const FontPlatformData&);
207     RefPtr<Font> similarFont(const FontDescription&, const AtomicString& family);
208
209     void addClient(FontSelector&);
210     void removeClient(FontSelector&);
211
212     unsigned short generation();
213     WEBCORE_EXPORT void invalidate();
214
215     WEBCORE_EXPORT size_t fontCount();
216     WEBCORE_EXPORT size_t inactiveFontCount();
217     WEBCORE_EXPORT void purgeInactiveFontData(unsigned count = UINT_MAX);
218     void platformPurgeInactiveFontData();
219
220 #if PLATFORM(WIN)
221     RefPtr<Font> fontFromDescriptionAndLogFont(const FontDescription&, const LOGFONT&, AtomicString& outFontFamilyName);
222 #endif
223
224 #if ENABLE(OPENTYPE_VERTICAL)
225     RefPtr<OpenTypeVerticalData> verticalData(const FontPlatformData&);
226 #endif
227
228     std::unique_ptr<FontPlatformData> createFontPlatformDataForTesting(const FontDescription&, const AtomicString& family);
229
230 private:
231     FontCache();
232     ~FontCache() = delete;
233
234     WEBCORE_EXPORT void purgeInactiveFontDataIfNeeded();
235
236     // FIXME: This method should eventually be removed.
237     FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, bool checkingAlternateName = false);
238
239     // These methods are implemented by each platform.
240 #if PLATFORM(COCOA)
241     FontPlatformData* getCustomFallbackFont(const UInt32, const FontDescription&);
242 #endif
243     WEBCORE_EXPORT std::unique_ptr<FontPlatformData> createFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings);
244     
245     static const AtomicString& alternateFamilyName(const AtomicString&);
246     static const AtomicString& platformAlternateFamilyName(const AtomicString&);
247
248     Timer m_purgeTimer;
249
250 #if PLATFORM(COCOA)
251     friend class ComplexTextController;
252 #endif
253     friend class Font;
254 };
255
256 inline std::unique_ptr<FontPlatformData> FontCache::createFontPlatformDataForTesting(const FontDescription& fontDescription, const AtomicString& family)
257 {
258     return createFontPlatformData(fontDescription, family, nullptr, nullptr);
259 }
260
261 #if PLATFORM(COCOA)
262
263 struct SynthesisPair {
264     SynthesisPair(bool needsSyntheticBold, bool needsSyntheticOblique)
265         : needsSyntheticBold(needsSyntheticBold)
266         , needsSyntheticOblique(needsSyntheticOblique)
267     {
268     }
269
270     std::pair<bool, bool> boldObliquePair() const
271     {
272         return std::make_pair(needsSyntheticBold, needsSyntheticOblique);
273     }
274
275     bool needsSyntheticBold;
276     bool needsSyntheticOblique;
277 };
278
279 RetainPtr<CTFontRef> preparePlatformFont(CTFontRef, TextRenderingMode, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings, const FontFeatureSettings& features, const FontVariantSettings&, FontSelectionRequest, const FontVariationSettings&, FontOpticalSizing, float size);
280 SynthesisPair computeNecessarySynthesis(CTFontRef, const FontDescription&, bool isPlatformFont = false);
281 RetainPtr<CTFontRef> platformFontWithFamilySpecialCase(const AtomicString& family, FontSelectionRequest, float size);
282 RetainPtr<CTFontRef> platformFontWithFamily(const AtomicString& family, FontSelectionRequest, TextRenderingMode, float size);
283 bool requiresCustomFallbackFont(UChar32 character);
284 FontSelectionCapabilities capabilitiesForFontDescriptor(CTFontDescriptorRef);
285
286 #else
287
288 inline void FontCache::platformPurgeInactiveFontData()
289 {
290 }
291
292 #endif
293
294 }