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