Replace WTF::move with WTFMove
[WebKit-https.git] / Source / WebCore / css / CSSFontSelector.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2011, 2013 Apple Inc. All rights reserved.
3  *           (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
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  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "CSSFontSelector.h"
29
30 #include "CachedFont.h"
31 #include "CSSFontFace.h"
32 #include "CSSFontFaceRule.h"
33 #include "CSSFontFaceSource.h"
34 #include "CSSFontFaceSrcValue.h"
35 #include "CSSFontFamily.h"
36 #include "CSSFontFeatureValue.h"
37 #include "CSSPrimitiveValue.h"
38 #include "CSSPrimitiveValueMappings.h"
39 #include "CSSPropertyNames.h"
40 #include "CSSSegmentedFontFace.h"
41 #include "CSSUnicodeRangeValue.h"
42 #include "CSSValueKeywords.h"
43 #include "CSSValueList.h"
44 #include "CachedResourceLoader.h"
45 #include "Document.h"
46 #include "Font.h"
47 #include "FontCache.h"
48 #include "FontVariantBuilder.h"
49 #include "Frame.h"
50 #include "FrameLoader.h"
51 #include "SVGFontFaceElement.h"
52 #include "SVGNames.h"
53 #include "Settings.h"
54 #include "StyleProperties.h"
55 #include "StyleResolver.h"
56 #include "StyleRule.h"
57 #include "WebKitFontFamilyNames.h"
58 #include <wtf/Ref.h>
59 #include <wtf/text/AtomicString.h>
60
61 namespace WebCore {
62
63 static unsigned fontSelectorId;
64
65 CSSFontSelector::CSSFontSelector(Document& document)
66     : m_document(&document)
67     , m_beginLoadingTimer(*this, &CSSFontSelector::beginLoadTimerFired)
68     , m_uniqueId(++fontSelectorId)
69     , m_version(0)
70 {
71     // FIXME: An old comment used to say there was no need to hold a reference to m_document
72     // because "we are guaranteed to be destroyed before the document". But there does not
73     // seem to be any such guarantee.
74
75     ASSERT(m_document);
76     FontCache::singleton().addClient(this);
77 }
78
79 CSSFontSelector::~CSSFontSelector()
80 {
81     clearDocument();
82     FontCache::singleton().removeClient(this);
83 }
84
85 bool CSSFontSelector::isEmpty() const
86 {
87     return m_fonts.isEmpty();
88 }
89
90 static Optional<FontTraitsMask> computeTraitsMask(const StyleProperties& style)
91 {
92     unsigned traitsMask = 0;
93
94     if (RefPtr<CSSValue> fontStyle = style.getPropertyCSSValue(CSSPropertyFontStyle)) {
95         if (!is<CSSPrimitiveValue>(*fontStyle))
96             return Nullopt;
97
98         switch (downcast<CSSPrimitiveValue>(*fontStyle).getValueID()) {
99         case CSSValueNormal:
100             traitsMask |= FontStyleNormalMask;
101             break;
102         case CSSValueItalic:
103         case CSSValueOblique:
104             traitsMask |= FontStyleItalicMask;
105             break;
106         default:
107             break;
108         }
109     } else
110         traitsMask |= FontStyleNormalMask;
111
112     if (RefPtr<CSSValue> fontWeight = style.getPropertyCSSValue(CSSPropertyFontWeight)) {
113         if (!is<CSSPrimitiveValue>(*fontWeight))
114             return Nullopt;
115
116         switch (downcast<CSSPrimitiveValue>(*fontWeight).getValueID()) {
117         case CSSValueBold:
118         case CSSValue700:
119             traitsMask |= FontWeight700Mask;
120             break;
121         case CSSValueNormal:
122         case CSSValue400:
123             traitsMask |= FontWeight400Mask;
124             break;
125         case CSSValue900:
126             traitsMask |= FontWeight900Mask;
127             break;
128         case CSSValue800:
129             traitsMask |= FontWeight800Mask;
130             break;
131         case CSSValue600:
132             traitsMask |= FontWeight600Mask;
133             break;
134         case CSSValue500:
135             traitsMask |= FontWeight500Mask;
136             break;
137         case CSSValue300:
138             traitsMask |= FontWeight300Mask;
139             break;
140         case CSSValue200:
141             traitsMask |= FontWeight200Mask;
142             break;
143         case CSSValue100:
144             traitsMask |= FontWeight100Mask;
145             break;
146         default:
147             break;
148         }
149     } else
150         traitsMask |= FontWeight400Mask;
151
152     return static_cast<FontTraitsMask>(traitsMask);
153 }
154
155 static Ref<CSSFontFace> createFontFace(CSSValueList& srcList, FontTraitsMask traitsMask, Document* document, const StyleRuleFontFace& fontFaceRule, bool isInitiatingElementInUserAgentShadowTree)
156 {
157     RefPtr<CSSFontFaceRule> rule;
158 #if ENABLE(FONT_LOAD_EVENTS)
159     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=112116 - This CSSFontFaceRule has no parent.
160     if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
161         rule = static_pointer_cast<CSSFontFaceRule>(fontFaceRule.createCSSOMWrapper());
162 #else
163     UNUSED_PARAM(fontFaceRule);
164 #endif
165     Ref<CSSFontFace> fontFace = CSSFontFace::create(traitsMask, WTFMove(rule));
166
167     int srcLength = srcList.length();
168
169     bool foundSVGFont = false;
170
171     for (int i = 0; i < srcLength; i++) {
172         // An item in the list either specifies a string (local font name) or a URL (remote font to download).
173         CSSFontFaceSrcValue& item = downcast<CSSFontFaceSrcValue>(*srcList.itemWithoutBoundsCheck(i));
174         std::unique_ptr<CSSFontFaceSource> source;
175
176 #if ENABLE(SVG_FONTS)
177         foundSVGFont = item.isSVGFontFaceSrc() || item.svgFontFaceElement();
178 #endif
179         if (!item.isLocal()) {
180             Settings* settings = document ? document->settings() : nullptr;
181             bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
182             if (allowDownloading && item.isSupportedFormat() && document) {
183                 CachedFont* cachedFont = item.cachedFont(document, foundSVGFont, isInitiatingElementInUserAgentShadowTree);
184                 if (cachedFont) {
185                     source = std::make_unique<CSSFontFaceSource>(item.resource(), cachedFont);
186 #if ENABLE(SVG_FONTS)
187                     if (foundSVGFont)
188                         source->setHasExternalSVGFont();
189 #endif
190                 }
191             }
192         } else {
193             source = std::make_unique<CSSFontFaceSource>(item.resource());
194         }
195
196         if (source) {
197 #if ENABLE(SVG_FONTS)
198             source->setSVGFontFaceElement(item.svgFontFaceElement());
199 #endif
200             fontFace->addSource(WTFMove(source));
201         }
202     }
203
204     return fontFace;
205 }
206
207 static String familyNameFromPrimitive(const CSSPrimitiveValue& value)
208 {
209     if (value.isFontFamily())
210         return value.fontFamily().familyName;
211     if (!value.isValueID())
212         return { };
213
214     // We need to use the raw text for all the generic family types, since @font-face is a way of actually
215     // defining what font to use for those types.
216     switch (value.getValueID()) {
217     case CSSValueSerif:
218         return serifFamily;
219     case CSSValueSansSerif:
220         return sansSerifFamily;
221     case CSSValueCursive:
222         return cursiveFamily;
223     case CSSValueFantasy:
224         return fantasyFamily;
225     case CSSValueMonospace:
226         return monospaceFamily;
227     case CSSValueWebkitPictograph:
228         return pictographFamily;
229     default:
230         return { };
231     }
232 }
233
234 static Vector<Ref<CSSFontFace>> constructFamilyFontFaces(const String& familyName, HashMap<String, Vector<Ref<CSSFontFace>>, CaseFoldingHash>& locallyInstalledFontFaces)
235 {
236     auto result = Vector<Ref<CSSFontFace>>();
237
238     ASSERT(!locallyInstalledFontFaces.contains(familyName));
239
240     Vector<FontTraitsMask> traitsMasks = FontCache::singleton().getTraitsInFamily(familyName);
241     if (!traitsMasks.isEmpty()) {
242         Vector<Ref<CSSFontFace>> faces = { };
243         for (auto mask : traitsMasks) {
244             Ref<CSSFontFace> face = CSSFontFace::create(mask, nullptr, true);
245             face->addSource(std::make_unique<CSSFontFaceSource>(familyName));
246             ASSERT(face->isValid());
247             faces.append(WTFMove(face));
248         }
249         locallyInstalledFontFaces.add(familyName, WTFMove(faces));
250     }
251     return result;
252 }
253
254 void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace& fontFaceRule, bool isInitiatingElementInUserAgentShadowTree)
255 {
256     const StyleProperties& style = fontFaceRule.properties();
257     RefPtr<CSSValue> fontFamily = style.getPropertyCSSValue(CSSPropertyFontFamily);
258     RefPtr<CSSValue> src = style.getPropertyCSSValue(CSSPropertySrc);
259     RefPtr<CSSValue> unicodeRange = style.getPropertyCSSValue(CSSPropertyUnicodeRange);
260     RefPtr<CSSValue> featureSettings = style.getPropertyCSSValue(CSSPropertyFontFeatureSettings);
261     RefPtr<CSSValue> variantLigatures = style.getPropertyCSSValue(CSSPropertyFontVariantLigatures);
262     RefPtr<CSSValue> variantPosition = style.getPropertyCSSValue(CSSPropertyFontVariantPosition);
263     RefPtr<CSSValue> variantCaps = style.getPropertyCSSValue(CSSPropertyFontVariantCaps);
264     RefPtr<CSSValue> variantNumeric = style.getPropertyCSSValue(CSSPropertyFontVariantNumeric);
265     RefPtr<CSSValue> variantAlternates = style.getPropertyCSSValue(CSSPropertyFontVariantAlternates);
266     RefPtr<CSSValue> variantEastAsian = style.getPropertyCSSValue(CSSPropertyFontVariantEastAsian);
267     if (!is<CSSValueList>(fontFamily.get()) || !is<CSSValueList>(src.get()) || (unicodeRange && !is<CSSValueList>(*unicodeRange)))
268         return;
269
270     CSSValueList& familyList = downcast<CSSValueList>(*fontFamily);
271     if (!familyList.length())
272         return;
273
274     CSSValueList& srcList = downcast<CSSValueList>(*src);
275     if (!srcList.length())
276         return;
277
278     CSSValueList* rangeList = downcast<CSSValueList>(unicodeRange.get());
279
280     auto computedTraitsMask = computeTraitsMask(style);
281     if (!computedTraitsMask)
282         return;
283     auto traitsMask = computedTraitsMask.value();
284
285     Ref<CSSFontFace> fontFace = createFontFace(srcList, traitsMask, m_document, fontFaceRule, isInitiatingElementInUserAgentShadowTree);
286     if (!fontFace->isValid())
287         return;
288
289     if (rangeList) {
290         unsigned numRanges = rangeList->length();
291         for (unsigned i = 0; i < numRanges; i++) {
292             CSSUnicodeRangeValue& range = downcast<CSSUnicodeRangeValue>(*rangeList->itemWithoutBoundsCheck(i));
293             fontFace->addRange(range.from(), range.to());
294         }
295     }
296
297     if (featureSettings) {
298         for (auto& item : downcast<CSSValueList>(*featureSettings)) {
299             auto& feature = downcast<CSSFontFeatureValue>(item.get());
300             fontFace->insertFeature(FontFeature(feature.tag(), feature.value()));
301         }
302     }
303
304     if (variantLigatures)
305         applyValueFontVariantLigatures(fontFace.get(), *variantLigatures);
306
307     if (variantPosition && is<CSSPrimitiveValue>(*variantPosition))
308         fontFace->setVariantPosition(downcast<CSSPrimitiveValue>(*variantPosition));
309
310     if (variantCaps && is<CSSPrimitiveValue>(*variantCaps))
311         fontFace->setVariantCaps(downcast<CSSPrimitiveValue>(*variantCaps));
312
313     if (variantNumeric)
314         applyValueFontVariantNumeric(fontFace.get(), *variantNumeric);
315
316     if (variantAlternates && is<CSSPrimitiveValue>(*variantAlternates))
317         fontFace->setVariantAlternates(downcast<CSSPrimitiveValue>(*variantAlternates));
318
319     if (variantEastAsian)
320         applyValueFontVariantEastAsian(fontFace.get(), *variantEastAsian);
321
322     for (auto& item : familyList) {
323         String familyName = familyNameFromPrimitive(downcast<CSSPrimitiveValue>(item.get()));
324         if (familyName.isEmpty())
325             continue;
326
327         auto addResult = m_fontFaces.add(familyName, Vector<Ref<CSSFontFace>>());
328         auto& familyFontFaces = addResult.iterator->value;
329         if (addResult.isNewEntry)
330             familyFontFaces = constructFamilyFontFaces(familyName, m_locallyInstalledFontFaces);
331
332         familyFontFaces.append(fontFace.copyRef());
333         
334         ++m_version;
335     }
336 }
337
338 void CSSFontSelector::registerForInvalidationCallbacks(FontSelectorClient& client)
339 {
340     m_clients.add(&client);
341 }
342
343 void CSSFontSelector::unregisterForInvalidationCallbacks(FontSelectorClient& client)
344 {
345     m_clients.remove(&client);
346 }
347
348 void CSSFontSelector::dispatchInvalidationCallbacks()
349 {
350     ++m_version;
351
352     Vector<FontSelectorClient*> clients;
353     copyToVector(m_clients, clients);
354     for (size_t i = 0; i < clients.size(); ++i)
355         clients[i]->fontsNeedUpdate(*this);
356 }
357
358 void CSSFontSelector::fontLoaded()
359 {
360     dispatchInvalidationCallbacks();
361 }
362
363 void CSSFontSelector::fontCacheInvalidated()
364 {
365     dispatchInvalidationCallbacks();
366 }
367
368 static const AtomicString& resolveGenericFamily(Document* document, const FontDescription& fontDescription, const AtomicString& familyName)
369 {
370     if (!document || !document->frame())
371         return familyName;
372
373     const Settings& settings = document->frame()->settings();
374
375     UScriptCode script = fontDescription.script();
376     if (familyName == serifFamily)
377         return settings.serifFontFamily(script);
378     if (familyName == sansSerifFamily)
379         return settings.sansSerifFontFamily(script);
380     if (familyName == cursiveFamily)
381         return settings.cursiveFontFamily(script);
382     if (familyName == fantasyFamily)
383         return settings.fantasyFontFamily(script);
384     if (familyName == monospaceFamily)
385         return settings.fixedFontFamily(script);
386     if (familyName == pictographFamily)
387         return settings.pictographFontFamily(script);
388     if (familyName == standardFamily)
389         return settings.standardFontFamily(script);
390
391     return familyName;
392 }
393
394 static FontTraitsMask desiredTraitsMaskForComparison;
395
396 static inline bool compareFontFaces(const CSSFontFace& first, const CSSFontFace& second)
397 {
398     FontTraitsMask firstTraitsMask = first.traitsMask();
399     FontTraitsMask secondTraitsMask = second.traitsMask();
400
401     bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
402     bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
403
404     if (firstHasDesiredStyle != secondHasDesiredStyle)
405         return firstHasDesiredStyle;
406
407     if ((desiredTraitsMaskForComparison & FontStyleItalicMask) && !first.isLocalFallback() && !second.isLocalFallback()) {
408         // Prefer a font that has indicated that it can only support italics to a font that claims to support
409         // all styles.  The specialized font is more likely to be the one the author wants used.
410         bool firstRequiresItalics = (firstTraitsMask & FontStyleItalicMask) && !(firstTraitsMask & FontStyleNormalMask);
411         bool secondRequiresItalics = (secondTraitsMask & FontStyleItalicMask) && !(secondTraitsMask & FontStyleNormalMask);
412         if (firstRequiresItalics != secondRequiresItalics)
413             return firstRequiresItalics;
414     }
415
416     if (secondTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
417         return false;
418     if (firstTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
419         return true;
420
421     // http://www.w3.org/TR/2011/WD-css3-fonts-20111004/#font-matching-algorithm says :
422     //   - If the desired weight is less than 400, weights below the desired weight are checked in descending order followed by weights above the desired weight in ascending order until a match is found.
423     //   - If the desired weight is greater than 500, weights above the desired weight are checked in ascending order followed by weights below the desired weight in descending order until a match is found.
424     //   - If the desired weight is 400, 500 is checked first and then the rule for desired weights less than 400 is used.
425     //   - If the desired weight is 500, 400 is checked first and then the rule for desired weights less than 400 is used.
426
427     static const unsigned fallbackRuleSets = 9;
428     static const unsigned rulesPerSet = 8;
429     static const FontTraitsMask weightFallbackRuleSets[fallbackRuleSets][rulesPerSet] = {
430         { FontWeight200Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
431         { FontWeight100Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
432         { FontWeight200Mask, FontWeight100Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
433         { FontWeight500Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
434         { FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
435         { FontWeight700Mask, FontWeight800Mask, FontWeight900Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
436         { FontWeight800Mask, FontWeight900Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
437         { FontWeight900Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
438         { FontWeight800Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask }
439     };
440
441     unsigned ruleSetIndex = 0;
442     unsigned w = FontWeight100Bit;
443     while (!(desiredTraitsMaskForComparison & (1 << w))) {
444         w++;
445         ruleSetIndex++;
446     }
447
448     ASSERT_WITH_SECURITY_IMPLICATION(ruleSetIndex < fallbackRuleSets);
449     const FontTraitsMask* weightFallbackRule = weightFallbackRuleSets[ruleSetIndex];
450     for (unsigned i = 0; i < rulesPerSet; ++i) {
451         if (secondTraitsMask & weightFallbackRule[i])
452             return false;
453         if (firstTraitsMask & weightFallbackRule[i])
454             return true;
455     }
456
457     return false;
458 }
459
460 FontRanges CSSFontSelector::fontRangesForFamily(const FontDescription& fontDescription, const AtomicString& familyName)
461 {
462     // FIXME: The spec (and Firefox) says user specified generic families (sans-serif etc.) should be resolved before the @font-face lookup too.
463     bool resolveGenericFamilyFirst = familyName == standardFamily;
464
465     AtomicString familyForLookup = resolveGenericFamilyFirst ? resolveGenericFamily(m_document, fontDescription, familyName) : familyName;
466     CSSSegmentedFontFace* face = getFontFace(fontDescription, familyForLookup);
467     if (!face) {
468         if (!resolveGenericFamilyFirst)
469             familyForLookup = resolveGenericFamily(m_document, fontDescription, familyName);
470         return FontRanges(FontCache::singleton().fontForFamily(fontDescription, familyForLookup));
471     }
472
473     return face->fontRanges(fontDescription);
474 }
475
476 CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
477 {
478     auto iterator = m_fontFaces.find(family);
479     if (iterator == m_fontFaces.end())
480         return nullptr;
481     auto& familyFontFaces = iterator->value;
482
483     auto& segmentedFontFaceCache = m_fonts.add(family, HashMap<unsigned, RefPtr<CSSSegmentedFontFace>>()).iterator->value;
484
485     FontTraitsMask traitsMask = fontDescription.traitsMask();
486
487     RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache.add(traitsMask, nullptr).iterator->value;
488     if (!face) {
489         face = CSSSegmentedFontFace::create(this);
490
491         Vector<std::reference_wrapper<CSSFontFace>, 32> candidateFontFaces;
492         for (int i = familyFontFaces.size() - 1; i >= 0; --i) {
493             CSSFontFace& candidate = familyFontFaces[i];
494             unsigned candidateTraitsMask = candidate.traitsMask();
495             if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
496                 continue;
497             candidateFontFaces.append(candidate);
498         }
499
500         auto iterator = m_locallyInstalledFontFaces.find(family);
501         if (iterator != m_locallyInstalledFontFaces.end()) {
502             for (auto& candidate : iterator->value) {
503                 unsigned candidateTraitsMask = candidate->traitsMask();
504                 if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
505                     continue;
506                 candidateFontFaces.append(candidate);
507             }
508         }
509
510         desiredTraitsMaskForComparison = traitsMask;
511         std::stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
512         for (auto& candidate : candidateFontFaces)
513             face->appendFontFace(candidate.get());
514     }
515     return face.get();
516 }
517
518 void CSSFontSelector::clearDocument()
519 {
520     if (!m_document) {
521         ASSERT(!m_beginLoadingTimer.isActive());
522         ASSERT(m_fontsToBeginLoading.isEmpty());
523         return;
524     }
525
526     m_beginLoadingTimer.stop();
527
528     CachedResourceLoader& cachedResourceLoader = m_document->cachedResourceLoader();
529     for (auto& fontHandle : m_fontsToBeginLoading) {
530         // Balances incrementRequestCount() in beginLoadingFontSoon().
531         cachedResourceLoader.decrementRequestCount(fontHandle.get());
532     }
533     m_fontsToBeginLoading.clear();
534
535     m_document = nullptr;
536 }
537
538 void CSSFontSelector::beginLoadingFontSoon(CachedFont* font)
539 {
540     if (!m_document)
541         return;
542
543     m_fontsToBeginLoading.append(font);
544     // Increment the request count now, in order to prevent didFinishLoad from being dispatched
545     // after this font has been requested but before it began loading. Balanced by
546     // decrementRequestCount() in beginLoadTimerFired() and in clearDocument().
547     m_document->cachedResourceLoader().incrementRequestCount(font);
548     m_beginLoadingTimer.startOneShot(0);
549 }
550
551 void CSSFontSelector::beginLoadTimerFired()
552 {
553     Vector<CachedResourceHandle<CachedFont>> fontsToBeginLoading;
554     fontsToBeginLoading.swap(m_fontsToBeginLoading);
555
556     // CSSFontSelector could get deleted via beginLoadIfNeeded() or loadDone() unless protected.
557     Ref<CSSFontSelector> protect(*this);
558
559     CachedResourceLoader& cachedResourceLoader = m_document->cachedResourceLoader();
560     for (auto& fontHandle : fontsToBeginLoading) {
561         fontHandle->beginLoadIfNeeded(cachedResourceLoader);
562         // Balances incrementRequestCount() in beginLoadingFontSoon().
563         cachedResourceLoader.decrementRequestCount(fontHandle.get());
564     }
565     // Ensure that if the request count reaches zero, the frame loader will know about it.
566     cachedResourceLoader.loadDone(nullptr);
567     // New font loads may be triggered by layout after the document load is complete but before we have dispatched
568     // didFinishLoading for the frame. Make sure the delegate is always dispatched by checking explicitly.
569     if (m_document && m_document->frame())
570         m_document->frame()->loader().checkLoadComplete();
571 }
572
573 bool CSSFontSelector::resolvesFamilyFor(const FontCascadeDescription& description) const
574 {
575     for (unsigned i = 0; i < description.familyCount(); ++i) {
576         const AtomicString& familyName = description.familyAt(i);
577         if (familyName.isEmpty())
578             continue;
579         if (m_fontFaces.contains(familyName))
580             return true;
581         static NeverDestroyed<String> webkitPrefix("-webkit-");
582         if (familyName.startsWith(webkitPrefix.get()))
583             return true;
584     }
585     return false;
586 }
587
588 size_t CSSFontSelector::fallbackFontCount()
589 {
590     if (!m_document)
591         return 0;
592
593     if (Settings* settings = m_document->settings())
594         return settings->fontFallbackPrefersPictographs() ? 1 : 0;
595
596     return 0;
597 }
598
599 PassRefPtr<Font> CSSFontSelector::fallbackFontAt(const FontDescription& fontDescription, size_t index)
600 {
601     ASSERT_UNUSED(index, !index);
602
603     if (!m_document)
604         return nullptr;
605
606     Settings* settings = m_document->settings();
607     if (!settings || !settings->fontFallbackPrefersPictographs())
608         return nullptr;
609
610     return FontCache::singleton().fontForFamily(fontDescription, settings->pictographFontFamily());
611 }
612
613 }