Debian Codegraph @

src/ports/SkFontMgr_android.cpp

raw
1 /*
2 * Copyright 2014 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/SkTypes.h"
9
10 #include "include/core/SkData.h"
11 #include "include/core/SkFontMgr.h"
12 #include "include/core/SkFontScanner.h"
13 #include "include/core/SkFontStyle.h"
14 #include "include/core/SkPaint.h"
15 #include "include/core/SkRefCnt.h"
16 #include "include/core/SkStream.h"
17 #include "include/core/SkString.h"
18 #include "include/ports/SkFontMgr_android.h"
19 #include "include/private/base/SkFixed.h"
20 #include "include/private/base/SkTArray.h"
21 #include "include/private/base/SkTDArray.h"
22 #include "include/private/base/SkTemplates.h"
23 #include "src/base/SkTSearch.h"
24 #include "src/core/SkFontDescriptor.h"
25 #include "src/core/SkOSFile.h"
26 #include "src/core/SkTHash.h"
27 #include "src/core/SkTypefaceCache.h"
28 #include "src/ports/SkFontMgr_android_parser.h"
29 #include "src/ports/SkTypeface_proxy.h"
30
31 #include <algorithm>
32 #include <limits>
33
34 using namespace skia_private;
35
36 class SkData;
37
38 namespace {
39
40 [[maybe_unused]] static inline const constexpr bool kSkFontMgrVerbose = false;
41
42 class SkTypeface_AndroidSystem : public SkTypeface_proxy {
43 public:
44 static sk_sp<SkTypeface_AndroidSystem> Make(sk_sp<SkTypeface> realTypeface,
45 const SkFontStyle& style,
46 bool isFixedPitch,
47 const SkString& familyName,
48 const TArray<SkLanguage, true>& lang,
49 FontVariant variantStyle) {
50 SkASSERT(realTypeface);
51 return sk_sp(new SkTypeface_AndroidSystem(std::move(realTypeface),
52 style, isFixedPitch,
53 familyName, lang, variantStyle));
54 }
55
56 const SkString fFamilyName;
57 const STArray<4, SkLanguage, true> fLang;
58 const FontVariant fVariantStyle;
59
60 protected:
61 SkTypeface_AndroidSystem(sk_sp<SkTypeface> realTypeface,
62 const SkFontStyle& style,
63 bool isFixedPitch,
64 const SkString& familyName,
65 const TArray<SkLanguage, true>& lang,
66 FontVariant variantStyle)
67 : SkTypeface_proxy(std::move(realTypeface), style, isFixedPitch)
68 , fFamilyName(familyName)
69 , fLang(lang)
70 , fVariantStyle(variantStyle)
71 {}
72
73 void onGetFamilyName(SkString* familyName) const override {
74 *familyName = fFamilyName;
75 }
76
77 sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
78 auto proxy = SkTypeface_proxy::onMakeClone(args);
79 if (proxy == nullptr) {
80 return nullptr;
81 }
82 return SkTypeface_AndroidSystem::Make(std::move(proxy),
83 this->fontStyle(), this->isFixedPitch(),
84 fFamilyName, fLang, fVariantStyle);
85 }
86
87 void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
88 SkTypeface_proxy::onGetFontDescriptor(desc, serialize);
89
90 SkASSERT(desc);
91 SkASSERT(serialize);
92 desc->setFamilyName(fFamilyName.c_str());
93 desc->setStyle(this->fontStyle());
94 *serialize = false;
95 }
96
97 SkFontStyle onGetFontStyle() const override {
98 return SkTypeface::onGetFontStyle();
99 }
100
101 bool onGetFixedPitch() const override {
102 return SkTypeface::onGetFixedPitch();
103 }
104 };
105
106 template <typename D, typename S> sk_sp<D> sk_sp_static_cast(sk_sp<S>&& s) {
107 return sk_sp<D>(static_cast<D*>(s.release()));
108 }
109
110 using StreamForPathCache = skia_private::THashMap<SkString, std::unique_ptr<SkStreamAsset>>;
111
112 class SkFontStyleSet_Android : public SkFontStyleSet {
113 public:
114 explicit SkFontStyleSet_Android(const FontFamily& family, const SkFontScanner* scanner,
115 const bool cacheFontFiles, StreamForPathCache& streamForPath) {
116 const SkString* cannonicalFamilyName = nullptr;
117 if (!family.fNames.empty()) {
118 cannonicalFamilyName = &family.fNames[0];
119 }
120 fFallbackFor = family.fFallbackFor;
121
122 // TODO? make this lazy
123 for (int i = 0; i < family.fFonts.size(); ++i) {
124 const FontFileInfo& fontFile = family.fFonts[i];
125
126 SkString pathName(family.fBasePath);
127 pathName.append(fontFile.fFileName);
128
129 std::unique_ptr<SkStreamAsset>* streamPtr = streamForPath.find(pathName);
130 if (!streamPtr) {
131 streamPtr = streamForPath.set(pathName, SkStream::MakeFromFile(pathName.c_str()));
132 }
133 if (!*streamPtr) {
134 SkDEBUGF("Requested font file %s cannot be opened.\n", pathName.c_str());
135 continue;
136 }
137 std::unique_ptr<SkStreamAsset> stream = (*streamPtr)->duplicate();
138 if (!stream) {
139 SkDEBUGF("Requested font file %s could not be duplicated.\n", pathName.c_str());
140 continue;
141 }
142
143 SkFontArguments::VariationPosition position = {
144 fontFile.fVariationDesignPosition.begin(),
145 fontFile.fVariationDesignPosition.size()
146 };
147 // TODO: this creates the proxy with the given stream, so always cacheFontFiles.
148 auto proxy = scanner->MakeFromStream(
149 std::move(stream),
150 SkFontArguments().setCollectionIndex(fontFile.fIndex)
151 .setVariationDesignPosition(position));
152 if (!proxy) {
153 SkDEBUGF("Requested font file %s does not have valid font data.\n",
154 pathName.c_str());
155 continue;
156 }
157
158 uint32_t variant = family.fVariant;
159 if (kDefault_FontVariant == variant) {
160 variant = kCompact_FontVariant | kElegant_FontVariant;
161 }
162
163 // The first specified family name overrides the family name found in the font.
164 // TODO: SkTypeface_AndroidSystem::onCreateFamilyNameIterator should return
165 // all of the specified family names in addition to the names found in the font.
166 SkString familyName;
167 proxy->getFamilyName(&familyName);
168 if (cannonicalFamilyName != nullptr) {
169 familyName = *cannonicalFamilyName;
170 }
171
172 SkFontStyle fontStyle = proxy->fontStyle();
173 int weight = fontFile.fWeight != 0 ? fontFile.fWeight : fontStyle.weight();
174 SkFontStyle::Slant slant = fontStyle.slant();
175 switch (fontFile.fStyle) {
176 case FontFileInfo::Style::kAuto: slant = fontStyle.slant(); break;
177 case FontFileInfo::Style::kNormal: slant = SkFontStyle::kUpright_Slant; break;
178 case FontFileInfo::Style::kItalic: slant = SkFontStyle::kItalic_Slant; break;
179 default: SkASSERT(false); break;
180 }
181 fontStyle = SkFontStyle(weight, fontStyle.width(), slant);
182
183 fStyles.push_back(
184 SkTypeface_AndroidSystem::Make(proxy,
185 fontStyle, proxy->isFixedPitch(),
186 familyName, family.fLanguages, variant));
187 }
188 }
189
190 int count() override {
191 return fStyles.size();
192 }
193 void getStyle(int index, SkFontStyle* style, SkString* name) override {
194 if (index < 0 || fStyles.size() <= index) {
195 return;
196 }
197 if (style) {
198 *style = fStyles[index]->fontStyle();
199 }
200 if (name) {
201 name->reset();
202 }
203 }
204 sk_sp<SkTypeface> createTypeface(int index) override {
205 if (index < 0 || fStyles.size() <= index) {
206 return nullptr;
207 }
208 return fStyles[index];
209 }
210
211 sk_sp<SkTypeface_AndroidSystem> matchAStyle(const SkFontStyle& pattern) {
212 return sk_sp_static_cast<SkTypeface_AndroidSystem>(this->matchStyleCSS3(pattern));
213 }
214 sk_sp<SkTypeface> matchStyle(const SkFontStyle& pattern) override {
215 return this->matchAStyle(pattern);
216 }
217
218 private:
219 TArray<sk_sp<SkTypeface_AndroidSystem>> fStyles;
220 SkString fFallbackFor;
221
222 friend struct NameToFamily;
223 friend class SkFontMgr_Android;
224
225 using INHERITED = SkFontStyleSet;
226 };
227
228 /** On Android a single family can have many names, but our API assumes unique names.
229 * Map names to the back end so that all names for a given family refer to the same
230 * (non-replicated) set of typefaces.
231 * SkTDict<> doesn't let us do index-based lookup, so we write our own mapping.
232 */
233 struct NameToFamily {
234 SkString name;
235 SkFontStyleSet_Android* styleSet;
236 };
237
238 class SkFontMgr_Android : public SkFontMgr {
239 public:
240 SkFontMgr_Android(const SkFontMgr_Android_CustomFonts* custom,
241 std::unique_ptr<SkFontScanner> scanner)
242 : fScanner(std::move(scanner)) {
243 std::vector<std::unique_ptr<FontFamily>> families;
244 if (custom && SkFontMgr_Android_CustomFonts::kPreferSystem != custom->fSystemFontUse) {
245 SkString base(custom->fBasePath);
246 SkFontMgr_Android_Parser::GetCustomFontFamilies(
247 families, base, custom->fFontsXml, custom->fFallbackFontsXml);
248 }
249 if (!custom ||
250 (custom && SkFontMgr_Android_CustomFonts::kOnlyCustom != custom->fSystemFontUse))
251 {
252 SkFontMgr_Android_Parser::GetSystemFontFamilies(families);
253 }
254 if (custom && SkFontMgr_Android_CustomFonts::kPreferSystem == custom->fSystemFontUse) {
255 SkString base(custom->fBasePath);
256 SkFontMgr_Android_Parser::GetCustomFontFamilies(
257 families, base, custom->fFontsXml, custom->fFallbackFontsXml);
258 }
259 this->buildNameToFamilyMap(families, custom ? custom->fIsolated : false);
260 this->findDefaultStyleSet();
261 }
262
263 protected:
264 /** Returns not how many families we have, but how many unique names
265 * exist among the families.
266 */
267 int onCountFamilies() const override {
268 return fNameToFamilyMap.size();
269 }
270
271 void onGetFamilyName(int index, SkString* familyName) const override {
272 if (index < 0 || fNameToFamilyMap.size() <= index) {
273 familyName->reset();
274 return;
275 }
276 familyName->set(fNameToFamilyMap[index].name);
277 }
278
279 sk_sp<SkFontStyleSet> onCreateStyleSet(int index) const override {
280 if (index < 0 || fNameToFamilyMap.size() <= index) {
281 return nullptr;
282 }
283 return sk_ref_sp(fNameToFamilyMap[index].styleSet);
284 }
285
286 sk_sp<SkFontStyleSet> onMatchFamily(const char familyName[]) const override {
287 if (!familyName) {
288 return nullptr;
289 }
290 SkAutoAsciiToLC tolc(familyName);
291 for (int i = 0; i < fNameToFamilyMap.size(); ++i) {
292 if (fNameToFamilyMap[i].name.equals(tolc.lc())) {
293 return sk_ref_sp(fNameToFamilyMap[i].styleSet);
294 }
295 }
296 // TODO: eventually we should not need to name fallback families.
297 for (int i = 0; i < fFallbackNameToFamilyMap.size(); ++i) {
298 if (fFallbackNameToFamilyMap[i].name.equals(tolc.lc())) {
299 return sk_ref_sp(fFallbackNameToFamilyMap[i].styleSet);
300 }
301 }
302 return nullptr;
303 }
304
305 sk_sp<SkTypeface> onMatchFamilyStyle(const char familyName[],
306 const SkFontStyle& style) const override {
307 sk_sp<SkFontStyleSet> sset(this->matchFamily(familyName));
308 return sset->matchStyle(style);
309 }
310
311 enum class NameType { Self, Fallback };
312 static sk_sp<SkTypeface_AndroidSystem> find_family_style_character(
313 const SkString& familyName,
314 const TArray<NameToFamily, true>& nameToFamilyMap,
315 NameType nameType,
316 const SkFontStyle& style, bool elegant,
317 const SkString& langTag, SkUnichar character)
318 {
319 for (auto&& nameToFamily : nameToFamilyMap) {
320 SkFontStyleSet_Android* family = nameToFamily.styleSet;
321 if (!familyName.isEmpty()) {
322 const SkString& name = nameType == NameType::Self ? nameToFamily.name
323 : family->fFallbackFor;
324 if (familyName != name) {
325 continue;
326 }
327 }
328 sk_sp<SkTypeface_AndroidSystem> face(family->matchAStyle(style));
329
330 if (!langTag.isEmpty() &&
331 std::none_of(face->fLang.begin(), face->fLang.end(), [&](const SkLanguage& lang){
332 return lang.getTag().startsWith(langTag.c_str());
333 }))
334 {
335 continue;
336 }
337
338 if (SkToBool(face->fVariantStyle & kElegant_FontVariant) != elegant) {
339 continue;
340 }
341
342 if (face->unicharToGlyph(character) != 0) {
343 return face;
344 }
345 }
346 return nullptr;
347 }
348
349 sk_sp<SkTypeface> onMatchFamilyStyleCharacter(const char familyName[],
350 const SkFontStyle& style,
351 const char* bcp47[],
352 int bcp47Count,
353 SkUnichar character) const override {
354 // The variant 'elegant' is 'not squashed', 'compact' is 'stays in ascent/descent'.
355 // The variant 'default' means 'compact and elegant'.
356 // As a result, it is not possible to know the variant context from the font alone.
357 // TODO: add 'is_elegant' and 'is_compact' bits to 'style' request.
358 sk_sp<SkTypeface_AndroidSystem> matchingTypeface;
359 SkString familyNameString(familyName);
360 for (const SkString& currentFamilyName : { familyNameString, SkString() }) {
361 // The first time match anything elegant, second time anything not elegant.
362 for (int elegant = 2; elegant --> 0;) {
363 for (int bcp47Index = bcp47Count; bcp47Index --> 0;) {
364 SkLanguage lang(bcp47[bcp47Index]);
365 while (!lang.getTag().isEmpty()) {
366 matchingTypeface = find_family_style_character(
367 currentFamilyName, fNameToFamilyMap, NameType::Self,
368 style, SkToBool(elegant), lang.getTag(), character);
369 if (matchingTypeface) {
370 return matchingTypeface;
371 }
372 matchingTypeface = find_family_style_character(
373 currentFamilyName, fFallbackNameToFamilyMap, NameType::Fallback,
374 style, SkToBool(elegant), lang.getTag(), character);
375 if (matchingTypeface) {
376 return matchingTypeface;
377 }
378
379 lang = lang.getParent();
380 }
381 }
382 matchingTypeface = find_family_style_character(
383 currentFamilyName, fNameToFamilyMap, NameType::Self,
384 style, SkToBool(elegant), SkString(), character);
385 if (matchingTypeface) {
386 return matchingTypeface;
387 }
388 matchingTypeface = find_family_style_character(
389 currentFamilyName, fFallbackNameToFamilyMap, NameType::Fallback,
390 style, SkToBool(elegant), SkString(), character);
391 if (matchingTypeface) {
392 return matchingTypeface;
393 }
394 }
395 }
396 return nullptr;
397 }
398
399 sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override {
400 return this->makeFromStream(std::unique_ptr<SkStreamAsset>(new SkMemoryStream(std::move(data))),
401 ttcIndex);
402 }
403
404 sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override {
405 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path);
406 return stream ? this->makeFromStream(std::move(stream), ttcIndex) : nullptr;
407 }
408
409 sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
410 int ttcIndex) const override {
411 return this->makeFromStream(std::move(stream),
412 SkFontArguments().setCollectionIndex(ttcIndex));
413 }
414
415 sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,
416 const SkFontArguments& args) const override {
417 return fScanner->MakeFromStream(std::move(stream), args);
418 }
419
420 sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[], SkFontStyle style) const override {
421 if (familyName) {
422 // On Android, we must return nullptr when we can't find the requested
423 // named typeface so that the system/app can provide their own recovery
424 // mechanism. On other platforms we'd provide a typeface from the
425 // default family instead.
426 return sk_sp<SkTypeface>(this->onMatchFamilyStyle(familyName, style));
427 }
428 if (fDefaultStyleSet) {
429 return sk_sp<SkTypeface>(fDefaultStyleSet->matchStyle(style));
430 }
431 return SkTypeface::MakeEmpty();
432 }
433
434
435 private:
436
437 std::unique_ptr<SkFontScanner> fScanner;
438
439 TArray<sk_sp<SkFontStyleSet_Android>> fStyleSets;
440 sk_sp<SkFontStyleSet> fDefaultStyleSet;
441
442 TArray<NameToFamily, true> fNameToFamilyMap;
443 TArray<NameToFamily, true> fFallbackNameToFamilyMap;
444
445 void addFamily(FontFamily& family, const bool isolated, int familyIndex,
446 StreamForPathCache& streamForPath)
447 {
448 TArray<NameToFamily, true>* nameToFamily = &fNameToFamilyMap;
449 if (family.fIsFallbackFont) {
450 nameToFamily = &fFallbackNameToFamilyMap;
451
452 if (family.fNames.empty()) {
453 SkString& fallbackName = family.fNames.push_back();
454 fallbackName.printf("%.2x##fallback", (uint32_t)familyIndex);
455 }
456 }
457
458 sk_sp<SkFontStyleSet_Android> newSet =
459 sk_make_sp<SkFontStyleSet_Android>(family, fScanner.get(), isolated, streamForPath);
460 if (0 == newSet->count()) {
461 return;
462 }
463
464 for (const SkString& name : family.fNames) {
465 nameToFamily->emplace_back(NameToFamily{name, newSet.get()});
466 }
467 fStyleSets.emplace_back(std::move(newSet));
468 }
469 void buildNameToFamilyMap(std::vector<std::unique_ptr<FontFamily>>& families,
470 const bool isolated) {
471 StreamForPathCache streamForPath;
472 int familyIndex = 0;
473 for (std::unique_ptr<FontFamily>& family : families) {
474 addFamily(*family, isolated, familyIndex++, streamForPath);
475 for (const auto& [unused, fallbackFamily] : family->fallbackFamilies) {
476 addFamily(*fallbackFamily, isolated, familyIndex++, streamForPath);
477 }
478 }
479 }
480
481 void findDefaultStyleSet() {
482 static const char* defaultNames[] = { "sans-serif" };
483 for (const char* defaultName : defaultNames) {
484 fDefaultStyleSet = this->onMatchFamily(defaultName);
485 if (fDefaultStyleSet) {
486 break;
487 }
488 }
489 if (!fDefaultStyleSet && !fStyleSets.empty()) {
490 fDefaultStyleSet = fStyleSets[0];
491 }
492 }
493
494 using INHERITED = SkFontMgr;
495 };
496
497 #ifdef SK_DEBUG
498 static char const * const gSystemFontUseStrings[] = {
499 "OnlyCustom", "PreferCustom", "PreferSystem"
500 };
501 #endif
502
503 } // namespace
504
505 sk_sp<SkFontMgr> SkFontMgr_New_Android(const SkFontMgr_Android_CustomFonts* custom,
506 std::unique_ptr<SkFontScanner> scanner) {
507 if (custom) {
508 SkASSERT(0 <= custom->fSystemFontUse);
509 SkASSERT(custom->fSystemFontUse < std::size(gSystemFontUseStrings));
510 if constexpr (kSkFontMgrVerbose) {
511 SkDEBUGF("SystemFontUse: %s BasePath: %s Fonts: %s FallbackFonts: %s\n",
512 gSystemFontUseStrings[custom->fSystemFontUse],
513 custom->fBasePath,
514 custom->fFontsXml,
515 custom->fFallbackFontsXml);
516 }
517 }
518 return sk_make_sp<SkFontMgr_Android>(custom, std::move(scanner));
519 }