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