Hang CSSFontSelector off Document instead of StyleResolver.
[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 "CSSPrimitiveValue.h"
36 #include "CSSPropertyNames.h"
37 #include "CSSSegmentedFontFace.h"
38 #include "CSSUnicodeRangeValue.h"
39 #include "CSSValueKeywords.h"
40 #include "CSSValueList.h"
41 #include "CachedResourceLoader.h"
42 #include "Document.h"
43 #include "Font.h"
44 #include "FontCache.h"
45 #include "Frame.h"
46 #include "FrameLoader.h"
47 #include "SVGFontFaceElement.h"
48 #include "SVGNames.h"
49 #include "Settings.h"
50 #include "StyleProperties.h"
51 #include "StyleResolver.h"
52 #include "StyleRule.h"
53 #include "WebKitFontFamilyNames.h"
54 #include <wtf/Ref.h>
55 #include <wtf/text/AtomicString.h>
56
57 namespace WebCore {
58
59 static unsigned fontSelectorId;
60
61 CSSFontSelector::CSSFontSelector(Document& document)
62     : m_document(&document)
63     , m_beginLoadingTimer(*this, &CSSFontSelector::beginLoadTimerFired)
64     , m_uniqueId(++fontSelectorId)
65     , m_version(0)
66 {
67     // FIXME: An old comment used to say there was no need to hold a reference to m_document
68     // because "we are guaranteed to be destroyed before the document". But there does not
69     // seem to be any such guarantee.
70
71     ASSERT(m_document);
72     fontCache().addClient(this);
73 }
74
75 CSSFontSelector::~CSSFontSelector()
76 {
77     clearDocument();
78     fontCache().removeClient(this);
79 }
80
81 bool CSSFontSelector::isEmpty() const
82 {
83     return m_fonts.isEmpty();
84 }
85
86 void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace* fontFaceRule)
87 {
88     // Obtain the font-family property and the src property.  Both must be defined.
89     const StyleProperties& style = fontFaceRule->properties();
90     RefPtr<CSSValue> fontFamily = style.getPropertyCSSValue(CSSPropertyFontFamily);
91     RefPtr<CSSValue> src = style.getPropertyCSSValue(CSSPropertySrc);
92     RefPtr<CSSValue> unicodeRange = style.getPropertyCSSValue(CSSPropertyUnicodeRange);
93     if (!is<CSSValueList>(fontFamily.get()) || !is<CSSValueList>(src.get()) || (unicodeRange && !is<CSSValueList>(*unicodeRange)))
94         return;
95
96     CSSValueList& familyList = downcast<CSSValueList>(*fontFamily);
97     if (!familyList.length())
98         return;
99
100     CSSValueList& srcList = downcast<CSSValueList>(*src);
101     if (!srcList.length())
102         return;
103
104     CSSValueList* rangeList = downcast<CSSValueList>(unicodeRange.get());
105
106     unsigned traitsMask = 0;
107
108     if (RefPtr<CSSValue> fontStyle = style.getPropertyCSSValue(CSSPropertyFontStyle)) {
109         if (!is<CSSPrimitiveValue>(*fontStyle))
110             return;
111
112         switch (downcast<CSSPrimitiveValue>(*fontStyle).getValueID()) {
113         case CSSValueNormal:
114             traitsMask |= FontStyleNormalMask;
115             break;
116         case CSSValueItalic:
117         case CSSValueOblique:
118             traitsMask |= FontStyleItalicMask;
119             break;
120         default:
121             break;
122         }
123     } else
124         traitsMask |= FontStyleNormalMask;
125
126     if (RefPtr<CSSValue> fontWeight = style.getPropertyCSSValue(CSSPropertyFontWeight)) {
127         if (!is<CSSPrimitiveValue>(*fontWeight))
128             return;
129
130         switch (downcast<CSSPrimitiveValue>(*fontWeight).getValueID()) {
131         case CSSValueBold:
132         case CSSValue700:
133             traitsMask |= FontWeight700Mask;
134             break;
135         case CSSValueNormal:
136         case CSSValue400:
137             traitsMask |= FontWeight400Mask;
138             break;
139         case CSSValue900:
140             traitsMask |= FontWeight900Mask;
141             break;
142         case CSSValue800:
143             traitsMask |= FontWeight800Mask;
144             break;
145         case CSSValue600:
146             traitsMask |= FontWeight600Mask;
147             break;
148         case CSSValue500:
149             traitsMask |= FontWeight500Mask;
150             break;
151         case CSSValue300:
152             traitsMask |= FontWeight300Mask;
153             break;
154         case CSSValue200:
155             traitsMask |= FontWeight200Mask;
156             break;
157         case CSSValue100:
158             traitsMask |= FontWeight100Mask;
159             break;
160         default:
161             break;
162         }
163     } else
164         traitsMask |= FontWeight400Mask;
165
166     if (RefPtr<CSSValue> fontVariant = style.getPropertyCSSValue(CSSPropertyFontVariant)) {
167         // font-variant descriptor can be a value list.
168         if (fontVariant->isPrimitiveValue()) {
169             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
170             list->append(fontVariant.releaseNonNull());
171             fontVariant = list.releaseNonNull();
172         } else if (!is<CSSValueList>(*fontVariant))
173             return;
174
175         CSSValueList& variantList = downcast<CSSValueList>(*fontVariant);
176         unsigned numVariants = variantList.length();
177         if (!numVariants)
178             return;
179
180         for (unsigned i = 0; i < numVariants; ++i) {
181             switch (downcast<CSSPrimitiveValue>(variantList.itemWithoutBoundsCheck(i))->getValueID()) {
182                 case CSSValueNormal:
183                     traitsMask |= FontVariantNormalMask;
184                     break;
185                 case CSSValueSmallCaps:
186                     traitsMask |= FontVariantSmallCapsMask;
187                     break;
188                 default:
189                     break;
190             }
191         }
192     } else
193         traitsMask |= FontVariantMask;
194
195     // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
196     RefPtr<CSSFontFace> fontFace;
197
198     int srcLength = srcList.length();
199
200     bool foundSVGFont = false;
201
202     for (int i = 0; i < srcLength; i++) {
203         // An item in the list either specifies a string (local font name) or a URL (remote font to download).
204         CSSFontFaceSrcValue& item = downcast<CSSFontFaceSrcValue>(*srcList.itemWithoutBoundsCheck(i));
205         std::unique_ptr<CSSFontFaceSource> source;
206
207 #if ENABLE(SVG_FONTS)
208         foundSVGFont = item.isSVGFontFaceSrc() || item.svgFontFaceElement();
209 #endif
210         if (!item.isLocal()) {
211             Settings* settings = m_document ? m_document->frame() ? &m_document->frame()->settings() : 0 : 0;
212             bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
213             if (allowDownloading && item.isSupportedFormat() && m_document) {
214                 CachedFont* cachedFont = item.cachedFont(m_document, foundSVGFont);
215                 if (cachedFont) {
216                     source = std::make_unique<CSSFontFaceSource>(item.resource(), cachedFont);
217 #if ENABLE(SVG_FONTS)
218                     if (foundSVGFont)
219                         source->setHasExternalSVGFont();
220 #endif
221                 }
222             }
223         } else {
224             source = std::make_unique<CSSFontFaceSource>(item.resource());
225         }
226
227         if (!fontFace) {
228             RefPtr<CSSFontFaceRule> rule;
229 #if ENABLE(FONT_LOAD_EVENTS)
230             // FIXME: https://bugs.webkit.org/show_bug.cgi?id=112116 - This CSSFontFaceRule has no parent.
231             if (RuntimeEnabledFeatures::sharedFeatures().fontLoadEventsEnabled())
232                 rule = static_pointer_cast<CSSFontFaceRule>(fontFaceRule->createCSSOMWrapper());
233 #endif
234             fontFace = CSSFontFace::create(static_cast<FontTraitsMask>(traitsMask), rule);
235         }
236
237         if (source) {
238 #if ENABLE(SVG_FONTS)
239             source->setSVGFontFaceElement(item.svgFontFaceElement());
240 #endif
241             fontFace->addSource(WTF::move(source));
242         }
243     }
244
245     ASSERT(fontFace);
246
247     if (fontFace && !fontFace->isValid())
248         return;
249
250     if (rangeList) {
251         unsigned numRanges = rangeList->length();
252         for (unsigned i = 0; i < numRanges; i++) {
253             CSSUnicodeRangeValue& range = downcast<CSSUnicodeRangeValue>(*rangeList->itemWithoutBoundsCheck(i));
254             fontFace->addRange(range.from(), range.to());
255         }
256     }
257
258     // Hash under every single family name.
259     int familyLength = familyList.length();
260     for (int i = 0; i < familyLength; i++) {
261         CSSPrimitiveValue* item = downcast<CSSPrimitiveValue>(familyList.itemWithoutBoundsCheck(i));
262         String familyName;
263         if (item->isString()) {
264             familyName = item->getStringValue();
265         } else if (item->isValueID()) {
266             // We need to use the raw text for all the generic family types, since @font-face is a way of actually
267             // defining what font to use for those types.
268             switch (item->getValueID()) {
269                 case CSSValueSerif:
270                     familyName = serifFamily;
271                     break;
272                 case CSSValueSansSerif:
273                     familyName = sansSerifFamily;
274                     break;
275                 case CSSValueCursive:
276                     familyName = cursiveFamily;
277                     break;
278                 case CSSValueFantasy:
279                     familyName = fantasyFamily;
280                     break;
281                 case CSSValueMonospace:
282                     familyName = monospaceFamily;
283                     break;
284                 case CSSValueWebkitPictograph:
285                     familyName = pictographFamily;
286                     break;
287                 default:
288                     break;
289             }
290         }
291
292         if (familyName.isEmpty())
293             continue;
294
295         std::unique_ptr<Vector<RefPtr<CSSFontFace>>>& familyFontFaces = m_fontFaces.add(familyName, nullptr).iterator->value;
296         if (!familyFontFaces) {
297             familyFontFaces = std::make_unique<Vector<RefPtr<CSSFontFace>>>();
298
299             ASSERT(!m_locallyInstalledFontFaces.contains(familyName));
300
301             Vector<unsigned> locallyInstalledFontsTraitsMasks;
302             fontCache().getTraitsInFamily(familyName, locallyInstalledFontsTraitsMasks);
303             if (unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size()) {
304                 auto familyLocallyInstalledFaces = std::make_unique<Vector<RefPtr<CSSFontFace>>>();
305
306                 for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
307                     RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), 0, true);
308                     locallyInstalledFontFace->addSource(std::make_unique<CSSFontFaceSource>(familyName));
309                     ASSERT(locallyInstalledFontFace->isValid());
310                     familyLocallyInstalledFaces->append(locallyInstalledFontFace);
311                 }
312
313                 m_locallyInstalledFontFaces.set(familyName, WTF::move(familyLocallyInstalledFaces));
314             }
315         }
316
317         familyFontFaces->append(fontFace);
318         
319         ++m_version;
320     }
321 }
322
323 void CSSFontSelector::registerForInvalidationCallbacks(FontSelectorClient* client)
324 {
325     m_clients.add(client);
326 }
327
328 void CSSFontSelector::unregisterForInvalidationCallbacks(FontSelectorClient* client)
329 {
330     m_clients.remove(client);
331 }
332
333 void CSSFontSelector::dispatchInvalidationCallbacks()
334 {
335     ++m_version;
336
337     Vector<FontSelectorClient*> clients;
338     copyToVector(m_clients, clients);
339     for (size_t i = 0; i < clients.size(); ++i)
340         clients[i]->fontsNeedUpdate(this);
341
342     // FIXME: Make Document a FontSelectorClient so that it can simply register for invalidation callbacks.
343     if (!m_document)
344         return;
345     if (StyleResolver* styleResolver = m_document->styleResolverIfExists())
346         styleResolver->invalidateMatchedPropertiesCache();
347     if (m_document->inPageCache() || !m_document->renderView())
348         return;
349     m_document->scheduleForcedStyleRecalc();
350 }
351
352 void CSSFontSelector::fontLoaded()
353 {
354     dispatchInvalidationCallbacks();
355 }
356
357 void CSSFontSelector::fontCacheInvalidated()
358 {
359     dispatchInvalidationCallbacks();
360 }
361
362 static const AtomicString& resolveGenericFamily(Document* document, const FontDescription& fontDescription, const AtomicString& familyName)
363 {
364     if (!document || !document->frame())
365         return familyName;
366
367     const Settings& settings = document->frame()->settings();
368
369     UScriptCode script = fontDescription.script();
370     if (familyName == serifFamily)
371         return settings.serifFontFamily(script);
372     if (familyName == sansSerifFamily)
373         return settings.sansSerifFontFamily(script);
374     if (familyName == cursiveFamily)
375         return settings.cursiveFontFamily(script);
376     if (familyName == fantasyFamily)
377         return settings.fantasyFontFamily(script);
378     if (familyName == monospaceFamily)
379         return settings.fixedFontFamily(script);
380     if (familyName == pictographFamily)
381         return settings.pictographFontFamily(script);
382     if (familyName == standardFamily)
383         return settings.standardFontFamily(script);
384
385     return familyName;
386 }
387
388 static FontTraitsMask desiredTraitsMaskForComparison;
389
390 static inline bool compareFontFaces(CSSFontFace* first, CSSFontFace* second)
391 {
392     FontTraitsMask firstTraitsMask = first->traitsMask();
393     FontTraitsMask secondTraitsMask = second->traitsMask();
394
395     bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
396     bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
397
398     if (firstHasDesiredVariant != secondHasDesiredVariant)
399         return firstHasDesiredVariant;
400
401     // We need to check font-variant css property for CSS2.1 compatibility.
402     if ((desiredTraitsMaskForComparison & FontVariantSmallCapsMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
403         // Prefer a font that has indicated that it can only support small-caps to a font that claims to support
404         // all variants.  The specialized font is more likely to be true small-caps and not require synthesis.
405         bool firstRequiresSmallCaps = (firstTraitsMask & FontVariantSmallCapsMask) && !(firstTraitsMask & FontVariantNormalMask);
406         bool secondRequiresSmallCaps = (secondTraitsMask & FontVariantSmallCapsMask) && !(secondTraitsMask & FontVariantNormalMask);
407         if (firstRequiresSmallCaps != secondRequiresSmallCaps)
408             return firstRequiresSmallCaps;
409     }
410
411     bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
412     bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
413
414     if (firstHasDesiredStyle != secondHasDesiredStyle)
415         return firstHasDesiredStyle;
416
417     if ((desiredTraitsMaskForComparison & FontStyleItalicMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
418         // Prefer a font that has indicated that it can only support italics to a font that claims to support
419         // all styles.  The specialized font is more likely to be the one the author wants used.
420         bool firstRequiresItalics = (firstTraitsMask & FontStyleItalicMask) && !(firstTraitsMask & FontStyleNormalMask);
421         bool secondRequiresItalics = (secondTraitsMask & FontStyleItalicMask) && !(secondTraitsMask & FontStyleNormalMask);
422         if (firstRequiresItalics != secondRequiresItalics)
423             return firstRequiresItalics;
424     }
425
426     if (secondTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
427         return false;
428     if (firstTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
429         return true;
430
431     // http://www.w3.org/TR/2011/WD-css3-fonts-20111004/#font-matching-algorithm says :
432     //   - 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.
433     //   - 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.
434     //   - If the desired weight is 400, 500 is checked first and then the rule for desired weights less than 400 is used.
435     //   - If the desired weight is 500, 400 is checked first and then the rule for desired weights less than 400 is used.
436
437     static const unsigned fallbackRuleSets = 9;
438     static const unsigned rulesPerSet = 8;
439     static const FontTraitsMask weightFallbackRuleSets[fallbackRuleSets][rulesPerSet] = {
440         { FontWeight200Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
441         { FontWeight100Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
442         { FontWeight200Mask, FontWeight100Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
443         { FontWeight500Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
444         { FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
445         { FontWeight700Mask, FontWeight800Mask, FontWeight900Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
446         { FontWeight800Mask, FontWeight900Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
447         { FontWeight900Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
448         { FontWeight800Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask }
449     };
450
451     unsigned ruleSetIndex = 0;
452     unsigned w = FontWeight100Bit;
453     while (!(desiredTraitsMaskForComparison & (1 << w))) {
454         w++;
455         ruleSetIndex++;
456     }
457
458     ASSERT_WITH_SECURITY_IMPLICATION(ruleSetIndex < fallbackRuleSets);
459     const FontTraitsMask* weightFallbackRule = weightFallbackRuleSets[ruleSetIndex];
460     for (unsigned i = 0; i < rulesPerSet; ++i) {
461         if (secondTraitsMask & weightFallbackRule[i])
462             return false;
463         if (firstTraitsMask & weightFallbackRule[i])
464             return true;
465     }
466
467     return false;
468 }
469
470 FontRanges CSSFontSelector::fontRangesForFamily(const FontDescription& fontDescription, const AtomicString& familyName)
471 {
472     // FIXME: The spec (and Firefox) says user specified generic families (sans-serif etc.) should be resolved before the @font-face lookup too.
473     bool resolveGenericFamilyFirst = familyName == standardFamily;
474
475     AtomicString familyForLookup = resolveGenericFamilyFirst ? resolveGenericFamily(m_document, fontDescription, familyName) : familyName;
476     CSSSegmentedFontFace* face = getFontFace(fontDescription, familyForLookup);
477     if (!face) {
478         if (!resolveGenericFamilyFirst)
479             familyForLookup = resolveGenericFamily(m_document, fontDescription, familyName);
480         return FontRanges(fontCache().fontForFamily(fontDescription, familyForLookup));
481     }
482
483     return face->fontRanges(fontDescription);
484 }
485
486 CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
487 {
488     Vector<RefPtr<CSSFontFace>>* familyFontFaces = m_fontFaces.get(family);
489     if (!familyFontFaces || familyFontFaces->isEmpty())
490         return 0;
491
492     std::unique_ptr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace>>>& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
493     if (!segmentedFontFaceCache)
494         segmentedFontFaceCache = std::make_unique<HashMap<unsigned, RefPtr<CSSSegmentedFontFace>>>();
495
496     FontTraitsMask traitsMask = fontDescription.traitsMask();
497
498     RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, nullptr).iterator->value;
499     if (!face) {
500         face = CSSSegmentedFontFace::create(this);
501
502         // Collect all matching faces and sort them in order of preference.
503         Vector<CSSFontFace*, 32> candidateFontFaces;
504         for (int i = familyFontFaces->size() - 1; i >= 0; --i) {
505             CSSFontFace* candidate = familyFontFaces->at(i).get();
506             unsigned candidateTraitsMask = candidate->traitsMask();
507             if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
508                 continue;
509             if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
510                 continue;
511 #if ENABLE(SVG_FONTS)
512             // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
513             // of small-caps synthesis and just ignore the font face as a candidate.
514             if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
515                 continue;
516 #endif
517             candidateFontFaces.append(candidate);
518         }
519
520         if (Vector<RefPtr<CSSFontFace>>* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
521             unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
522             for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
523                 CSSFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
524                 unsigned candidateTraitsMask = candidate->traitsMask();
525                 if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
526                     continue;
527                 if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
528                     continue;
529                 candidateFontFaces.append(candidate);
530             }
531         }
532
533         desiredTraitsMaskForComparison = traitsMask;
534         std::stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
535         unsigned numCandidates = candidateFontFaces.size();
536         for (unsigned i = 0; i < numCandidates; ++i)
537             face->appendFontFace(candidateFontFaces[i]);
538     }
539     return face.get();
540 }
541
542 void CSSFontSelector::clearDocument()
543 {
544     if (!m_document) {
545         ASSERT(!m_beginLoadingTimer.isActive());
546         ASSERT(m_fontsToBeginLoading.isEmpty());
547         return;
548     }
549
550     m_beginLoadingTimer.stop();
551
552     CachedResourceLoader* cachedResourceLoader = m_document->cachedResourceLoader();
553     for (size_t i = 0; i < m_fontsToBeginLoading.size(); ++i) {
554         // Balances incrementRequestCount() in beginLoadingFontSoon().
555         cachedResourceLoader->decrementRequestCount(m_fontsToBeginLoading[i].get());
556     }
557
558     m_fontsToBeginLoading.clear();
559
560     m_document = 0;
561 }
562
563 void CSSFontSelector::beginLoadingFontSoon(CachedFont* font)
564 {
565     if (!m_document)
566         return;
567
568     m_fontsToBeginLoading.append(font);
569     // Increment the request count now, in order to prevent didFinishLoad from being dispatched
570     // after this font has been requested but before it began loading. Balanced by
571     // decrementRequestCount() in beginLoadTimerFired() and in clearDocument().
572     m_document->cachedResourceLoader()->incrementRequestCount(font);
573     m_beginLoadingTimer.startOneShot(0);
574 }
575
576 void CSSFontSelector::beginLoadTimerFired()
577 {
578     Vector<CachedResourceHandle<CachedFont>> fontsToBeginLoading;
579     fontsToBeginLoading.swap(m_fontsToBeginLoading);
580
581     // CSSFontSelector could get deleted via beginLoadIfNeeded() or loadDone() unless protected.
582     Ref<CSSFontSelector> protect(*this);
583
584     CachedResourceLoader* cachedResourceLoader = m_document->cachedResourceLoader();
585     for (size_t i = 0; i < fontsToBeginLoading.size(); ++i) {
586         fontsToBeginLoading[i]->beginLoadIfNeeded(cachedResourceLoader);
587         // Balances incrementRequestCount() in beginLoadingFontSoon().
588         cachedResourceLoader->decrementRequestCount(fontsToBeginLoading[i].get());
589     }
590     // Ensure that if the request count reaches zero, the frame loader will know about it.
591     cachedResourceLoader->loadDone(0);
592     // New font loads may be triggered by layout after the document load is complete but before we have dispatched
593     // didFinishLoading for the frame. Make sure the delegate is always dispatched by checking explicitly.
594     if (m_document && m_document->frame())
595         m_document->frame()->loader().checkLoadComplete();
596 }
597
598 bool CSSFontSelector::resolvesFamilyFor(const FontDescription& description) const
599 {
600     for (unsigned i = 0; i < description.familyCount(); ++i) {
601         const AtomicString& familyName = description.familyAt(i);
602         if (familyName.isEmpty())
603             continue;
604         if (m_fontFaces.contains(familyName))
605             return true;
606         DEPRECATED_DEFINE_STATIC_LOCAL(String, webkitPrefix, ("-webkit-"));
607         if (familyName.startsWith(webkitPrefix))
608             return true;
609             
610     }
611     return false;
612 }
613
614 size_t CSSFontSelector::fallbackFontCount()
615 {
616     if (!m_document)
617         return 0;
618
619     if (Settings* settings = m_document->settings())
620         return settings->fontFallbackPrefersPictographs() ? 1 : 0;
621
622     return 0;
623 }
624
625 PassRefPtr<Font> CSSFontSelector::fallbackFontAt(const FontDescription& fontDescription, size_t index)
626 {
627     ASSERT_UNUSED(index, !index);
628
629     if (!m_document)
630         return 0;
631
632     Settings* settings = m_document->settings();
633     if (!settings || !settings->fontFallbackPrefersPictographs())
634         return 0;
635
636     return fontCache().fontForFamily(fontDescription, settings->pictographFontFamily());
637 }
638
639 }