2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "include/private/SkMutex.h"
9 #include "src/core/SkTypefaceCache.h"
12 #define TYPEFACE_CACHE_LIMIT 1024
14 SkTypefaceCache::SkTypefaceCache() {}
16 void SkTypefaceCache::add(sk_sp<SkTypeface> face) {
17 if (fTypefaces.count() >= TYPEFACE_CACHE_LIMIT) {
18 this->purge(TYPEFACE_CACHE_LIMIT >> 2);
21 fTypefaces.emplace_back(std::move(face));
24 sk_sp<SkTypeface> SkTypefaceCache::findByProcAndRef(FindProc proc, void* ctx) const {
25 for (const sk_sp<SkTypeface>& typeface : fTypefaces) {
26 if (proc(typeface.get(), ctx)) {
33 void SkTypefaceCache::purge(int numToPurge) {
34 int count = fTypefaces.count();
37 if (fTypefaces[i]->unique()) {
38 fTypefaces.removeShuffle(i);
40 if (--numToPurge == 0) {
49 void SkTypefaceCache::purgeAll() {
50 this->purge(fTypefaces.count());
53 ///////////////////////////////////////////////////////////////////////////////
55 SkTypefaceCache& SkTypefaceCache::Get() {
56 static SkTypefaceCache gCache;
60 SkTypefaceID SkTypefaceCache::NewTypefaceID() {
61 static std::atomic<int32_t> nextID{1};
62 return nextID.fetch_add(1, std::memory_order_relaxed);
65 static SkMutex& typeface_cache_mutex() {
66 static SkMutex& mutex = *(new SkMutex);
70 void SkTypefaceCache::Add(sk_sp<SkTypeface> face) {
71 SkAutoMutexExclusive ama(typeface_cache_mutex());
72 Get().add(std::move(face));
75 sk_sp<SkTypeface> SkTypefaceCache::FindByProcAndRef(FindProc proc, void* ctx) {
76 SkAutoMutexExclusive ama(typeface_cache_mutex());
77 return Get().findByProcAndRef(proc, ctx);
80 void SkTypefaceCache::PurgeAll() {
81 SkAutoMutexExclusive ama(typeface_cache_mutex());
85 ///////////////////////////////////////////////////////////////////////////////
88 static bool DumpProc(SkTypeface* face, void* ctx) {
90 face->getFamilyName(&n);
91 SkFontStyle s = face->fontStyle();
92 SkTypefaceID id = face->uniqueID();
93 SkDebugf("SkTypefaceCache: face %p typefaceID %d weight %d width %d style %d name %s\n",
94 face, id, s.weight(), s.width(), s.slant(), n.c_str());
99 void SkTypefaceCache::Dump() {
101 (void)Get().findByProcAndRef(DumpProc, nullptr);