2 * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "FontCache.h"
34 #include "FontFallbackList.h"
35 #include "FontPlatformData.h"
36 #include "FontSelector.h"
37 #include <wtf/HashMap.h>
38 #include <wtf/ListHashSet.h>
39 #include <wtf/StdLibExtras.h>
40 #include <wtf/text/StringHash.h>
46 FontCache* fontCache()
48 DEFINE_STATIC_LOCAL(FontCache, globalFontCache, ());
49 return &globalFontCache;
52 FontCache::FontCache()
56 struct FontPlatformDataCacheKey {
57 WTF_MAKE_FAST_ALLOCATED;
59 FontPlatformDataCacheKey(const AtomicString& family = AtomicString(), unsigned size = 0, unsigned weight = 0, bool italic = false,
60 bool isPrinterFont = false, FontRenderingMode renderingMode = NormalRenderingMode, FontOrientation orientation = Horizontal,
61 TextOrientation textOrientation = TextOrientationVerticalRight, FontWidthVariant widthVariant = RegularWidth)
66 , m_printerFont(isPrinterFont)
67 , m_renderingMode(renderingMode)
68 , m_orientation(orientation)
69 , m_textOrientation(textOrientation)
70 , m_widthVariant(widthVariant)
74 FontPlatformDataCacheKey(HashTableDeletedValueType) : m_size(hashTableDeletedSize()) { }
75 bool isHashTableDeletedValue() const { return m_size == hashTableDeletedSize(); }
77 bool operator==(const FontPlatformDataCacheKey& other) const
79 return equalIgnoringCase(m_family, other.m_family) && m_size == other.m_size &&
80 m_weight == other.m_weight && m_italic == other.m_italic && m_printerFont == other.m_printerFont &&
81 m_renderingMode == other.m_renderingMode && m_orientation == other.m_orientation && m_textOrientation == other.m_textOrientation && m_widthVariant == other.m_widthVariant;
86 AtomicString m_family;
89 FontRenderingMode m_renderingMode;
90 FontOrientation m_orientation;
91 TextOrientation m_textOrientation;
92 FontWidthVariant m_widthVariant;
95 static unsigned hashTableDeletedSize() { return 0xFFFFFFFFU; }
98 inline unsigned computeHash(const FontPlatformDataCacheKey& fontKey)
100 unsigned hashCodes[5] = {
101 CaseFoldingHash::hash(fontKey.m_family),
104 fontKey.m_widthVariant,
105 static_cast<unsigned>(fontKey.m_textOrientation) << 4 | static_cast<unsigned>(fontKey.m_orientation) << 3 | static_cast<unsigned>(fontKey.m_italic) << 2 | static_cast<unsigned>(fontKey.m_printerFont) << 1 | static_cast<unsigned>(fontKey.m_renderingMode)
107 return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes);
110 struct FontPlatformDataCacheKeyHash {
111 static unsigned hash(const FontPlatformDataCacheKey& font)
113 return computeHash(font);
116 static bool equal(const FontPlatformDataCacheKey& a, const FontPlatformDataCacheKey& b)
121 static const bool safeToCompareToEmptyOrDeleted = true;
124 struct FontPlatformDataCacheKeyTraits : WTF::SimpleClassHashTraits<FontPlatformDataCacheKey> { };
126 typedef HashMap<FontPlatformDataCacheKey, FontPlatformData*, FontPlatformDataCacheKeyHash, FontPlatformDataCacheKeyTraits> FontPlatformDataCache;
128 static FontPlatformDataCache* gFontPlatformDataCache = 0;
130 static const AtomicString& alternateFamilyName(const AtomicString& familyName)
132 // Alias Courier <-> Courier New
133 DEFINE_STATIC_LOCAL(AtomicString, courier, ("Courier"));
134 DEFINE_STATIC_LOCAL(AtomicString, courierNew, ("Courier New"));
135 if (equalIgnoringCase(familyName, courier))
138 // On Windows, Courier New (truetype font) is always present and
139 // Courier is a bitmap font. So, we don't want to map Courier New to
141 if (equalIgnoringCase(familyName, courierNew))
145 // Alias Times and Times New Roman.
146 DEFINE_STATIC_LOCAL(AtomicString, times, ("Times"));
147 DEFINE_STATIC_LOCAL(AtomicString, timesNewRoman, ("Times New Roman"));
148 if (equalIgnoringCase(familyName, times))
149 return timesNewRoman;
150 if (equalIgnoringCase(familyName, timesNewRoman))
153 // Alias Arial and Helvetica
154 DEFINE_STATIC_LOCAL(AtomicString, arial, ("Arial"));
155 DEFINE_STATIC_LOCAL(AtomicString, helvetica, ("Helvetica"));
156 if (equalIgnoringCase(familyName, arial))
158 if (equalIgnoringCase(familyName, helvetica))
162 // On Windows, bitmap fonts are blocked altogether so that we have to
163 // alias MS Sans Serif (bitmap font) -> Microsoft Sans Serif (truetype font)
164 DEFINE_STATIC_LOCAL(AtomicString, msSans, ("MS Sans Serif"));
165 DEFINE_STATIC_LOCAL(AtomicString, microsoftSans, ("Microsoft Sans Serif"));
166 if (equalIgnoringCase(familyName, msSans))
167 return microsoftSans;
169 // Alias MS Serif (bitmap) -> Times New Roman (truetype font). There's no
170 // 'Microsoft Sans Serif-equivalent' for Serif.
171 static AtomicString msSerif("MS Serif");
172 if (equalIgnoringCase(familyName, msSerif))
173 return timesNewRoman;
179 FontPlatformData* FontCache::getCachedFontPlatformData(const FontDescription& fontDescription,
180 const AtomicString& familyName,
181 bool checkingAlternateName)
183 if (!gFontPlatformDataCache) {
184 gFontPlatformDataCache = new FontPlatformDataCache;
188 FontPlatformDataCacheKey key(familyName, fontDescription.computedPixelSize(), fontDescription.weight(), fontDescription.italic(),
189 fontDescription.usePrinterFont(), fontDescription.renderingMode(), fontDescription.orientation(),
190 fontDescription.textOrientation(), fontDescription.widthVariant());
191 FontPlatformData* result = 0;
193 FontPlatformDataCache::iterator it = gFontPlatformDataCache->find(key);
194 if (it == gFontPlatformDataCache->end()) {
195 result = createFontPlatformData(fontDescription, familyName);
196 gFontPlatformDataCache->set(key, result);
197 foundResult = result;
203 if (!foundResult && !checkingAlternateName) {
204 // We were unable to find a font. We have a small set of fonts that we alias to other names,
205 // e.g., Arial/Helvetica, Courier/Courier New, etc. Try looking up the font under the aliased name.
206 const AtomicString& alternateName = alternateFamilyName(familyName);
207 if (!alternateName.isEmpty())
208 result = getCachedFontPlatformData(fontDescription, alternateName, true);
210 gFontPlatformDataCache->set(key, new FontPlatformData(*result)); // Cache the result under the old name.
216 struct FontDataCacheKeyHash {
217 static unsigned hash(const FontPlatformData& platformData)
219 return platformData.hash();
222 static bool equal(const FontPlatformData& a, const FontPlatformData& b)
227 static const bool safeToCompareToEmptyOrDeleted = true;
230 struct FontDataCacheKeyTraits : WTF::GenericHashTraits<FontPlatformData> {
231 static const bool emptyValueIsZero = true;
232 static const bool needsDestruction = true;
233 static const FontPlatformData& emptyValue()
235 DEFINE_STATIC_LOCAL(FontPlatformData, key, (0.f, false, false));
238 static void constructDeletedValue(FontPlatformData& slot)
240 new (&slot) FontPlatformData(HashTableDeletedValue);
242 static bool isDeletedValue(const FontPlatformData& value)
244 return value.isHashTableDeletedValue();
248 typedef HashMap<FontPlatformData, pair<SimpleFontData*, unsigned>, FontDataCacheKeyHash, FontDataCacheKeyTraits> FontDataCache;
250 static FontDataCache* gFontDataCache = 0;
252 const int cMaxInactiveFontData = 120; // Pretty Low Threshold
253 const int cTargetInactiveFontData = 100;
254 static ListHashSet<const SimpleFontData*>* gInactiveFontData = 0;
256 SimpleFontData* FontCache::getCachedFontData(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName)
258 FontPlatformData* platformData = getCachedFontPlatformData(fontDescription, family, checkingAlternateName);
262 return getCachedFontData(platformData);
265 SimpleFontData* FontCache::getCachedFontData(const FontPlatformData* platformData)
270 if (!gFontDataCache) {
271 gFontDataCache = new FontDataCache;
272 gInactiveFontData = new ListHashSet<const SimpleFontData*>;
275 FontDataCache::iterator result = gFontDataCache->find(*platformData);
276 if (result == gFontDataCache->end()) {
277 pair<SimpleFontData*, unsigned> newValue(new SimpleFontData(*platformData), 1);
278 gFontDataCache->set(*platformData, newValue);
279 return newValue.first;
281 if (!result.get()->second.second++) {
282 ASSERT(gInactiveFontData->contains(result.get()->second.first));
283 gInactiveFontData->remove(result.get()->second.first);
286 return result.get()->second.first;
289 void FontCache::releaseFontData(const SimpleFontData* fontData)
291 ASSERT(gFontDataCache);
292 ASSERT(!fontData->isCustomFont());
294 FontDataCache::iterator it = gFontDataCache->find(fontData->platformData());
295 ASSERT(it != gFontDataCache->end());
297 if (!--it->second.second) {
298 gInactiveFontData->add(fontData);
299 if (gInactiveFontData->size() > cMaxInactiveFontData)
300 purgeInactiveFontData(gInactiveFontData->size() - cTargetInactiveFontData);
304 void FontCache::purgeInactiveFontData(int count)
306 if (!gInactiveFontData)
309 static bool isPurging; // Guard against reentry when e.g. a deleted FontData releases its small caps FontData.
315 Vector<const SimpleFontData*, 20> fontDataToDelete;
316 ListHashSet<const SimpleFontData*>::iterator end = gInactiveFontData->end();
317 ListHashSet<const SimpleFontData*>::iterator it = gInactiveFontData->begin();
318 for (int i = 0; i < count && it != end; ++it, ++i) {
319 const SimpleFontData* fontData = *it.get();
320 gFontDataCache->remove(fontData->platformData());
321 fontDataToDelete.append(fontData);
325 // Removed everything
326 gInactiveFontData->clear();
328 for (int i = 0; i < count; ++i)
329 gInactiveFontData->remove(gInactiveFontData->begin());
332 size_t fontDataToDeleteCount = fontDataToDelete.size();
333 for (size_t i = 0; i < fontDataToDeleteCount; ++i)
334 delete fontDataToDelete[i];
336 if (gFontPlatformDataCache) {
337 Vector<FontPlatformDataCacheKey> keysToRemove;
338 keysToRemove.reserveInitialCapacity(gFontPlatformDataCache->size());
339 FontPlatformDataCache::iterator platformDataEnd = gFontPlatformDataCache->end();
340 for (FontPlatformDataCache::iterator platformData = gFontPlatformDataCache->begin(); platformData != platformDataEnd; ++platformData) {
341 if (platformData->second && !gFontDataCache->contains(*platformData->second))
342 keysToRemove.append(platformData->first);
345 size_t keysToRemoveCount = keysToRemove.size();
346 for (size_t i = 0; i < keysToRemoveCount; ++i)
347 delete gFontPlatformDataCache->take(keysToRemove[i]);
353 size_t FontCache::fontDataCount()
356 return gFontDataCache->size();
360 size_t FontCache::inactiveFontDataCount()
362 if (gInactiveFontData)
363 return gInactiveFontData->size();
367 const FontData* FontCache::getFontData(const Font& font, int& familyIndex, FontSelector* fontSelector)
369 SimpleFontData* result = 0;
371 int startIndex = familyIndex;
372 const FontFamily* startFamily = &font.fontDescription().family();
373 for (int i = 0; startFamily && i < startIndex; i++)
374 startFamily = startFamily->next();
375 const FontFamily* currFamily = startFamily;
376 while (currFamily && !result) {
378 if (currFamily->family().length()) {
380 FontData* data = fontSelector->getFontData(font.fontDescription(), currFamily->family());
384 result = getCachedFontData(font.fontDescription(), currFamily->family());
386 currFamily = currFamily->next();
390 familyIndex = cAllFamiliesScanned;
393 // We didn't find a font. Try to find a similar font using our own specific knowledge about our platform.
394 // For example on OS X, we know to map any families containing the words Arabic, Pashto, or Urdu to the
396 result = getSimilarFontPlatformData(font);
398 if (!result && startIndex == 0) {
399 // If it's the primary font that we couldn't find, we try the following. In all other cases, we will
400 // just use per-character system fallback.
403 // Try the user's preferred standard font.
404 if (FontData* data = fontSelector->getFontData(font.fontDescription(), "-webkit-standard"))
408 // Still no result. Hand back our last resort fallback font.
409 result = getLastResortFallbackFont(font.fontDescription());
414 static HashSet<FontSelector*>* gClients;
416 void FontCache::addClient(FontSelector* client)
419 gClients = new HashSet<FontSelector*>;
421 ASSERT(!gClients->contains(client));
422 gClients->add(client);
425 void FontCache::removeClient(FontSelector* client)
428 ASSERT(gClients->contains(client));
430 gClients->remove(client);
433 static unsigned gGeneration = 0;
435 unsigned FontCache::generation()
440 void FontCache::invalidate()
443 ASSERT(!gFontPlatformDataCache);
447 if (gFontPlatformDataCache) {
448 deleteAllValues(*gFontPlatformDataCache);
449 delete gFontPlatformDataCache;
450 gFontPlatformDataCache = new FontPlatformDataCache;
455 Vector<RefPtr<FontSelector> > clients;
456 size_t numClients = gClients->size();
457 clients.reserveInitialCapacity(numClients);
458 HashSet<FontSelector*>::iterator end = gClients->end();
459 for (HashSet<FontSelector*>::iterator it = gClients->begin(); it != end; ++it)
462 ASSERT(numClients == clients.size());
463 for (size_t i = 0; i < numClients; ++i)
464 clients[i]->fontCacheInvalidated();
466 purgeInactiveFontData();
469 } // namespace WebCore