• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SkFontConfigInterface.h"
9 #include "SkFontConfigTypeface.h"
10 #include "SkFontDescriptor.h"
11 #include "SkFontMgr.h"
12 #include "SkFontMgr_FontConfigInterface.h"
13 #include "SkFontStyle.h"
14 #include "SkMakeUnique.h"
15 #include "SkMutex.h"
16 #include "SkString.h"
17 #include "SkTypeface.h"
18 #include "SkTypefaceCache.h"
19 #include "SkResourceCache.h"
20 #include <new>
21 
onOpenStream(int * ttcIndex) const22 std::unique_ptr<SkStreamAsset> SkTypeface_FCI::onOpenStream(int* ttcIndex) const {
23     *ttcIndex =  this->getIdentity().fTTCIndex;
24 
25     if (fFontData) {
26         SkStreamAsset* stream = fFontData->getStream();
27         if (!stream) {
28             return nullptr;
29         }
30         return stream->duplicate();
31     }
32 
33     return std::unique_ptr<SkStreamAsset>(fFCI->openStream(this->getIdentity()));
34 }
35 
onMakeFontData() const36 std::unique_ptr<SkFontData> SkTypeface_FCI::onMakeFontData() const {
37     if (fFontData) {
38         return skstd::make_unique<SkFontData>(*fFontData);
39     }
40 
41     const SkFontConfigInterface::FontIdentity& id = this->getIdentity();
42     return skstd::make_unique<SkFontData>(std::unique_ptr<SkStreamAsset>(fFCI->openStream(id)),
43                                           id.fTTCIndex, nullptr, 0);
44 }
45 
onGetFontDescriptor(SkFontDescriptor * desc,bool * isLocalStream) const46 void SkTypeface_FCI::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocalStream) const {
47     SkString name;
48     this->getFamilyName(&name);
49     desc->setFamilyName(name.c_str());
50     desc->setStyle(this->fontStyle());
51     *isLocalStream = SkToBool(fFontData);
52 }
53 
54 ///////////////////////////////////////////////////////////////////////////////
55 
56 class SkFontStyleSet_FCI : public SkFontStyleSet {
57 public:
SkFontStyleSet_FCI()58     SkFontStyleSet_FCI() {}
59 
count()60     int count() override { return 0; }
getStyle(int index,SkFontStyle *,SkString * style)61     void getStyle(int index, SkFontStyle*, SkString* style) override { SkASSERT(false); }
createTypeface(int index)62     SkTypeface* createTypeface(int index) override { SkASSERT(false); return nullptr; }
matchStyle(const SkFontStyle & pattern)63     SkTypeface* matchStyle(const SkFontStyle& pattern) override { return nullptr; }
64 };
65 
66 ///////////////////////////////////////////////////////////////////////////////
67 
68 class SkFontRequestCache {
69 public:
70     struct Request : public SkResourceCache::Key {
71     private:
RequestSkFontRequestCache::Request72         Request(const char* name, size_t nameLen, const SkFontStyle& style) : fStyle(style) {
73             /** Pointer to just after the last field of this class. */
74             char* content = const_cast<char*>(SkTAfter<const char>(&this->fStyle));
75 
76             // No holes.
77             SkASSERT(SkTAddOffset<char>(this, sizeof(SkResourceCache::Key) + keySize) == content);
78 
79             // Has a size divisible by size of uint32_t.
80             SkASSERT((content - reinterpret_cast<char*>(this)) % sizeof(uint32_t) == 0);
81 
82             size_t contentLen = SkAlign4(nameLen);
83             sk_careful_memcpy(content, name, nameLen);
84             sk_bzero(content + nameLen, contentLen - nameLen);
85             this->init(nullptr, 0, keySize + contentLen);
86         }
87         const SkFontStyle fStyle;
88         /** The sum of the sizes of the fields of this class. */
89         static const size_t keySize = sizeof(fStyle);
90 
91     public:
CreateSkFontRequestCache::Request92         static Request* Create(const char* name, const SkFontStyle& style) {
93             size_t nameLen = name ? strlen(name) : 0;
94             size_t contentLen = SkAlign4(nameLen);
95             char* storage = new char[sizeof(Request) + contentLen];
96             return new (storage) Request(name, nameLen, style);
97         }
operator deleteSkFontRequestCache::Request98         void operator delete(void* storage) {
99             delete[] reinterpret_cast<char*>(storage);
100         }
101     };
102 
103 
104 private:
105     struct Result : public SkResourceCache::Rec {
ResultSkFontRequestCache::Result106         Result(Request* request, sk_sp<SkTypeface> typeface)
107             : fRequest(request), fFace(std::move(typeface)) {}
108         Result(Result&&) = default;
109         Result& operator=(Result&&) = default;
110 
getKeySkFontRequestCache::Result111         const Key& getKey() const override { return *fRequest; }
bytesUsedSkFontRequestCache::Result112         size_t bytesUsed() const override { return fRequest->size() + sizeof(fFace); }
getCategorySkFontRequestCache::Result113         const char* getCategory() const override { return "request_cache"; }
diagnostic_only_getDiscardableSkFontRequestCache::Result114         SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; }
115 
116         std::unique_ptr<Request> fRequest;
117         sk_sp<SkTypeface> fFace;
118     };
119 
120     SkResourceCache fCachedResults;
121 
122 public:
SkFontRequestCache(size_t maxSize)123     SkFontRequestCache(size_t maxSize) : fCachedResults(maxSize) {}
124 
125     /** Takes ownership of request. It will be deleted when no longer needed. */
add(sk_sp<SkTypeface> face,Request * request)126     void add(sk_sp<SkTypeface> face, Request* request) {
127         fCachedResults.add(new Result(request, std::move(face)));
128     }
129     /** Does not take ownership of request. */
findAndRef(Request * request)130     sk_sp<SkTypeface> findAndRef(Request* request) {
131         sk_sp<SkTypeface> face;
132         fCachedResults.find(*request, [](const SkResourceCache::Rec& rec, void* context) -> bool {
133             const Result& result = static_cast<const Result&>(rec);
134             sk_sp<SkTypeface>* face = static_cast<sk_sp<SkTypeface>*>(context);
135 
136             *face = result.fFace;
137             return true;
138         }, &face);
139         return face;
140     }
141 };
142 
143 ///////////////////////////////////////////////////////////////////////////////
144 
find_by_FontIdentity(SkTypeface * cachedTypeface,void * ctx)145 static bool find_by_FontIdentity(SkTypeface* cachedTypeface, void* ctx) {
146     typedef SkFontConfigInterface::FontIdentity FontIdentity;
147     SkTypeface_FCI* cachedFCTypeface = static_cast<SkTypeface_FCI*>(cachedTypeface);
148     FontIdentity* identity = static_cast<FontIdentity*>(ctx);
149 
150     return cachedFCTypeface->getIdentity() == *identity;
151 }
152 
153 ///////////////////////////////////////////////////////////////////////////////
154 
155 class SkFontMgr_FCI : public SkFontMgr {
156     sk_sp<SkFontConfigInterface> fFCI;
157     SkTypeface_FreeType::Scanner fScanner;
158 
159     mutable SkMutex fMutex;
160     mutable SkTypefaceCache fTFCache;
161 
162     // The value of maxSize here is a compromise between cache hits and cache size.
163     // See https://crbug.com/424082#63 for reason for current size.
164     static const size_t kMaxSize = 1 << 15;
165     mutable SkFontRequestCache fCache;
166 
167 public:
SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci)168     SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci)
169         : fFCI(std::move(fci))
170         , fCache(kMaxSize)
171     {}
172 
173 protected:
onCountFamilies() const174     int onCountFamilies() const override {
175         SK_ABORT("Not implemented.");
176         return 0;
177     }
178 
onGetFamilyName(int index,SkString * familyName) const179     void onGetFamilyName(int index, SkString* familyName) const override {
180         SK_ABORT("Not implemented.");
181     }
182 
onCreateStyleSet(int index) const183     SkFontStyleSet* onCreateStyleSet(int index) const override {
184         SK_ABORT("Not implemented.");
185         return nullptr;
186     }
187 
onMatchFamily(const char familyName[]) const188     SkFontStyleSet* onMatchFamily(const char familyName[]) const override {
189         SK_ABORT("Not implemented.");
190         return new SkFontStyleSet_FCI();
191     }
192 
onMatchFamilyStyle(const char requestedFamilyName[],const SkFontStyle & requestedStyle) const193     SkTypeface* onMatchFamilyStyle(const char requestedFamilyName[],
194                                    const SkFontStyle& requestedStyle) const override
195     {
196         SkAutoMutexAcquire ama(fMutex);
197 
198         SkFontConfigInterface::FontIdentity identity;
199         SkString outFamilyName;
200         SkFontStyle outStyle;
201         if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle,
202                                    &identity, &outFamilyName, &outStyle))
203         {
204             return nullptr;
205         }
206 
207         // Check if a typeface with this FontIdentity is already in the FontIdentity cache.
208         sk_sp<SkTypeface> face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity);
209         if (!face) {
210             face.reset(SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle));
211             // Add this FontIdentity to the FontIdentity cache.
212             fTFCache.add(face);
213         }
214         return face.release();
215     }
216 
onMatchFamilyStyleCharacter(const char familyName[],const SkFontStyle &,const char * bcp47[],int bcp47Count,SkUnichar character) const217     SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&,
218                                             const char* bcp47[], int bcp47Count,
219                                             SkUnichar character) const override {
220         SK_ABORT("Not implemented.");
221         return nullptr;
222     }
223 
onMatchFaceStyle(const SkTypeface *,const SkFontStyle &) const224     SkTypeface* onMatchFaceStyle(const SkTypeface*, const SkFontStyle&) const override {
225         SK_ABORT("Not implemented.");
226         return nullptr;
227     }
228 
onMakeFromData(sk_sp<SkData> data,int ttcIndex) const229     sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override {
230         return this->onMakeFromStreamIndex(SkMemoryStream::Make(std::move(data)), ttcIndex);
231     }
232 
onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,int ttcIndex) const233     sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
234                                             int ttcIndex) 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         // TODO should the caller give us the style or should we get it from freetype?
244         SkString name;
245         SkFontStyle style;
246         bool isFixedPitch = false;
247         if (!fScanner.scanFont(stream.get(), 0, &name, &style, &isFixedPitch, nullptr)) {
248             return nullptr;
249         }
250 
251         auto fontData = skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, nullptr, 0);
252         return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name),
253                                                         style, isFixedPitch));
254     }
255 
onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,const SkFontArguments & args) const256     sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,
257                                            const SkFontArguments& args) const override {
258         using Scanner = SkTypeface_FreeType::Scanner;
259         const size_t length = stream->getLength();
260         if (!length) {
261             return nullptr;
262         }
263         if (length >= 1024 * 1024 * 1024) {
264             return nullptr;  // don't accept too large fonts (>= 1GB) for safety.
265         }
266 
267         bool isFixedPitch;
268         SkFontStyle style;
269         SkString name;
270         Scanner::AxisDefinitions axisDefinitions;
271         if (!fScanner.scanFont(stream.get(), args.getCollectionIndex(),
272                                &name, &style, &isFixedPitch, &axisDefinitions))
273         {
274             return nullptr;
275         }
276 
277         SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
278         Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
279                                    axisValues, name);
280 
281         auto fontData = skstd::make_unique<SkFontData>(std::move(stream),
282                                                        args.getCollectionIndex(),
283                                                        axisValues.get(),
284                                                        axisDefinitions.count());
285         return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name),
286                                                         style, isFixedPitch));
287     }
288 
onMakeFromFile(const char path[],int ttcIndex) const289     sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override {
290         std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path);
291         return stream ? this->makeFromStream(std::move(stream), ttcIndex) : nullptr;
292     }
293 
onLegacyMakeTypeface(const char requestedFamilyName[],SkFontStyle requestedStyle) const294     sk_sp<SkTypeface> onLegacyMakeTypeface(const char requestedFamilyName[],
295                                            SkFontStyle requestedStyle) const override
296     {
297         SkAutoMutexAcquire ama(fMutex);
298 
299         // Check if this request is already in the request cache.
300         using Request = SkFontRequestCache::Request;
301         std::unique_ptr<Request> request(Request::Create(requestedFamilyName, requestedStyle));
302         sk_sp<SkTypeface> face = fCache.findAndRef(request.get());
303         if (face) {
304             return sk_sp<SkTypeface>(face);
305         }
306 
307         SkFontConfigInterface::FontIdentity identity;
308         SkString outFamilyName;
309         SkFontStyle outStyle;
310         if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle,
311                                    &identity, &outFamilyName, &outStyle))
312         {
313             return nullptr;
314         }
315 
316         // Check if a typeface with this FontIdentity is already in the FontIdentity cache.
317         face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity);
318         if (!face) {
319             face.reset(SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle));
320             // Add this FontIdentity to the FontIdentity cache.
321             fTFCache.add(face);
322         }
323         // Add this request to the request cache.
324         fCache.add(face, request.release());
325 
326         return face;
327     }
328 };
329 
SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci)330 SK_API sk_sp<SkFontMgr> SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci) {
331     SkASSERT(fci);
332     return sk_make_sp<SkFontMgr_FCI>(std::move(fci));
333 }
334