xref: /aosp_15_r20/external/skia/src/ports/SkFontMgr_FontConfigInterface.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkFontMgr.h"
9 #include "include/core/SkFontStyle.h"
10 #include "include/core/SkString.h"
11 #include "include/core/SkTypeface.h"
12 #include "include/ports/SkFontConfigInterface.h"
13 #include "include/ports/SkFontMgr_FontConfigInterface.h"
14 #include "include/private/base/SkMutex.h"
15 #include "src/core/SkFontDescriptor.h"
16 #include "src/core/SkResourceCache.h"
17 #include "src/core/SkTypefaceCache.h"
18 #include "src/ports/SkFontConfigTypeface.h"
19 #include "src/ports/SkTypeface_FreeType.h"
20 
21 #include <new>
22 
23 using namespace skia_private;
24 
onOpenStream(int * ttcIndex) const25 std::unique_ptr<SkStreamAsset> SkTypeface_FCI::onOpenStream(int* ttcIndex) const {
26     *ttcIndex =  this->getIdentity().fTTCIndex;
27     return std::unique_ptr<SkStreamAsset>(fFCI->openStream(this->getIdentity()));
28 }
29 
onMakeFontData() const30 std::unique_ptr<SkFontData> SkTypeface_FCI::onMakeFontData() const {
31     const SkFontConfigInterface::FontIdentity& id = this->getIdentity();
32     return std::make_unique<SkFontData>(std::unique_ptr<SkStreamAsset>(fFCI->openStream(id)),
33                                         id.fTTCIndex, 0, nullptr, 0, nullptr, 0);
34 }
35 
onGetFontDescriptor(SkFontDescriptor * desc,bool * serialize) const36 void SkTypeface_FCI::onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const {
37     SkString name;
38     this->getFamilyName(&name);
39     desc->setFamilyName(name.c_str());
40     desc->setStyle(this->fontStyle());
41     desc->setFactoryId(SkTypeface_FreeType::FactoryId);
42     *serialize = true;
43 }
44 
45 ///////////////////////////////////////////////////////////////////////////////
46 
47 class SkFontStyleSet_FCI : public SkFontStyleSet {
48 public:
SkFontStyleSet_FCI()49     SkFontStyleSet_FCI() {}
50 
count()51     int count() override { return 0; }
getStyle(int index,SkFontStyle *,SkString * style)52     void getStyle(int index, SkFontStyle*, SkString* style) override { SkASSERT(false); }
createTypeface(int index)53     sk_sp<SkTypeface> createTypeface(int index) override { SkASSERT(false); return nullptr; }
matchStyle(const SkFontStyle & pattern)54     sk_sp<SkTypeface> matchStyle(const SkFontStyle& pattern) override { return nullptr; }
55 };
56 
57 ///////////////////////////////////////////////////////////////////////////////
58 
59 class SkFontRequestCache {
60 public:
61     struct Request : public SkResourceCache::Key {
62     private:
RequestSkFontRequestCache::Request63         Request(const char* name, size_t nameLen, const SkFontStyle& style) : fStyle(style) {
64             /** Pointer to just after the last field of this class. */
65             char* content = const_cast<char*>(SkTAfter<const char>(&this->fStyle));
66 
67             // No holes.
68             SkASSERT(SkTAddOffset<char>(this, sizeof(SkResourceCache::Key) + keySize) == content);
69 
70             // Has a size divisible by size of uint32_t.
71             SkASSERT((content - reinterpret_cast<char*>(this)) % sizeof(uint32_t) == 0);
72 
73             size_t contentLen = SkAlign4(nameLen);
74             sk_careful_memcpy(content, name, nameLen);
75             sk_bzero(content + nameLen, contentLen - nameLen);
76             this->init(nullptr, 0, keySize + contentLen);
77         }
78         const SkFontStyle fStyle;
79         /** The sum of the sizes of the fields of this class. */
80         static const size_t keySize = sizeof(fStyle);
81 
82     public:
CreateSkFontRequestCache::Request83         static Request* Create(const char* name, const SkFontStyle& style) {
84             size_t nameLen = name ? strlen(name) : 0;
85             size_t contentLen = SkAlign4(nameLen);
86             char* storage = new char[sizeof(Request) + contentLen];
87             return new (storage) Request(name, nameLen, style);
88         }
operator deleteSkFontRequestCache::Request89         void operator delete(void* storage) {
90             delete[] reinterpret_cast<char*>(storage);
91         }
92     };
93 
94 
95 private:
96     struct Result : public SkResourceCache::Rec {
ResultSkFontRequestCache::Result97         Result(Request* request, sk_sp<SkTypeface> typeface)
98             : fRequest(request), fFace(std::move(typeface)) {}
99         Result(Result&&) = default;
100         Result& operator=(Result&&) = default;
101 
getKeySkFontRequestCache::Result102         const Key& getKey() const override { return *fRequest; }
bytesUsedSkFontRequestCache::Result103         size_t bytesUsed() const override { return fRequest->size() + sizeof(fFace); }
getCategorySkFontRequestCache::Result104         const char* getCategory() const override { return "request_cache"; }
diagnostic_only_getDiscardableSkFontRequestCache::Result105         SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; }
106 
107         std::unique_ptr<Request> fRequest;
108         sk_sp<SkTypeface> fFace;
109     };
110 
111     SkResourceCache fCachedResults;
112 
113 public:
SkFontRequestCache(size_t maxSize)114     SkFontRequestCache(size_t maxSize) : fCachedResults(maxSize) {}
115 
116     /** Takes ownership of request. It will be deleted when no longer needed. */
add(sk_sp<SkTypeface> face,Request * request)117     void add(sk_sp<SkTypeface> face, Request* request) {
118         fCachedResults.add(new Result(request, std::move(face)));
119     }
120     /** Does not take ownership of request. */
findAndRef(Request * request)121     sk_sp<SkTypeface> findAndRef(Request* request) {
122         sk_sp<SkTypeface> face;
123         fCachedResults.find(*request, [](const SkResourceCache::Rec& rec, void* context) -> bool {
124             const Result& result = static_cast<const Result&>(rec);
125             sk_sp<SkTypeface>* face = static_cast<sk_sp<SkTypeface>*>(context);
126 
127             *face = result.fFace;
128             return true;
129         }, &face);
130         return face;
131     }
132 };
133 
134 ///////////////////////////////////////////////////////////////////////////////
135 
find_by_FontIdentity(SkTypeface * cachedTypeface,void * ctx)136 static bool find_by_FontIdentity(SkTypeface* cachedTypeface, void* ctx) {
137     typedef SkFontConfigInterface::FontIdentity FontIdentity;
138     SkTypeface_FCI* cachedFCTypeface = static_cast<SkTypeface_FCI*>(cachedTypeface);
139     FontIdentity* identity = static_cast<FontIdentity*>(ctx);
140 
141     return cachedFCTypeface->getIdentity() == *identity;
142 }
143 
144 ///////////////////////////////////////////////////////////////////////////////
145 
146 class SkFontMgr_FCI : public SkFontMgr {
147     sk_sp<SkFontConfigInterface> fFCI;
148 
149     mutable SkMutex fMutex;
150     mutable SkTypefaceCache fTFCache;
151 
152     // The value of maxSize here is a compromise between cache hits and cache size.
153     // See https://crbug.com/424082#63 for reason for current size.
154     static const size_t kMaxSize = 1 << 15;
155     mutable SkFontRequestCache fCache;
156 
157 public:
SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci)158     SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci)
159         : fFCI(std::move(fci))
160         , fCache(kMaxSize)
161     {
162         SkASSERT_RELEASE(fFCI);
163     }
164 
165 protected:
onCountFamilies() const166     int onCountFamilies() const override {
167         SK_ABORT("Not implemented.");
168     }
169 
onGetFamilyName(int index,SkString * familyName) const170     void onGetFamilyName(int index, SkString* familyName) const override {
171         SK_ABORT("Not implemented.");
172     }
173 
onCreateStyleSet(int index) const174     sk_sp<SkFontStyleSet> onCreateStyleSet(int index) const override {
175         SK_ABORT("Not implemented.");
176     }
177 
onMatchFamily(const char familyName[]) const178     sk_sp<SkFontStyleSet> onMatchFamily(const char familyName[]) const override {
179         SK_ABORT("Not implemented.");
180     }
181 
onMatchFamilyStyle(const char requestedFamilyName[],const SkFontStyle & requestedStyle) const182     sk_sp<SkTypeface> onMatchFamilyStyle(const char requestedFamilyName[],
183                                          const SkFontStyle& requestedStyle) const override
184     {
185         SkAutoMutexExclusive ama(fMutex);
186 
187         // Check if this request is already in the request cache.
188         using Request = SkFontRequestCache::Request;
189         std::unique_ptr<Request> request(Request::Create(requestedFamilyName, requestedStyle));
190         sk_sp<SkTypeface> face = fCache.findAndRef(request.get());
191         if (face) {
192             return sk_sp<SkTypeface>(face);
193         }
194 
195         SkFontConfigInterface::FontIdentity identity;
196         SkString outFamilyName;
197         SkFontStyle outStyle;
198         if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle,
199                                    &identity, &outFamilyName, &outStyle))
200         {
201             return nullptr;
202         }
203 
204         // Check if a typeface with this FontIdentity is already in the FontIdentity cache.
205         face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity);
206         if (!face) {
207             face.reset(SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle));
208             // Add this FontIdentity to the FontIdentity cache.
209             fTFCache.add(face);
210         }
211         // Add this request to the request cache.
212         fCache.add(face, request.release());
213 
214         return face;
215     }
216 
onMatchFamilyStyleCharacter(const char familyName[],const SkFontStyle &,const char * bcp47[],int bcp47Count,SkUnichar character) const217     sk_sp<SkTypeface> onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&,
218                                             const char* bcp47[], int bcp47Count,
219                                             SkUnichar character) const override {
220         SK_ABORT("Not implemented.");
221     }
222 
onMakeFromData(sk_sp<SkData> data,int ttcIndex) const223     sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override {
224         return this->onMakeFromStreamIndex(SkMemoryStream::Make(std::move(data)), ttcIndex);
225     }
226 
onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,int ttcIndex) const227     sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
228                                             int ttcIndex) const override {
229         return this->makeFromStream(std::move(stream),
230                                     SkFontArguments().setCollectionIndex(ttcIndex));
231     }
232 
onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,const SkFontArguments & args) const233     sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,
234                                            const SkFontArguments& args) const override {
235         const size_t length = stream->getLength();
236         if (!length) {
237             return nullptr;
238         }
239         if (length >= 1024 * 1024 * 1024) {
240             return nullptr;  // don't accept too large fonts (>= 1GB) for safety.
241         }
242 
243         return SkTypeface_FreeType::MakeFromStream(std::move(stream), args);
244     }
245 
onMakeFromFile(const char path[],int ttcIndex) const246     sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override {
247         std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path);
248         return stream ? this->makeFromStream(std::move(stream), ttcIndex) : nullptr;
249     }
250 
onLegacyMakeTypeface(const char requestedFamilyName[],SkFontStyle requestedStyle) const251     sk_sp<SkTypeface> onLegacyMakeTypeface(const char requestedFamilyName[],
252                                            SkFontStyle requestedStyle) const override {
253         return this->onMatchFamilyStyle(requestedFamilyName, requestedStyle);
254     }
255 };
256 
SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci)257 SK_API sk_sp<SkFontMgr> SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci) {
258     SkASSERT(fci);
259     return sk_make_sp<SkFontMgr_FCI>(std::move(fci));
260 }
261