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