2 * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
3 * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, 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 COMPUTER, 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.
28 #include "CSSFontSelector.h"
30 #include "AtomicString.h"
31 #include "CachedFont.h"
32 #include "CSSFontFace.h"
33 #include "CSSFontFaceRule.h"
34 #include "CSSFontFaceSource.h"
35 #include "CSSFontFaceSrcValue.h"
36 #include "CSSMutableStyleDeclaration.h"
37 #include "CSSPrimitiveValue.h"
38 #include "CSSPropertyNames.h"
39 #include "CSSSegmentedFontFace.h"
40 #include "CSSUnicodeRangeValue.h"
41 #include "CSSValueKeywords.h"
42 #include "CSSValueList.h"
43 #include "DocLoader.h"
45 #include "FontCache.h"
46 #include "FontFamilyValue.h"
48 #include "RenderObject.h"
50 #include "SimpleFontData.h"
53 #include "SVGFontFaceElement.h"
59 CSSFontSelector::CSSFontSelector(Document* document)
60 : m_document(document)
62 // FIXME: An old comment used to say there was no need to hold a reference to m_document
63 // because "we are guaranteed to be destroyed before the document". But there does not
64 // seem to be any such guarantee.
67 fontCache()->addClient(this);
70 CSSFontSelector::~CSSFontSelector()
72 fontCache()->removeClient(this);
73 deleteAllValues(m_fontFaces);
74 deleteAllValues(m_locallyInstalledFontFaces);
75 deleteAllValues(m_fonts);
78 bool CSSFontSelector::isEmpty() const
80 return m_fonts.isEmpty();
83 DocLoader* CSSFontSelector::docLoader() const
85 return m_document ? m_document->docLoader() : 0;
88 void CSSFontSelector::addFontFaceRule(const CSSFontFaceRule* fontFaceRule)
90 // Obtain the font-family property and the src property. Both must be defined.
91 const CSSMutableStyleDeclaration* style = fontFaceRule->style();
92 RefPtr<CSSValue> fontFamily = style->getPropertyCSSValue(CSSPropertyFontFamily);
93 RefPtr<CSSValue> src = style->getPropertyCSSValue(CSSPropertySrc);
94 RefPtr<CSSValue> unicodeRange = style->getPropertyCSSValue(CSSPropertyUnicodeRange);
95 if (!fontFamily || !src || !fontFamily->isValueList() || !src->isValueList() || (unicodeRange && !unicodeRange->isValueList()))
98 CSSValueList* familyList = static_cast<CSSValueList*>(fontFamily.get());
99 if (!familyList->length())
102 CSSValueList* srcList = static_cast<CSSValueList*>(src.get());
103 if (!srcList->length())
106 CSSValueList* rangeList = static_cast<CSSValueList*>(unicodeRange.get());
108 unsigned traitsMask = 0;
110 if (RefPtr<CSSValue> fontStyle = style->getPropertyCSSValue(CSSPropertyFontStyle)) {
111 if (fontStyle->isPrimitiveValue()) {
112 RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
113 list->append(fontStyle);
115 } else if (!fontStyle->isValueList())
118 CSSValueList* styleList = static_cast<CSSValueList*>(fontStyle.get());
119 unsigned numStyles = styleList->length();
123 for (unsigned i = 0; i < numStyles; ++i) {
124 switch (static_cast<CSSPrimitiveValue*>(styleList->itemWithoutBoundsCheck(i))->getIdent()) {
126 traitsMask |= FontStyleMask;
129 traitsMask |= FontStyleNormalMask;
132 case CSSValueOblique:
133 traitsMask |= FontStyleItalicMask;
140 traitsMask |= FontStyleMask;
142 if (RefPtr<CSSValue> fontWeight = style->getPropertyCSSValue(CSSPropertyFontWeight)) {
143 if (fontWeight->isPrimitiveValue()) {
144 RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
145 list->append(fontWeight);
147 } else if (!fontWeight->isValueList())
150 CSSValueList* weightList = static_cast<CSSValueList*>(fontWeight.get());
151 unsigned numWeights = weightList->length();
155 for (unsigned i = 0; i < numWeights; ++i) {
156 switch (static_cast<CSSPrimitiveValue*>(weightList->itemWithoutBoundsCheck(i))->getIdent()) {
158 traitsMask |= FontWeightMask;
163 traitsMask |= FontWeight700Mask;
167 traitsMask |= FontWeight400Mask;
170 traitsMask |= FontWeight900Mask;
173 traitsMask |= FontWeight800Mask;
176 traitsMask |= FontWeight600Mask;
179 traitsMask |= FontWeight500Mask;
182 traitsMask |= FontWeight300Mask;
184 case CSSValueLighter:
186 traitsMask |= FontWeight200Mask;
189 traitsMask |= FontWeight100Mask;
196 traitsMask |= FontWeightMask;
198 if (RefPtr<CSSValue> fontVariant = style->getPropertyCSSValue(CSSPropertyFontVariant)) {
199 if (fontVariant->isPrimitiveValue()) {
200 RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
201 list->append(fontVariant);
203 } else if (!fontVariant->isValueList())
206 CSSValueList* variantList = static_cast<CSSValueList*>(fontVariant.get());
207 unsigned numVariants = variantList->length();
211 for (unsigned i = 0; i < numVariants; ++i) {
212 switch (static_cast<CSSPrimitiveValue*>(variantList->itemWithoutBoundsCheck(i))->getIdent()) {
214 traitsMask |= FontVariantMask;
217 traitsMask |= FontVariantNormalMask;
219 case CSSValueSmallCaps:
220 traitsMask |= FontVariantSmallCapsMask;
227 traitsMask |= FontVariantNormalMask;
229 // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
230 RefPtr<CSSFontFace> fontFace;
232 int srcLength = srcList->length();
234 bool foundSVGFont = false;
236 for (int i = 0; i < srcLength; i++) {
237 // An item in the list either specifies a string (local font name) or a URL (remote font to download).
238 CSSFontFaceSrcValue* item = static_cast<CSSFontFaceSrcValue*>(srcList->itemWithoutBoundsCheck(i));
239 CSSFontFaceSource* source = 0;
241 #if ENABLE(SVG_FONTS)
242 foundSVGFont = item->isSVGFontFaceSrc() || item->svgFontFaceElement();
244 if (!item->isLocal()) {
245 Settings* settings = m_document ? m_document->frame() ? m_document->frame()->settings() : 0 : 0;
246 bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
247 if (allowDownloading && item->isSupportedFormat() && m_document) {
248 CachedFont* cachedFont = m_document->docLoader()->requestFont(item->resource());
250 #if ENABLE(SVG_FONTS)
252 cachedFont->setSVGFont(true);
254 source = new CSSFontFaceSource(item->resource(), cachedFont);
258 source = new CSSFontFaceSource(item->resource());
262 fontFace = CSSFontFace::create(static_cast<FontTraitsMask>(traitsMask));
265 #if ENABLE(SVG_FONTS)
266 source->setSVGFontFaceElement(item->svgFontFaceElement());
268 fontFace->addSource(source);
274 if (fontFace && !fontFace->isValid())
278 unsigned numRanges = rangeList->length();
279 for (unsigned i = 0; i < numRanges; i++) {
280 CSSUnicodeRangeValue* range = static_cast<CSSUnicodeRangeValue*>(rangeList->itemWithoutBoundsCheck(i));
281 fontFace->addRange(range->from(), range->to());
285 // Hash under every single family name.
286 int familyLength = familyList->length();
287 for (int i = 0; i < familyLength; i++) {
288 CSSPrimitiveValue* item = static_cast<CSSPrimitiveValue*>(familyList->itemWithoutBoundsCheck(i));
290 if (item->primitiveType() == CSSPrimitiveValue::CSS_STRING)
291 familyName = static_cast<FontFamilyValue*>(item)->familyName();
292 else if (item->primitiveType() == CSSPrimitiveValue::CSS_IDENT) {
293 // We need to use the raw text for all the generic family types, since @font-face is a way of actually
294 // defining what font to use for those types.
296 switch (item->getIdent()) {
298 familyName = "-webkit-serif";
300 case CSSValueSansSerif:
301 familyName = "-webkit-sans-serif";
303 case CSSValueCursive:
304 familyName = "-webkit-cursive";
306 case CSSValueFantasy:
307 familyName = "-webkit-fantasy";
309 case CSSValueMonospace:
310 familyName = "-webkit-monospace";
317 if (familyName.isEmpty())
320 #if ENABLE(SVG_FONTS)
321 // SVG allows several <font> elements with the same font-family, differing only
322 // in ie. font-variant. Be sure to pick up the right one - in getFontData below.
323 if (foundSVGFont && (traitsMask & FontVariantSmallCapsMask))
324 familyName += "-webkit-svg-small-caps";
327 Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(familyName);
328 if (!familyFontFaces) {
329 familyFontFaces = new Vector<RefPtr<CSSFontFace> >;
330 m_fontFaces.set(familyName, familyFontFaces);
332 ASSERT(!m_locallyInstalledFontFaces.contains(familyName));
333 Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFaces;
335 Vector<unsigned> locallyInstalledFontsTraitsMasks;
336 fontCache()->getTraitsInFamily(familyName, locallyInstalledFontsTraitsMasks);
337 unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size();
338 if (numLocallyInstalledFaces) {
339 familyLocallyInstalledFaces = new Vector<RefPtr<CSSFontFace> >;
340 m_locallyInstalledFontFaces.set(familyName, familyLocallyInstalledFaces);
342 for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
343 RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]));
344 locallyInstalledFontFace->addSource(new CSSFontFaceSource(familyName));
345 ASSERT(locallyInstalledFontFace->isValid());
346 familyLocallyInstalledFaces->append(locallyInstalledFontFace);
351 familyFontFaces->append(fontFace);
355 void CSSFontSelector::fontLoaded()
357 if (!m_document || m_document->inPageCache() || !m_document->renderer())
359 m_document->recalcStyle(Document::Force);
360 m_document->renderer()->setNeedsLayoutAndPrefWidthsRecalc();
363 void CSSFontSelector::fontCacheInvalidated()
365 if (!m_document || m_document->inPageCache() || !m_document->renderer())
367 m_document->recalcStyle(Document::Force);
368 m_document->renderer()->setNeedsLayoutAndPrefWidthsRecalc();
371 static FontData* fontDataForGenericFamily(Document* document, const FontDescription& fontDescription, const AtomicString& familyName)
373 if (!document || !document->frame())
376 const Settings* settings = document->frame()->settings();
380 AtomicString genericFamily;
381 if (familyName == "-webkit-serif")
382 genericFamily = settings->serifFontFamily();
383 else if (familyName == "-webkit-sans-serif")
384 genericFamily = settings->sansSerifFontFamily();
385 else if (familyName == "-webkit-cursive")
386 genericFamily = settings->cursiveFontFamily();
387 else if (familyName == "-webkit-fantasy")
388 genericFamily = settings->fantasyFontFamily();
389 else if (familyName == "-webkit-monospace")
390 genericFamily = settings->fixedFontFamily();
391 else if (familyName == "-webkit-standard")
392 genericFamily = settings->standardFontFamily();
394 if (!genericFamily.isEmpty())
395 return fontCache()->getCachedFontData(fontDescription, genericFamily);
400 static FontTraitsMask desiredTraitsMaskForComparison;
402 static inline bool compareFontFaces(CSSFontFace* first, CSSFontFace* second)
404 FontTraitsMask firstTraitsMask = first->traitsMask();
405 FontTraitsMask secondTraitsMask = second->traitsMask();
407 bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
408 bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMaskForComparison & FontVariantMask;
410 if (firstHasDesiredVariant != secondHasDesiredVariant)
411 return firstHasDesiredVariant;
413 bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
414 bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMaskForComparison & FontStyleMask;
416 if (firstHasDesiredStyle != secondHasDesiredStyle)
417 return firstHasDesiredStyle;
419 if (secondTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
421 if (firstTraitsMask & desiredTraitsMaskForComparison & FontWeightMask)
424 // http://www.w3.org/TR/2002/WD-css3-webfonts-20020802/#q46 says: "If there are fewer then 9 weights in the family, the default algorithm
425 // for filling the "holes" is as follows. If '500' is unassigned, it will be assigned the same font as '400'. If any of the values '600',
426 // '700', '800', or '900' remains unassigned, they are assigned to the same face as the next darker assigned keyword, if any, or the next
427 // lighter one otherwise. If any of '300', '200', or '100' remains unassigned, it is assigned to the next lighter assigned keyword, if any,
428 // or the next darker otherwise."
429 // For '400', we made up our own rule (which then '500' follows).
431 static const unsigned fallbackRuleSets = 9;
432 static const unsigned rulesPerSet = 8;
433 static const FontTraitsMask weightFallbackRuleSets[fallbackRuleSets][rulesPerSet] = {
434 { FontWeight200Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
435 { FontWeight100Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
436 { FontWeight200Mask, FontWeight100Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
437 { FontWeight500Mask, FontWeight300Mask, FontWeight600Mask, FontWeight200Mask, FontWeight700Mask, FontWeight100Mask, FontWeight800Mask, FontWeight900Mask },
438 { FontWeight400Mask, FontWeight300Mask, FontWeight600Mask, FontWeight200Mask, FontWeight700Mask, FontWeight100Mask, FontWeight800Mask, FontWeight900Mask },
439 { FontWeight700Mask, FontWeight800Mask, FontWeight900Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
440 { FontWeight800Mask, FontWeight900Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
441 { FontWeight900Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
442 { FontWeight800Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask }
445 unsigned ruleSetIndex = 0;
446 unsigned w = FontWeight100Bit;
447 while (!(desiredTraitsMaskForComparison & (1 << w))) {
452 ASSERT(ruleSetIndex < fallbackRuleSets);
453 const FontTraitsMask* weightFallbackRule = weightFallbackRuleSets[ruleSetIndex];
454 for (unsigned i = 0; i < rulesPerSet; ++i) {
455 if (secondTraitsMask & weightFallbackRule[i])
457 if (firstTraitsMask & weightFallbackRule[i])
464 FontData* CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
466 if (m_fontFaces.isEmpty()) {
467 if (familyName.startsWith("-webkit-"))
468 return fontDataForGenericFamily(m_document, fontDescription, familyName);
472 String family = familyName.string();
474 #if ENABLE(SVG_FONTS)
475 if (fontDescription.smallCaps())
476 family += "-webkit-svg-small-caps";
479 Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(family);
480 // If no face was found, then return 0 and let the OS come up with its best match for the name.
481 if (!familyFontFaces || familyFontFaces->isEmpty()) {
482 // If we were handed a generic family, but there was no match, go ahead and return the correct font based off our
484 return fontDataForGenericFamily(m_document, fontDescription, familyName);
487 HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* segmentedFontFaceCache = m_fonts.get(family);
488 if (!segmentedFontFaceCache) {
489 segmentedFontFaceCache = new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >;
490 m_fonts.set(family, segmentedFontFaceCache);
493 FontTraitsMask traitsMask = fontDescription.traitsMask();
495 RefPtr<CSSSegmentedFontFace> face = segmentedFontFaceCache->get(traitsMask);
498 face = CSSSegmentedFontFace::create(this);
499 segmentedFontFaceCache->set(traitsMask, face);
500 // Collect all matching faces and sort them in order of preference.
501 Vector<CSSFontFace*, 32> candidateFontFaces;
502 for (int i = familyFontFaces->size() - 1; i >= 0; --i) {
503 CSSFontFace* candidate = familyFontFaces->at(i).get();
504 unsigned candidateTraitsMask = candidate->traitsMask();
505 if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
507 if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
509 candidateFontFaces.append(candidate);
512 if (Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
513 unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
514 for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
515 CSSFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
516 unsigned candidateTraitsMask = candidate->traitsMask();
517 if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
519 if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
521 candidateFontFaces.append(candidate);
525 desiredTraitsMaskForComparison = traitsMask;
526 std::stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
527 unsigned numCandidates = candidateFontFaces.size();
528 for (unsigned i = 0; i < numCandidates; ++i)
529 face->appendFontFace(candidateFontFaces[i]);
532 // We have a face. Ask it for a font data. If it cannot produce one, it will fail, and the OS will take over.
533 return face->getFontData(fontDescription);