Use Optional::valueOr() instead of Optional::value_or()
[WebKit-https.git] / Source / WebCore / platform / graphics / FontCache.h
index e9bbfa3..b635a13 100644 (file)
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef FontCache_h
-#define FontCache_h
+#pragma once
 
 #include "FontDescription.h"
+#include "FontPlatformData.h"
+#include "FontTaggedSettings.h"
+#include "Timer.h"
+#include <array>
 #include <limits.h>
 #include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
+#include <wtf/ListHashSet.h>
 #include <wtf/RefPtr.h>
 #include <wtf/Vector.h>
+#include <wtf/WorkQueue.h>
+#include <wtf/text/AtomicStringHash.h>
 #include <wtf/text/WTFString.h>
 
-#if PLATFORM(IOS)
-#include <CoreText/CTFont.h>
+#if PLATFORM(COCOA)
+#include "FontCacheCoreText.h"
 #endif
 
 #if OS(WINDOWS)
 
 namespace WebCore {
 
-class Font;
+class FontCascade;
 class FontPlatformData;
-class FontData;
 class FontSelector;
-class OpenTypeMathData;
 class OpenTypeVerticalData;
-class SimpleFontData;
+class Font;
 
 #if PLATFORM(WIN)
 #if USE(IMLANG_FONT_LINK2)
@@ -67,63 +70,132 @@ typedef IMLangFontLink IMLangFontLinkType;
 #endif
 
 // This key contains the FontDescription fields other than family that matter when fetching FontDatas (platform fonts).
-struct FontDescriptionFontDataCacheKey {
-    explicit FontDescriptionFontDataCacheKey(unsigned size = 0)
-        : size(size)
-        , weight(0)
-        , flags(0)
+struct FontDescriptionKey {
+    FontDescriptionKey() = default;
+
+    FontDescriptionKey(const FontDescription& description)
+        : m_size(description.computedPixelSize())
+        , m_fontSelectionRequest(description.fontSelectionRequest())
+        , m_flags(makeFlagsKey(description))
+        , m_locale(description.locale())
+        , m_featureSettings(description.featureSettings())
+#if ENABLE(VARIATION_FONTS)
+        , m_variationSettings(description.variationSettings())
+#endif
     { }
-    FontDescriptionFontDataCacheKey(const FontDescription& description)
-        : size(description.computedPixelSize())
-        , weight(description.weight())
-        , flags(makeFlagKey(description))
+
+    explicit FontDescriptionKey(WTF::HashTableDeletedValueType)
+        : m_size(cHashTableDeletedSize)
     { }
-    static unsigned makeFlagKey(const FontDescription& description)
-    {
-        return static_cast<unsigned>(description.widthVariant()) << 4
-            | static_cast<unsigned>(description.orientation()) << 3
-            | static_cast<unsigned>(description.italic()) << 2
-            | static_cast<unsigned>(description.usePrinterFont()) << 1
-            | static_cast<unsigned>(description.renderingMode());
-    }
-    bool operator==(const FontDescriptionFontDataCacheKey& other) const
+
+    bool operator==(const FontDescriptionKey& other) const
     {
-        return size == other.size && weight == other.weight && flags == other.flags;
+        return m_size == other.m_size
+            && m_fontSelectionRequest == other.m_fontSelectionRequest
+            && m_flags == other.m_flags
+            && m_locale == other.m_locale
+#if ENABLE(VARIATION_FONTS)
+            && m_variationSettings == other.m_variationSettings
+#endif
+            && m_featureSettings == other.m_featureSettings;
     }
-    bool operator!=(const FontDescriptionFontDataCacheKey& other) const
+
+    bool operator!=(const FontDescriptionKey& other) const
     {
         return !(*this == other);
     }
+
+    bool isHashTableDeletedValue() const { return m_size == cHashTableDeletedSize; }
+
     inline unsigned computeHash() const
     {
-        return StringHasher::hashMemory<sizeof(FontDescriptionFontDataCacheKey)>(this);
+        IntegerHasher hasher;
+        hasher.add(m_size);
+        hasher.add(m_fontSelectionRequest.weight);
+        hasher.add(m_fontSelectionRequest.width);
+        hasher.add(m_fontSelectionRequest.slope.valueOr(normalItalicValue()));
+        hasher.add(m_locale.existingHash());
+        for (unsigned flagItem : m_flags)
+            hasher.add(flagItem);
+        hasher.add(m_featureSettings.hash());
+#if ENABLE(VARIATION_FONTS)
+        hasher.add(m_variationSettings.hash());
+#endif
+        return hasher.hash();
+    }
+
+private:
+    static std::array<unsigned, 2> makeFlagsKey(const FontDescription& description)
+    {
+        unsigned first = static_cast<unsigned>(description.script()) << 14
+            | static_cast<unsigned>(description.shouldAllowUserInstalledFonts()) << 13
+            | static_cast<unsigned>(description.fontStyleAxis() == FontStyleAxis::slnt) << 12
+            | static_cast<unsigned>(description.opticalSizing()) << 11
+            | static_cast<unsigned>(description.textRenderingMode()) << 9
+            | static_cast<unsigned>(description.fontSynthesis()) << 6
+            | static_cast<unsigned>(description.widthVariant()) << 4
+            | static_cast<unsigned>(description.nonCJKGlyphOrientation()) << 3
+            | static_cast<unsigned>(description.orientation()) << 2
+            | static_cast<unsigned>(description.renderingMode());
+        unsigned second = static_cast<unsigned>(description.variantEastAsianRuby()) << 27
+            | static_cast<unsigned>(description.variantEastAsianWidth()) << 25
+            | static_cast<unsigned>(description.variantEastAsianVariant()) << 22
+            | static_cast<unsigned>(description.variantAlternates()) << 21
+            | static_cast<unsigned>(description.variantNumericSlashedZero()) << 20
+            | static_cast<unsigned>(description.variantNumericOrdinal()) << 19
+            | static_cast<unsigned>(description.variantNumericFraction()) << 17
+            | static_cast<unsigned>(description.variantNumericSpacing()) << 15
+            | static_cast<unsigned>(description.variantNumericFigure()) << 13
+            | static_cast<unsigned>(description.variantCaps()) << 10
+            | static_cast<unsigned>(description.variantPosition()) << 8
+            | static_cast<unsigned>(description.variantContextualAlternates()) << 6
+            | static_cast<unsigned>(description.variantHistoricalLigatures()) << 4
+            | static_cast<unsigned>(description.variantDiscretionaryLigatures()) << 2
+            | static_cast<unsigned>(description.variantCommonLigatures());
+        return {{ first, second }};
     }
-    unsigned size;
-    unsigned weight;
-    unsigned flags;
+
+    static const unsigned cHashTableDeletedSize = 0xFFFFFFFFU;
+
+    // FontCascade::locale() is explicitly not included in this struct.
+    unsigned m_size { 0 };
+    FontSelectionRequest m_fontSelectionRequest;
+    std::array<unsigned, 2> m_flags {{ 0, 0 }};
+    AtomicString m_locale;
+    FontFeatureSettings m_featureSettings;
+#if ENABLE(VARIATION_FONTS)
+    FontVariationSettings m_variationSettings;
+#endif
+};
+
+struct FontDescriptionKeyHash {
+    static unsigned hash(const FontDescriptionKey& key)
+    {
+        return key.computeHash();
+    }
+
+    static bool equal(const FontDescriptionKey& a, const FontDescriptionKey& b)
+    {
+        return a == b;
+    }
+
+    static const bool safeToCompareToEmptyOrDeleted = true;
 };
 
 class FontCache {
-    friend class FontCachePurgePreventer;
     friend class WTF::NeverDestroyed<FontCache>;
 
     WTF_MAKE_NONCOPYABLE(FontCache); WTF_MAKE_FAST_ALLOCATED;
 public:
-    friend FontCache* fontCache();
+    WEBCORE_EXPORT static FontCache& singleton();
 
-    enum ShouldRetain { Retain, DoNotRetain };
-
-    PassRefPtr<FontData> getFontData(const FontDescription&, int& familyIndex, FontSelector*);
-    void releaseFontData(const SimpleFontData*);
-
-    // This method is implemented by the platform.
-    PassRefPtr<SimpleFontData> systemFallbackForCharacters(const FontDescription&, const SimpleFontData* originalFontData, bool isPlatformFont, const UChar* characters, int length);
-
-    // Also implemented by the platform.
+    // These methods are implemented by the platform.
+    RefPtr<Font> systemFallbackForCharacters(const FontDescription&, const Font* originalFontData, bool isPlatformFont, const UChar* characters, unsigned length);
+    Vector<String> systemFontFamilies();
     void platformInit();
 
-#if PLATFORM(IOS)
-    static float weightOfCTFont(CTFontRef);
+#if PLATFORM(COCOA)
+    WEBCORE_EXPORT static void setFontWhitelist(const Vector<String>&);
 #endif
 #if PLATFORM(WIN)
     IMLangFontLinkType* getFontLinkInterface();
@@ -132,87 +204,125 @@ public:
     static IMultiLanguage* getMultiLanguageInterface();
 #endif
 
-    void getTraitsInFamily(const AtomicString&, Vector<unsigned>&);
+    // This function exists so CSSFontSelector can have a unified notion of preinstalled fonts and @font-face.
+    // It comes into play when you create an @font-face which shares a family name as a preinstalled font.
+    Vector<FontSelectionCapabilities> getFontSelectionCapabilitiesInFamily(const AtomicString&, AllowUserInstalledFonts);
 
-    PassRefPtr<SimpleFontData> getCachedFontData(const FontDescription&, const AtomicString&, bool checkingAlternateName = false, ShouldRetain = Retain);
-    PassRefPtr<SimpleFontData> getLastResortFallbackFont(const FontDescription&, ShouldRetain = Retain);
-    SimpleFontData* getNonRetainedLastResortFallbackFont(const FontDescription&);
+    WEBCORE_EXPORT RefPtr<Font> fontForFamily(const FontDescription&, const AtomicString&, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, FontSelectionSpecifiedCapabilities fontFaceCapabilities = { }, bool checkingAlternateName = false);
+    WEBCORE_EXPORT Ref<Font> lastResortFallbackFont(const FontDescription&);
+    WEBCORE_EXPORT Ref<Font> fontForPlatformData(const FontPlatformData&);
+    RefPtr<Font> similarFont(const FontDescription&, const AtomicString& family);
 
-    void addClient(FontSelector*);
-    void removeClient(FontSelector*);
+    void addClient(FontSelector&);
+    void removeClient(FontSelector&);
 
     unsigned short generation();
-    void invalidate();
+    WEBCORE_EXPORT void invalidate();
 
-    size_t fontDataCount();
-    size_t inactiveFontDataCount();
-    void purgeInactiveFontData(int count = INT_MAX);
+    WEBCORE_EXPORT size_t fontCount();
+    WEBCORE_EXPORT size_t inactiveFontCount();
+    WEBCORE_EXPORT void purgeInactiveFontData(unsigned count = UINT_MAX);
+    void platformPurgeInactiveFontData();
 
 #if PLATFORM(WIN)
-    PassRefPtr<SimpleFontData> fontDataFromDescriptionAndLogFont(const FontDescription&, ShouldRetain, const LOGFONT&, AtomicString& outFontFamilyName);
+    RefPtr<Font> fontFromDescriptionAndLogFont(const FontDescription&, const LOGFONT&, AtomicString& outFontFamilyName);
 #endif
 
-    typedef AtomicString FontFileKey;
-    PassRefPtr<OpenTypeMathData> getMathData(const FontFileKey&, const FontPlatformData&);
 #if ENABLE(OPENTYPE_VERTICAL)
-    PassRefPtr<OpenTypeVerticalData> getVerticalData(const FontFileKey&, const FontPlatformData&);
+    RefPtr<OpenTypeVerticalData> verticalData(const FontPlatformData&);
 #endif
 
-    struct SimpleFontFamily {
-        String name;
-        bool isBold;
-        bool isItalic;
+    std::unique_ptr<FontPlatformData> createFontPlatformDataForTesting(const FontDescription&, const AtomicString& family);
+    
+    bool shouldMockBoldSystemFontForAccessibility() const { return m_shouldMockBoldSystemFontForAccessibility; }
+    void setShouldMockBoldSystemFontForAccessibility(bool shouldMockBoldSystemFontForAccessibility) { m_shouldMockBoldSystemFontForAccessibility = shouldMockBoldSystemFontForAccessibility; }
+
+    struct PrewarmInformation {
+        Vector<String> seenFamilies;
+        Vector<String> fontNamesRequiringSystemFallback;
+
+        bool isEmpty() const;
+        PrewarmInformation isolatedCopy() const;
+
+        template<class Encoder> void encode(Encoder&) const;
+        template<class Decoder> static Optional<PrewarmInformation> decode(Decoder&);
     };
-    static void getFontFamilyForCharacters(const UChar* characters, size_t numCharacters, const char* preferredLocale, SimpleFontFamily*);
+    PrewarmInformation collectPrewarmInformation() const;
+    void prewarm(const PrewarmInformation&);
 
 private:
     FontCache();
-    ~FontCache();
+    ~FontCache() = delete;
 
-    void disablePurging() { m_purgePreventCount++; }
-    void enablePurging()
-    {
-        ASSERT(m_purgePreventCount);
-        if (!--m_purgePreventCount)
-            purgeInactiveFontDataIfNeeded();
-    }
-
-    void purgeInactiveFontDataIfNeeded();
+    WEBCORE_EXPORT void purgeInactiveFontDataIfNeeded();
 
     // FIXME: This method should eventually be removed.
-    FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, bool checkingAlternateName = false);
+    FontPlatformData* getCachedFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures = nullptr, const FontVariantSettings* fontFaceVariantSettings = nullptr, FontSelectionSpecifiedCapabilities fontFaceCapabilities = { }, bool checkingAlternateName = false);
 
     // These methods are implemented by each platform.
-#if PLATFORM(IOS)
-    FontPlatformData* getCustomFallbackFont(const UInt32, const FontDescription&);
-    PassRefPtr<SimpleFontData> getSystemFontFallbackForCharacters(const FontDescription&, const SimpleFontData*, const UChar* characters, int length);
-#endif
-    PassOwnPtr<FontPlatformData> createFontPlatformData(const FontDescription&, const AtomicString& family);
 #if PLATFORM(COCOA)
-    PassRefPtr<SimpleFontData> similarFontPlatformData(const FontDescription&);
+    FontPlatformData* getCustomFallbackFont(const UInt32, const FontDescription&);
 #endif
+    WEBCORE_EXPORT std::unique_ptr<FontPlatformData> createFontPlatformData(const FontDescription&, const AtomicString& family, const FontFeatureSettings* fontFaceFeatures, const FontVariantSettings* fontFaceVariantSettings, FontSelectionSpecifiedCapabilities fontFaceCapabilities);
+    
+    static const AtomicString& alternateFamilyName(const AtomicString&);
+    static const AtomicString& platformAlternateFamilyName(const AtomicString&);
 
-    PassRefPtr<SimpleFontData> getCachedFontData(const FontPlatformData*, ShouldRetain = Retain);
-
-    // Don't purge if this count is > 0;
-    int m_purgePreventCount;
+    Timer m_purgeTimer;
+    
+    bool m_shouldMockBoldSystemFontForAccessibility { false };
 
 #if PLATFORM(COCOA)
+    ListHashSet<String> m_seenFamiliesForPrewarming;
+    ListHashSet<String> m_fontNamesRequiringSystemFallbackForPrewarming;
+    RefPtr<WorkQueue> m_prewarmQueue;
+
     friend class ComplexTextController;
 #endif
-    friend class SimpleFontData; // For getCachedFontData(const FontPlatformData*)
-    friend class FontGlyphs;
+    friend class Font;
 };
 
-// Get the global fontCache.
-FontCache* fontCache();
+inline std::unique_ptr<FontPlatformData> FontCache::createFontPlatformDataForTesting(const FontDescription& fontDescription, const AtomicString& family)
+{
+    return createFontPlatformData(fontDescription, family, nullptr, nullptr, { });
+}
 
-class FontCachePurgePreventer {
-public:
-    FontCachePurgePreventer() { fontCache()->disablePurging(); }
-    ~FontCachePurgePreventer() { fontCache()->enablePurging(); }
-};
+#if !PLATFORM(COCOA)
 
+inline void FontCache::platformPurgeInactiveFontData()
+{
 }
 
 #endif
+
+
+inline bool FontCache::PrewarmInformation::isEmpty() const
+{
+    return seenFamilies.isEmpty() && fontNamesRequiringSystemFallback.isEmpty();
+}
+
+inline FontCache::PrewarmInformation FontCache::PrewarmInformation::isolatedCopy() const
+{
+    return { seenFamilies.isolatedCopy(), fontNamesRequiringSystemFallback.isolatedCopy() };
+}
+
+template<class Encoder>
+void FontCache::PrewarmInformation::encode(Encoder& encoder) const
+{
+    encoder << seenFamilies;
+    encoder << fontNamesRequiringSystemFallback;
+}
+
+template<class Decoder>
+Optional<FontCache::PrewarmInformation> FontCache::PrewarmInformation::decode(Decoder& decoder)
+{
+    PrewarmInformation prewarmInformation;
+    if (!decoder.decode(prewarmInformation.seenFamilies))
+        return { };
+    if (!decoder.decode(prewarmInformation.fontNamesRequiringSystemFallback))
+        return { };
+
+    return prewarmInformation;
+}
+
+}