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/SkDataTable.h"
9 #include "include/core/SkFontMgr.h"
10 #include "include/core/SkFontStyle.h"
11 #include "include/core/SkMath.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkStream.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkTypeface.h"
16 #include "include/core/SkTypes.h"
17 #include "include/private/SkFixed.h"
18 #include "include/private/SkMutex.h"
19 #include "include/private/SkTDArray.h"
20 #include "include/private/SkTemplates.h"
21 #include "src/core/SkAdvancedTypefaceMetrics.h"
22 #include "src/core/SkFontDescriptor.h"
23 #include "src/core/SkOSFile.h"
24 #include "src/core/SkTypefaceCache.h"
25 #include "src/ports/SkFontHost_FreeType_common.h"
26 
27 #include <fontconfig/fontconfig.h>
28 #include <string.h>
29 
30 class SkData;
31 
32 // FC_POSTSCRIPT_NAME was added with b561ff20 which ended up in 2.10.92
33 // Ubuntu 14.04 is on 2.11.0
34 // Debian 8 and 9 are on 2.11
35 // OpenSUSE Leap 42.1 is on 2.11.0 (42.3 is on 2.11.1)
36 // Fedora 24 is on 2.11.94
37 #ifndef FC_POSTSCRIPT_NAME
38 #    define FC_POSTSCRIPT_NAME  "postscriptname"
39 #endif
40 
41 /** Since FontConfig is poorly documented, this gives a high level overview:
42  *
43  *  FcConfig is a handle to a FontConfig configuration instance. Each 'configuration' is independent
44  *  from any others which may exist. There exists a default global configuration which is created
45  *  and destroyed by FcInit and FcFini, but this default should not normally be used.
46  *  Instead, one should use FcConfigCreate and FcInit* to have a named local state.
47  *
48  *  FcPatterns are {objectName -> [element]} (maps from object names to a list of elements).
49  *  Each element is some internal data plus an FcValue which is a variant (a union with a type tag).
50  *  Lists of elements are not typed, except by convention. Any collection of FcValues must be
51  *  assumed to be heterogeneous by the code, but the code need not do anything particularly
52  *  interesting if the values go against convention.
53  *
54  *  Somewhat like DirectWrite, FontConfig supports synthetics through FC_EMBOLDEN and FC_MATRIX.
55  *  Like all synthetic information, such information must be passed with the font data.
56  */
57 
58 namespace {
59 
60 // FontConfig was thread antagonistic until 2.10.91 with known thread safety issues until 2.13.93.
61 // Before that, lock with a global mutex.
62 // See https://bug.skia.org/1497 and cl/339089311 for background.
f_c_mutex()63 static SkMutex& f_c_mutex() {
64     static SkMutex& mutex = *(new SkMutex);
65     return mutex;
66 }
67 
68 class FCLocker {
69     inline static constexpr int FontConfigThreadSafeVersion = 21393;
70 
71     // Assume FcGetVersion() has always been thread safe.
72     static void lock() SK_NO_THREAD_SAFETY_ANALYSIS {
73         if (FcGetVersion() < FontConfigThreadSafeVersion) {
74             f_c_mutex().acquire();
75         }
76     }
77     static void unlock() SK_NO_THREAD_SAFETY_ANALYSIS {
78         AssertHeld();
79         if (FcGetVersion() < FontConfigThreadSafeVersion) {
80             f_c_mutex().release();
81         }
82     }
83 
84 public:
FCLocker()85     FCLocker() { lock(); }
~FCLocker()86     ~FCLocker() { unlock(); }
87 
AssertHeld()88     static void AssertHeld() { SkDEBUGCODE(
89         if (FcGetVersion() < FontConfigThreadSafeVersion) {
90             f_c_mutex().assertHeld();
91         }
92     ) }
93 };
94 
95 } // namespace
96 
FcTDestroy(T* t)97 template<typename T, void (*D)(T*)> void FcTDestroy(T* t) {
98     FCLocker::AssertHeld();
99     D(t);
100 }
101 template <typename T, T* (*C)(), void (*D)(T*)> class SkAutoFc
102     : public SkAutoTCallVProc<T, FcTDestroy<T, D>> {
103     using inherited = SkAutoTCallVProc<T, FcTDestroy<T, D>>;
104 public:
SkAutoFc()105     SkAutoFc() : SkAutoTCallVProc<T, FcTDestroy<T, D>>( C() ) {
106         T* obj = this->operator T*();
107         SkASSERT_RELEASE(nullptr != obj);
108     }
SkAutoFc(T* obj)109     explicit SkAutoFc(T* obj) : inherited(obj) {}
110     SkAutoFc(const SkAutoFc&) = delete;
SkAutoFc(SkAutoFc&& that)111     SkAutoFc(SkAutoFc&& that) : inherited(std::move(that)) {}
112 };
113 
114 typedef SkAutoFc<FcCharSet, FcCharSetCreate, FcCharSetDestroy> SkAutoFcCharSet;
115 typedef SkAutoFc<FcConfig, FcConfigCreate, FcConfigDestroy> SkAutoFcConfig;
116 typedef SkAutoFc<FcFontSet, FcFontSetCreate, FcFontSetDestroy> SkAutoFcFontSet;
117 typedef SkAutoFc<FcLangSet, FcLangSetCreate, FcLangSetDestroy> SkAutoFcLangSet;
118 typedef SkAutoFc<FcObjectSet, FcObjectSetCreate, FcObjectSetDestroy> SkAutoFcObjectSet;
119 typedef SkAutoFc<FcPattern, FcPatternCreate, FcPatternDestroy> SkAutoFcPattern;
120 
get_bool(FcPattern* pattern, const char object[], bool missing = false)121 static bool get_bool(FcPattern* pattern, const char object[], bool missing = false) {
122     FcBool value;
123     if (FcPatternGetBool(pattern, object, 0, &value) != FcResultMatch) {
124         return missing;
125     }
126     return value;
127 }
128 
get_int(FcPattern* pattern, const char object[], int missing)129 static int get_int(FcPattern* pattern, const char object[], int missing) {
130     int value;
131     if (FcPatternGetInteger(pattern, object, 0, &value) != FcResultMatch) {
132         return missing;
133     }
134     return value;
135 }
136 
get_string(FcPattern* pattern, const char object[], const char* missing = �)137 static const char* get_string(FcPattern* pattern, const char object[], const char* missing = "") {
138     FcChar8* value;
139     if (FcPatternGetString(pattern, object, 0, &value) != FcResultMatch) {
140         return missing;
141     }
142     return (const char*)value;
143 }
144 
get_matrix(FcPattern* pattern, const char object[])145 static const FcMatrix* get_matrix(FcPattern* pattern, const char object[]) {
146     FcMatrix* matrix;
147     if (FcPatternGetMatrix(pattern, object, 0, &matrix) != FcResultMatch) {
148         return nullptr;
149     }
150     return matrix;
151 }
152 
153 enum SkWeakReturn {
154     kIsWeak_WeakReturn,
155     kIsStrong_WeakReturn,
156     kNoId_WeakReturn
157 };
158 /** Ideally there  would exist a call like
159  *  FcResult FcPatternIsWeak(pattern, object, id, FcBool* isWeak);
160  *  Sometime after 2.12.4 FcPatternGetWithBinding was added which can retrieve the binding.
161  *
162  *  However, there is no such call and as of Fc 2.11.0 even FcPatternEquals ignores the weak bit.
163  *  Currently, the only reliable way of finding the weak bit is by its effect on matching.
164  *  The weak bit only affects the matching of FC_FAMILY and FC_POSTSCRIPT_NAME object values.
165  *  A element with the weak bit is scored after FC_LANG, without the weak bit is scored before.
166  *  Note that the weak bit is stored on the element, not on the value it holds.
167  */
is_weak(FcPattern* pattern, const char object[], int id)168 static SkWeakReturn is_weak(FcPattern* pattern, const char object[], int id) {
169     FCLocker::AssertHeld();
170 
171     FcResult result;
172 
173     // Create a copy of the pattern with only the value 'pattern'['object'['id']] in it.
174     // Internally, FontConfig pattern objects are linked lists, so faster to remove from head.
175     SkAutoFcObjectSet requestedObjectOnly(FcObjectSetBuild(object, nullptr));
176     SkAutoFcPattern minimal(FcPatternFilter(pattern, requestedObjectOnly));
177     FcBool hasId = true;
178     for (int i = 0; hasId && i < id; ++i) {
179         hasId = FcPatternRemove(minimal, object, 0);
180     }
181     if (!hasId) {
182         return kNoId_WeakReturn;
183     }
184     FcValue value;
185     result = FcPatternGet(minimal, object, 0, &value);
186     if (result != FcResultMatch) {
187         return kNoId_WeakReturn;
188     }
189     while (hasId) {
190         hasId = FcPatternRemove(minimal, object, 1);
191     }
192 
193     // Create a font set with two patterns.
194     // 1. the same 'object' as minimal and a lang object with only 'nomatchlang'.
195     // 2. a different 'object' from minimal and a lang object with only 'matchlang'.
196     SkAutoFcFontSet fontSet;
197 
198     SkAutoFcLangSet strongLangSet;
199     FcLangSetAdd(strongLangSet, (const FcChar8*)"nomatchlang");
200     SkAutoFcPattern strong(FcPatternDuplicate(minimal));
201     FcPatternAddLangSet(strong, FC_LANG, strongLangSet);
202 
203     SkAutoFcLangSet weakLangSet;
204     FcLangSetAdd(weakLangSet, (const FcChar8*)"matchlang");
205     SkAutoFcPattern weak;
206     FcPatternAddString(weak, object, (const FcChar8*)"nomatchstring");
207     FcPatternAddLangSet(weak, FC_LANG, weakLangSet);
208 
209     FcFontSetAdd(fontSet, strong.release());
210     FcFontSetAdd(fontSet, weak.release());
211 
212     // Add 'matchlang' to the copy of the pattern.
213     FcPatternAddLangSet(minimal, FC_LANG, weakLangSet);
214 
215     // Run a match against the copy of the pattern.
216     // If the 'id' was weak, then we should match the pattern with 'matchlang'.
217     // If the 'id' was strong, then we should match the pattern with 'nomatchlang'.
218 
219     // Note that this config is only used for FcFontRenderPrepare, which we don't even want.
220     // However, there appears to be no way to match/sort without it.
221     SkAutoFcConfig config;
222     FcFontSet* fontSets[1] = { fontSet };
223     SkAutoFcPattern match(FcFontSetMatch(config, fontSets, SK_ARRAY_COUNT(fontSets),
224                                          minimal, &result));
225 
226     FcLangSet* matchLangSet;
227     FcPatternGetLangSet(match, FC_LANG, 0, &matchLangSet);
228     return FcLangEqual == FcLangSetHasLang(matchLangSet, (const FcChar8*)"matchlang")
229                         ? kIsWeak_WeakReturn : kIsStrong_WeakReturn;
230 }
231 
232 /** Removes weak elements from either FC_FAMILY or FC_POSTSCRIPT_NAME objects in the property.
233  *  This can be quite expensive, and should not be used more than once per font lookup.
234  *  This removes all of the weak elements after the last strong element.
235  */
remove_weak(FcPattern* pattern, const char object[])236 static void remove_weak(FcPattern* pattern, const char object[]) {
237     FCLocker::AssertHeld();
238 
239     SkAutoFcObjectSet requestedObjectOnly(FcObjectSetBuild(object, nullptr));
240     SkAutoFcPattern minimal(FcPatternFilter(pattern, requestedObjectOnly));
241 
242     int lastStrongId = -1;
243     int numIds;
244     SkWeakReturn result;
245     for (int id = 0; ; ++id) {
246         result = is_weak(minimal, object, 0);
247         if (kNoId_WeakReturn == result) {
248             numIds = id;
249             break;
250         }
251         if (kIsStrong_WeakReturn == result) {
252             lastStrongId = id;
253         }
254         SkAssertResult(FcPatternRemove(minimal, object, 0));
255     }
256 
257     // If they were all weak, then leave the pattern alone.
258     if (lastStrongId < 0) {
259         return;
260     }
261 
262     // Remove everything after the last strong.
263     for (int id = lastStrongId + 1; id < numIds; ++id) {
264         SkAssertResult(FcPatternRemove(pattern, object, lastStrongId + 1));
265     }
266 }
267 
map_range(SkScalar value, SkScalar old_min, SkScalar old_max, SkScalar new_min, SkScalar new_max)268 static int map_range(SkScalar value,
269                      SkScalar old_min, SkScalar old_max,
270                      SkScalar new_min, SkScalar new_max)
271 {
272     SkASSERT(old_min < old_max);
273     SkASSERT(new_min <= new_max);
274     return new_min + ((value - old_min) * (new_max - new_min) / (old_max - old_min));
275 }
276 
277 struct MapRanges {
278     SkScalar old_val;
279     SkScalar new_val;
280 };
281 
282 static SkScalar map_ranges(SkScalar val, MapRanges const ranges[], int rangesCount) {
283     // -Inf to [0]
284     if (val < ranges[0].old_val) {
285         return ranges[0].new_val;
286     }
287 
288     // Linear from [i] to [i+1]
289     for (int i = 0; i < rangesCount - 1; ++i) {
290         if (val < ranges[i+1].old_val) {
291             return map_range(val, ranges[i].old_val, ranges[i+1].old_val,
292                                   ranges[i].new_val, ranges[i+1].new_val);
293         }
294     }
295 
296     // From [n] to +Inf
297     // if (fcweight < Inf)
298     return ranges[rangesCount-1].new_val;
299 }
300 
301 #ifndef FC_WEIGHT_DEMILIGHT
302 #define FC_WEIGHT_DEMILIGHT        65
303 #endif
304 
305 static SkFontStyle skfontstyle_from_fcpattern(FcPattern* pattern) {
306     typedef SkFontStyle SkFS;
307 
308     // FcWeightToOpenType was buggy until 2.12.4
309     static constexpr MapRanges weightRanges[] = {
310         { FC_WEIGHT_THIN,       SkFS::kThin_Weight },
311         { FC_WEIGHT_EXTRALIGHT, SkFS::kExtraLight_Weight },
312         { FC_WEIGHT_LIGHT,      SkFS::kLight_Weight },
313         { FC_WEIGHT_DEMILIGHT,  350 },
314         { FC_WEIGHT_BOOK,       380 },
315         { FC_WEIGHT_REGULAR,    SkFS::kNormal_Weight },
316         { FC_WEIGHT_MEDIUM,     SkFS::kMedium_Weight },
317         { FC_WEIGHT_DEMIBOLD,   SkFS::kSemiBold_Weight },
318         { FC_WEIGHT_BOLD,       SkFS::kBold_Weight },
319         { FC_WEIGHT_EXTRABOLD,  SkFS::kExtraBold_Weight },
320         { FC_WEIGHT_BLACK,      SkFS::kBlack_Weight },
321         { FC_WEIGHT_EXTRABLACK, SkFS::kExtraBlack_Weight },
322     };
323     SkScalar weight = map_ranges(get_int(pattern, FC_WEIGHT, FC_WEIGHT_REGULAR),
324                                  weightRanges, SK_ARRAY_COUNT(weightRanges));
325 
326     static constexpr MapRanges widthRanges[] = {
327         { FC_WIDTH_ULTRACONDENSED, SkFS::kUltraCondensed_Width },
328         { FC_WIDTH_EXTRACONDENSED, SkFS::kExtraCondensed_Width },
329         { FC_WIDTH_CONDENSED,      SkFS::kCondensed_Width },
330         { FC_WIDTH_SEMICONDENSED,  SkFS::kSemiCondensed_Width },
331         { FC_WIDTH_NORMAL,         SkFS::kNormal_Width },
332         { FC_WIDTH_SEMIEXPANDED,   SkFS::kSemiExpanded_Width },
333         { FC_WIDTH_EXPANDED,       SkFS::kExpanded_Width },
334         { FC_WIDTH_EXTRAEXPANDED,  SkFS::kExtraExpanded_Width },
335         { FC_WIDTH_ULTRAEXPANDED,  SkFS::kUltraExpanded_Width },
336     };
337     SkScalar width = map_ranges(get_int(pattern, FC_WIDTH, FC_WIDTH_NORMAL),
338                                 widthRanges, SK_ARRAY_COUNT(widthRanges));
339 
340     SkFS::Slant slant = SkFS::kUpright_Slant;
341     switch (get_int(pattern, FC_SLANT, FC_SLANT_ROMAN)) {
342         case FC_SLANT_ROMAN:   slant = SkFS::kUpright_Slant; break;
343         case FC_SLANT_ITALIC : slant = SkFS::kItalic_Slant ; break;
344         case FC_SLANT_OBLIQUE: slant = SkFS::kOblique_Slant; break;
345         default: SkASSERT(false); break;
346     }
347 
348     return SkFontStyle(SkScalarRoundToInt(weight), SkScalarRoundToInt(width), slant);
349 }
350 
351 static void fcpattern_from_skfontstyle(SkFontStyle style, FcPattern* pattern) {
352     FCLocker::AssertHeld();
353 
354     typedef SkFontStyle SkFS;
355 
356     // FcWeightFromOpenType was buggy until 2.12.4
357     static constexpr MapRanges weightRanges[] = {
358         { SkFS::kThin_Weight,       FC_WEIGHT_THIN },
359         { SkFS::kExtraLight_Weight, FC_WEIGHT_EXTRALIGHT },
360         { SkFS::kLight_Weight,      FC_WEIGHT_LIGHT },
361         { 350,                      FC_WEIGHT_DEMILIGHT },
362         { 380,                      FC_WEIGHT_BOOK },
363         { SkFS::kNormal_Weight,     FC_WEIGHT_REGULAR },
364         { SkFS::kMedium_Weight,     FC_WEIGHT_MEDIUM },
365         { SkFS::kSemiBold_Weight,   FC_WEIGHT_DEMIBOLD },
366         { SkFS::kBold_Weight,       FC_WEIGHT_BOLD },
367         { SkFS::kExtraBold_Weight,  FC_WEIGHT_EXTRABOLD },
368         { SkFS::kBlack_Weight,      FC_WEIGHT_BLACK },
369         { SkFS::kExtraBlack_Weight, FC_WEIGHT_EXTRABLACK },
370     };
371     int weight = map_ranges(style.weight(), weightRanges, SK_ARRAY_COUNT(weightRanges));
372 
373     static constexpr MapRanges widthRanges[] = {
374         { SkFS::kUltraCondensed_Width, FC_WIDTH_ULTRACONDENSED },
375         { SkFS::kExtraCondensed_Width, FC_WIDTH_EXTRACONDENSED },
376         { SkFS::kCondensed_Width,      FC_WIDTH_CONDENSED },
377         { SkFS::kSemiCondensed_Width,  FC_WIDTH_SEMICONDENSED },
378         { SkFS::kNormal_Width,         FC_WIDTH_NORMAL },
379         { SkFS::kSemiExpanded_Width,   FC_WIDTH_SEMIEXPANDED },
380         { SkFS::kExpanded_Width,       FC_WIDTH_EXPANDED },
381         { SkFS::kExtraExpanded_Width,  FC_WIDTH_EXTRAEXPANDED },
382         { SkFS::kUltraExpanded_Width,  FC_WIDTH_ULTRAEXPANDED },
383     };
384     int width = map_ranges(style.width(), widthRanges, SK_ARRAY_COUNT(widthRanges));
385 
386     int slant = FC_SLANT_ROMAN;
387     switch (style.slant()) {
388         case SkFS::kUpright_Slant: slant = FC_SLANT_ROMAN  ; break;
389         case SkFS::kItalic_Slant : slant = FC_SLANT_ITALIC ; break;
390         case SkFS::kOblique_Slant: slant = FC_SLANT_OBLIQUE; break;
391         default: SkASSERT(false); break;
392     }
393 
394     FcPatternAddInteger(pattern, FC_WEIGHT, weight);
395     FcPatternAddInteger(pattern, FC_WIDTH , width);
396     FcPatternAddInteger(pattern, FC_SLANT , slant);
397 }
398 
399 class SkTypeface_stream : public SkTypeface_FreeType {
400 public:
401     SkTypeface_stream(std::unique_ptr<SkFontData> data,
402                       SkString familyName, const SkFontStyle& style, bool fixedWidth)
403         : INHERITED(style, fixedWidth)
404         , fFamilyName(std::move(familyName))
405         , fData(std::move(data))
406     { }
407 
408     void onGetFamilyName(SkString* familyName) const override {
409         *familyName = fFamilyName;
410     }
411 
412     void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
413         *serialize = true;
414     }
415 
416     std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
417         *ttcIndex = fData->getIndex();
418         return fData->getStream()->duplicate();
419     }
420 
421     std::unique_ptr<SkFontData> onMakeFontData() const override {
422         return std::make_unique<SkFontData>(*fData);
423     }
424 
425     sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
426         std::unique_ptr<SkFontData> data = this->cloneFontData(args);
427         if (!data) {
428             return nullptr;
429         }
430         return sk_make_sp<SkTypeface_stream>(std::move(data),
431                                              fFamilyName,
432                                              this->fontStyle(),
433                                              this->isFixedPitch());
434     }
435 
436 private:
437     SkString fFamilyName;
438     const std::unique_ptr<const SkFontData> fData;
439 
440     using INHERITED = SkTypeface_FreeType;
441 };
442 
443 class SkTypeface_fontconfig : public SkTypeface_FreeType {
444 public:
445     static sk_sp<SkTypeface_fontconfig> Make(SkAutoFcPattern pattern, SkString sysroot) {
446         return sk_sp<SkTypeface_fontconfig>(new SkTypeface_fontconfig(std::move(pattern),
447                                                                       std::move(sysroot)));
448     }
449     mutable SkAutoFcPattern fPattern;  // Mutable for passing to FontConfig API.
450     const SkString fSysroot;
451 
452     void onGetFamilyName(SkString* familyName) const override {
453         *familyName = get_string(fPattern, FC_FAMILY);
454     }
455 
456     void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
457         FCLocker lock;
458         desc->setFamilyName(get_string(fPattern, FC_FAMILY));
459         desc->setFullName(get_string(fPattern, FC_FULLNAME));
460         desc->setPostscriptName(get_string(fPattern, FC_POSTSCRIPT_NAME));
461         desc->setStyle(this->fontStyle());
462         *serialize = false;
463     }
464 
465     std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
466         FCLocker lock;
467         *ttcIndex = get_int(fPattern, FC_INDEX, 0);
468         const char* filename = get_string(fPattern, FC_FILE);
469         // See FontAccessible for note on searching sysroot then non-sysroot path.
470         SkString resolvedFilename;
471         if (!fSysroot.isEmpty()) {
472             resolvedFilename = fSysroot;
473             resolvedFilename += filename;
474             if (sk_exists(resolvedFilename.c_str(), kRead_SkFILE_Flag)) {
475                 filename = resolvedFilename.c_str();
476             }
477         }
478         return SkStream::MakeFromFile(filename);
479     }
480 
481     void onFilterRec(SkScalerContextRec* rec) const override {
482         // FontConfig provides 10-scale-bitmap-fonts.conf which applies an inverse "pixelsize"
483         // matrix. It is not known if this .conf is active or not, so it is not clear if
484         // "pixelsize" should be applied before this matrix. Since using a matrix with a bitmap
485         // font isn't a great idea, only apply the matrix to outline fonts.
486         const FcMatrix* fcMatrix = get_matrix(fPattern, FC_MATRIX);
487         bool fcOutline = get_bool(fPattern, FC_OUTLINE, true);
488         if (fcOutline && fcMatrix) {
489             // fPost2x2 is column-major, left handed (y down).
490             // FcMatrix is column-major, right handed (y up).
491             SkMatrix fm;
492             fm.setAll(fcMatrix->xx,-fcMatrix->xy, 0,
493                      -fcMatrix->yx, fcMatrix->yy, 0,
494                       0           , 0           , 1);
495 
496             SkMatrix sm;
497             rec->getMatrixFrom2x2(&sm);
498 
499             sm.preConcat(fm);
500             rec->fPost2x2[0][0] = sm.getScaleX();
501             rec->fPost2x2[0][1] = sm.getSkewX();
502             rec->fPost2x2[1][0] = sm.getSkewY();
503             rec->fPost2x2[1][1] = sm.getScaleY();
504         }
505         if (get_bool(fPattern, FC_EMBOLDEN)) {
506             rec->fFlags |= SkScalerContext::kEmbolden_Flag;
507         }
508         this->INHERITED::onFilterRec(rec);
509     }
510 
511     std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override {
512         std::unique_ptr<SkAdvancedTypefaceMetrics> info =
513             this->INHERITED::onGetAdvancedMetrics();
514 
515         // Simulated fonts shouldn't be considered to be of the type of their data.
516         if (get_matrix(fPattern, FC_MATRIX) || get_bool(fPattern, FC_EMBOLDEN)) {
517             info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
518         }
519         return info;
520     }
521 
522     sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
523         std::unique_ptr<SkFontData> data = this->cloneFontData(args);
524         if (!data) {
525             return nullptr;
526         }
527 
528         SkString familyName;
529         this->getFamilyName(&familyName);
530 
531         return sk_make_sp<SkTypeface_stream>(std::move(data),
532                                              familyName,
533                                              this->fontStyle(),
534                                              this->isFixedPitch());
535     }
536 
537     std::unique_ptr<SkFontData> onMakeFontData() const override {
538         int index;
539         std::unique_ptr<SkStreamAsset> stream(this->onOpenStream(&index));
540         if (!stream) {
541             return nullptr;
542         }
543         // TODO: FC_VARIABLE and FC_FONT_VARIATIONS
544         return std::make_unique<SkFontData>(std::move(stream), index, nullptr, 0);
545     }
546 
547     ~SkTypeface_fontconfig() override {
548         // Hold the lock while unrefing the pattern.
549         FCLocker lock;
550         fPattern.reset();
551     }
552 
553 private:
554     SkTypeface_fontconfig(SkAutoFcPattern pattern, SkString sysroot)
555         : INHERITED(skfontstyle_from_fcpattern(pattern),
556                     FC_PROPORTIONAL != get_int(pattern, FC_SPACING, FC_PROPORTIONAL))
557         , fPattern(std::move(pattern))
558         , fSysroot(std::move(sysroot))
559     { }
560 
561     using INHERITED = SkTypeface_FreeType;
562 };
563 
564 class SkFontMgr_fontconfig : public SkFontMgr {
565     mutable SkAutoFcConfig fFC;  // Only mutable to avoid const cast when passed to FontConfig API.
566     const SkString fSysroot;
567     const sk_sp<SkDataTable> fFamilyNames;
568     const SkTypeface_FreeType::Scanner fScanner;
569 
570     class StyleSet : public SkFontStyleSet {
571     public:
572         StyleSet(sk_sp<SkFontMgr_fontconfig> parent, SkAutoFcFontSet fontSet)
573             : fFontMgr(std::move(parent)), fFontSet(std::move(fontSet))
574         { }
575 
576         ~StyleSet() override {
577             // Hold the lock while unrefing the font set.
578             FCLocker lock;
579             fFontSet.reset();
580         }
581 
582         int count() override { return fFontSet->nfont; }
583 
584         void getStyle(int index, SkFontStyle* style, SkString* styleName) override {
585             if (index < 0 || fFontSet->nfont <= index) {
586                 return;
587             }
588 
589             FCLocker lock;
590             if (style) {
591                 *style = skfontstyle_from_fcpattern(fFontSet->fonts[index]);
592             }
593             if (styleName) {
594                 *styleName = get_string(fFontSet->fonts[index], FC_STYLE);
595             }
596         }
597 
598         SkTypeface* createTypeface(int index) override {
599             if (index < 0 || fFontSet->nfont <= index) {
600                 return nullptr;
601             }
602             SkAutoFcPattern match([this, &index]() {
603                 FCLocker lock;
604                 FcPatternReference(fFontSet->fonts[index]);
605                 return fFontSet->fonts[index];
606             }());
607             return fFontMgr->createTypefaceFromFcPattern(std::move(match)).release();
608         }
609 
610         SkTypeface* matchStyle(const SkFontStyle& style) override {
611             SkAutoFcPattern match([this, &style]() {
612                 FCLocker lock;
613 
614                 SkAutoFcPattern pattern;
615                 fcpattern_from_skfontstyle(style, pattern);
616                 FcConfigSubstitute(fFontMgr->fFC, pattern, FcMatchPattern);
617                 FcDefaultSubstitute(pattern);
618 
619                 FcResult result;
620                 FcFontSet* fontSets[1] = { fFontSet };
621                 return FcFontSetMatch(fFontMgr->fFC,
622                                       fontSets, SK_ARRAY_COUNT(fontSets),
623                                       pattern, &result);
624 
625             }());
626             return fFontMgr->createTypefaceFromFcPattern(std::move(match)).release();
627         }
628 
629     private:
630         sk_sp<SkFontMgr_fontconfig> fFontMgr;
631         SkAutoFcFontSet fFontSet;
632     };
633 
634     static bool FindName(const SkTDArray<const char*>& list, const char* str) {
635         int count = list.count();
636         for (int i = 0; i < count; ++i) {
637             if (!strcmp(list[i], str)) {
638                 return true;
639             }
640         }
641         return false;
642     }
643 
644     static sk_sp<SkDataTable> GetFamilyNames(FcConfig* fcconfig) {
645         FCLocker lock;
646 
647         SkTDArray<const char*> names;
648         SkTDArray<size_t> sizes;
649 
650         static const FcSetName fcNameSet[] = { FcSetSystem, FcSetApplication };
651         for (int setIndex = 0; setIndex < (int)SK_ARRAY_COUNT(fcNameSet); ++setIndex) {
652             // Return value of FcConfigGetFonts must not be destroyed.
653             FcFontSet* allFonts(FcConfigGetFonts(fcconfig, fcNameSet[setIndex]));
654             if (nullptr == allFonts) {
655                 continue;
656             }
657 
658             for (int fontIndex = 0; fontIndex < allFonts->nfont; ++fontIndex) {
659                 FcPattern* current = allFonts->fonts[fontIndex];
660                 for (int id = 0; ; ++id) {
661                     FcChar8* fcFamilyName;
662                     FcResult result = FcPatternGetString(current, FC_FAMILY, id, &fcFamilyName);
663                     if (FcResultNoId == result) {
664                         break;
665                     }
666                     if (FcResultMatch != result) {
667                         continue;
668                     }
669                     const char* familyName = reinterpret_cast<const char*>(fcFamilyName);
670                     if (familyName && !FindName(names, familyName)) {
671                         *names.append() = familyName;
672                         *sizes.append() = strlen(familyName) + 1;
673                     }
674                 }
675             }
676         }
677 
678         return SkDataTable::MakeCopyArrays((void const *const *)names.begin(),
679                                            sizes.begin(), names.count());
680     }
681 
682     static bool FindByFcPattern(SkTypeface* cached, void* ctx) {
683         SkTypeface_fontconfig* cshFace = static_cast<SkTypeface_fontconfig*>(cached);
684         FcPattern* ctxPattern = static_cast<FcPattern*>(ctx);
685         return FcTrue == FcPatternEqual(cshFace->fPattern, ctxPattern);
686     }
687 
688     mutable SkMutex fTFCacheMutex;
689     mutable SkTypefaceCache fTFCache;
690     /** Creates a typeface using a typeface cache.
691      *  @param pattern a complete pattern from FcFontRenderPrepare.
692      */
693     sk_sp<SkTypeface> createTypefaceFromFcPattern(SkAutoFcPattern pattern) const {
694         if (!pattern) {
695             return nullptr;
696         }
697         // Cannot hold FCLocker when calling fTFCache.add; an evicted typeface may need to lock.
698         // Must hold fTFCacheMutex when interacting with fTFCache.
699         SkAutoMutexExclusive ama(fTFCacheMutex);
700         sk_sp<SkTypeface> face = [&]() {
701             FCLocker lock;
702             sk_sp<SkTypeface> face = fTFCache.findByProcAndRef(FindByFcPattern, pattern);
703             if (face) {
704                 pattern.reset();
705             }
706             return face;
707         }();
708         if (!face) {
709             face = SkTypeface_fontconfig::Make(std::move(pattern), fSysroot);
710             if (face) {
711                 // Cannot hold FCLocker in fTFCache.add; evicted typefaces may need to lock.
712                 fTFCache.add(face);
713             }
714         }
715         return face;
716     }
717 
718 public:
719     /** Takes control of the reference to 'config'. */
720     explicit SkFontMgr_fontconfig(FcConfig* config)
721         : fFC(config ? config : FcInitLoadConfigAndFonts())
722         , fSysroot(reinterpret_cast<const char*>(FcConfigGetSysRoot(fFC)))
723         , fFamilyNames(GetFamilyNames(fFC)) { }
724 
725     ~SkFontMgr_fontconfig() override {
726         // Hold the lock while unrefing the config.
727         FCLocker lock;
728         fFC.reset();
729     }
730 
731 protected:
732     int onCountFamilies() const override {
733         return fFamilyNames->count();
734     }
735 
736     void onGetFamilyName(int index, SkString* familyName) const override {
737         familyName->set(fFamilyNames->atStr(index));
738     }
739 
740     SkFontStyleSet* onCreateStyleSet(int index) const override {
741         return this->onMatchFamily(fFamilyNames->atStr(index));
742     }
743 
744     /** True if any string object value in the font is the same
745      *         as a string object value in the pattern.
746      */
747     static bool AnyMatching(FcPattern* font, FcPattern* pattern, const char* object) {
748         FcChar8* fontString;
749         FcChar8* patternString;
750         FcResult result;
751         // Set an arbitrary limit on the number of pattern object values to consider.
752         // TODO: re-write this to avoid N*M
753         static const int maxId = 16;
754         for (int patternId = 0; patternId < maxId; ++patternId) {
755             result = FcPatternGetString(pattern, object, patternId, &patternString);
756             if (FcResultNoId == result) {
757                 break;
758             }
759             if (FcResultMatch != result) {
760                 continue;
761             }
762             for (int fontId = 0; fontId < maxId; ++fontId) {
763                 result = FcPatternGetString(font, object, fontId, &fontString);
764                 if (FcResultNoId == result) {
765                     break;
766                 }
767                 if (FcResultMatch != result) {
768                     continue;
769                 }
770                 if (0 == FcStrCmpIgnoreCase(patternString, fontString)) {
771                     return true;
772                 }
773             }
774         }
775         return false;
776     }
777 
778     bool FontAccessible(FcPattern* font) const {
779         // FontConfig can return fonts which are unreadable.
780         const char* filename = get_string(font, FC_FILE, nullptr);
781         if (nullptr == filename) {
782             return false;
783         }
784 
785         // When sysroot was implemented in e96d7760886a3781a46b3271c76af99e15cb0146 (before 2.11.0)
786         // it was broken;  mostly fixed in d17f556153fbaf8fe57fdb4fc1f0efa4313f0ecf (after 2.11.1).
787         // This leaves Debian 8 and 9 with broken support for this feature.
788         // As a result, this feature should not be used until at least 2.11.91.
789         // The broken support is mostly around not making all paths relative to the sysroot.
790         // However, even at 2.13.1 it is possible to get a mix of sysroot and non-sysroot paths,
791         // as any added file path not lexically starting with the sysroot will be unchanged.
792         // To allow users to add local app files outside the sysroot,
793         // prefer the sysroot but also look without the sysroot.
794         if (!fSysroot.isEmpty()) {
795             SkString resolvedFilename;
796             resolvedFilename = fSysroot;
797             resolvedFilename += filename;
798             if (sk_exists(resolvedFilename.c_str(), kRead_SkFILE_Flag)) {
799                 return true;
800             }
801         }
802         return sk_exists(filename, kRead_SkFILE_Flag);
803     }
804 
805     static bool FontFamilyNameMatches(FcPattern* font, FcPattern* pattern) {
806         return AnyMatching(font, pattern, FC_FAMILY);
807     }
808 
809     static bool FontContainsCharacter(FcPattern* font, uint32_t character) {
810         FcResult result;
811         FcCharSet* matchCharSet;
812         for (int charSetId = 0; ; ++charSetId) {
813             result = FcPatternGetCharSet(font, FC_CHARSET, charSetId, &matchCharSet);
814             if (FcResultNoId == result) {
815                 break;
816             }
817             if (FcResultMatch != result) {
818                 continue;
819             }
820             if (FcCharSetHasChar(matchCharSet, character)) {
821                 return true;
822             }
823         }
824         return false;
825     }
826 
827     SkFontStyleSet* onMatchFamily(const char familyName[]) const override {
828         if (!familyName) {
829             return nullptr;
830         }
831         FCLocker lock;
832 
833         SkAutoFcPattern pattern;
834         FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
835         FcConfigSubstitute(fFC, pattern, FcMatchPattern);
836         FcDefaultSubstitute(pattern);
837 
838         FcPattern* matchPattern;
839         SkAutoFcPattern strongPattern(nullptr);
840         if (familyName) {
841             strongPattern.reset(FcPatternDuplicate(pattern));
842             remove_weak(strongPattern, FC_FAMILY);
843             matchPattern = strongPattern;
844         } else {
845             matchPattern = pattern;
846         }
847 
848         SkAutoFcFontSet matches;
849         // TODO: Some families have 'duplicates' due to symbolic links.
850         // The patterns are exactly the same except for the FC_FILE.
851         // It should be possible to collapse these patterns by normalizing.
852         static const FcSetName fcNameSet[] = { FcSetSystem, FcSetApplication };
853         for (int setIndex = 0; setIndex < (int)SK_ARRAY_COUNT(fcNameSet); ++setIndex) {
854             // Return value of FcConfigGetFonts must not be destroyed.
855             FcFontSet* allFonts(FcConfigGetFonts(fFC, fcNameSet[setIndex]));
856             if (nullptr == allFonts) {
857                 continue;
858             }
859 
860             for (int fontIndex = 0; fontIndex < allFonts->nfont; ++fontIndex) {
861                 FcPattern* font = allFonts->fonts[fontIndex];
862                 if (FontAccessible(font) && FontFamilyNameMatches(font, matchPattern)) {
863                     FcFontSetAdd(matches, FcFontRenderPrepare(fFC, pattern, font));
864                 }
865             }
866         }
867 
868         return new StyleSet(sk_ref_sp(this), std::move(matches));
869     }
870 
871     SkTypeface* onMatchFamilyStyle(const char familyName[],
872                                    const SkFontStyle& style) const override
873     {
874         SkAutoFcPattern font([this, &familyName, &style]() {
875             FCLocker lock;
876 
877             SkAutoFcPattern pattern;
878             FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
879             fcpattern_from_skfontstyle(style, pattern);
880             FcConfigSubstitute(fFC, pattern, FcMatchPattern);
881             FcDefaultSubstitute(pattern);
882 
883             // We really want to match strong (preferred) and same (acceptable) only here.
884             // If a family name was specified, assume that any weak matches after the last strong
885             // match are weak (default) and ignore them.
886             // After substitution the pattern for 'sans-serif' looks like "wwwwwwwwwwwwwwswww" where
887             // there are many weak but preferred names, followed by defaults.
888             // So it is possible to have weakly matching but preferred names.
889             // In aliases, bindings are weak by default, so this is easy and common.
890             // If no family name was specified, we'll probably only get weak matches, but that's ok.
891             FcPattern* matchPattern;
892             SkAutoFcPattern strongPattern(nullptr);
893             if (familyName) {
894                 strongPattern.reset(FcPatternDuplicate(pattern));
895                 remove_weak(strongPattern, FC_FAMILY);
896                 matchPattern = strongPattern;
897             } else {
898                 matchPattern = pattern;
899             }
900 
901             FcResult result;
902             SkAutoFcPattern font(FcFontMatch(fFC, pattern, &result));
903             if (!font || !FontAccessible(font) || !FontFamilyNameMatches(font, matchPattern)) {
904                 font.reset();
905             }
906             return font;
907         }());
908         return createTypefaceFromFcPattern(std::move(font)).release();
909     }
910 
911     SkTypeface* onMatchFamilyStyleCharacter(const char familyName[],
912                                             const SkFontStyle& style,
913                                             const char* bcp47[],
914                                             int bcp47Count,
915                                             SkUnichar character) const override
916     {
917         SkAutoFcPattern font([&](){
918             FCLocker lock;
919 
920             SkAutoFcPattern pattern;
921             if (familyName) {
922                 FcValue familyNameValue;
923                 familyNameValue.type = FcTypeString;
924                 familyNameValue.u.s = reinterpret_cast<const FcChar8*>(familyName);
925                 FcPatternAddWeak(pattern, FC_FAMILY, familyNameValue, FcFalse);
926             }
927             fcpattern_from_skfontstyle(style, pattern);
928 
929             SkAutoFcCharSet charSet;
930             FcCharSetAddChar(charSet, character);
931             FcPatternAddCharSet(pattern, FC_CHARSET, charSet);
932 
933             if (bcp47Count > 0) {
934                 SkASSERT(bcp47);
935                 SkAutoFcLangSet langSet;
936                 for (int i = bcp47Count; i --> 0;) {
937                     FcLangSetAdd(langSet, (const FcChar8*)bcp47[i]);
938                 }
939                 FcPatternAddLangSet(pattern, FC_LANG, langSet);
940             }
941 
942             FcConfigSubstitute(fFC, pattern, FcMatchPattern);
943             FcDefaultSubstitute(pattern);
944 
945             FcResult result;
946             SkAutoFcPattern font(FcFontMatch(fFC, pattern, &result));
947             if (!font || !FontAccessible(font) || !FontContainsCharacter(font, character)) {
948                 font.reset();
949             }
950             return font;
951         }());
952         return createTypefaceFromFcPattern(std::move(font)).release();
953     }
954 
955     sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
956                                             int ttcIndex) const override {
957         const size_t length = stream->getLength();
958         if (length <= 0 || (1u << 30) < length) {
959             return nullptr;
960         }
961 
962         SkString name;
963         SkFontStyle style;
964         bool isFixedWidth = false;
965         if (!fScanner.scanFont(stream.get(), ttcIndex, &name, &style, &isFixedWidth, nullptr)) {
966             return nullptr;
967         }
968 
969         auto data = std::make_unique<SkFontData>(std::move(stream), ttcIndex, nullptr, 0);
970         return sk_sp<SkTypeface>(new SkTypeface_stream(std::move(data), std::move(name),
971                                                        style, isFixedWidth));
972     }
973 
974     sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,
975                                            const SkFontArguments& args) const override {
976         using Scanner = SkTypeface_FreeType::Scanner;
977         bool isFixedPitch;
978         SkFontStyle style;
979         SkString name;
980         Scanner::AxisDefinitions axisDefinitions;
981         if (!fScanner.scanFont(stream.get(), args.getCollectionIndex(),
982                                &name, &style, &isFixedPitch, &axisDefinitions))
983         {
984             return nullptr;
985         }
986 
987         SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
988         Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
989                                    axisValues, name);
990 
991         auto data = std::make_unique<SkFontData>(std::move(stream), args.getCollectionIndex(),
992                                                    axisValues.get(), axisDefinitions.count());
993         return sk_sp<SkTypeface>(new SkTypeface_stream(std::move(data), std::move(name),
994                                                        style, isFixedPitch));
995     }
996 
997     sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override {
998         return this->makeFromStream(std::make_unique<SkMemoryStream>(std::move(data)), ttcIndex);
999     }
1000 
1001     sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override {
1002         return this->makeFromStream(SkStream::MakeFromFile(path), ttcIndex);
1003     }
1004 
1005     sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[], SkFontStyle style) const override {
1006         sk_sp<SkTypeface> typeface(this->matchFamilyStyle(familyName, style));
1007         if (typeface) {
1008             return typeface;
1009         }
1010 
1011         return sk_sp<SkTypeface>(this->matchFamilyStyle(nullptr, style));
1012     }
1013 };
1014 
1015 SK_API sk_sp<SkFontMgr> SkFontMgr_New_FontConfig(FcConfig* fc) {
1016     return sk_make_sp<SkFontMgr_fontconfig>(fc);
1017 }
1018