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.
lock()72 static void lock() SK_NO_THREAD_SAFETY_ANALYSIS {
73 if (FcGetVersion() < FontConfigThreadSafeVersion) {
74 f_c_mutex().acquire();
75 }
76 }
unlock()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
map_ranges(SkScalar val,MapRanges const ranges[],int rangesCount)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
skfontstyle_from_fcpattern(FcPattern * pattern)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
fcpattern_from_skfontstyle(SkFontStyle style,FcPattern * pattern)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:
SkTypeface_stream(std::unique_ptr<SkFontData> data,SkString familyName,const SkFontStyle & style,bool fixedWidth)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
onGetFamilyName(SkString * familyName) const408 void onGetFamilyName(SkString* familyName) const override {
409 *familyName = fFamilyName;
410 }
411
onGetFontDescriptor(SkFontDescriptor * desc,bool * serialize) const412 void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
413 SkTypeface_FreeType::FontDataPaletteToDescriptorPalette(*fData, desc);
414 *serialize = true;
415 }
416
onOpenStream(int * ttcIndex) const417 std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
418 *ttcIndex = fData->getIndex();
419 return fData->getStream()->duplicate();
420 }
421
onMakeFontData() const422 std::unique_ptr<SkFontData> onMakeFontData() const override {
423 return std::make_unique<SkFontData>(*fData);
424 }
425
onMakeClone(const SkFontArguments & args) const426 sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
427 std::unique_ptr<SkFontData> data = this->cloneFontData(args);
428 if (!data) {
429 return nullptr;
430 }
431 return sk_make_sp<SkTypeface_stream>(std::move(data),
432 fFamilyName,
433 this->fontStyle(),
434 this->isFixedPitch());
435 }
436
437 private:
438 SkString fFamilyName;
439 const std::unique_ptr<const SkFontData> fData;
440
441 using INHERITED = SkTypeface_FreeType;
442 };
443
444 class SkTypeface_fontconfig : public SkTypeface_FreeType {
445 public:
Make(SkAutoFcPattern pattern,SkString sysroot)446 static sk_sp<SkTypeface_fontconfig> Make(SkAutoFcPattern pattern, SkString sysroot) {
447 return sk_sp<SkTypeface_fontconfig>(new SkTypeface_fontconfig(std::move(pattern),
448 std::move(sysroot)));
449 }
450 mutable SkAutoFcPattern fPattern; // Mutable for passing to FontConfig API.
451 const SkString fSysroot;
452
onGetFamilyName(SkString * familyName) const453 void onGetFamilyName(SkString* familyName) const override {
454 *familyName = get_string(fPattern, FC_FAMILY);
455 }
456
onGetFontDescriptor(SkFontDescriptor * desc,bool * serialize) const457 void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override {
458 FCLocker lock;
459 desc->setFamilyName(get_string(fPattern, FC_FAMILY));
460 desc->setFullName(get_string(fPattern, FC_FULLNAME));
461 desc->setPostscriptName(get_string(fPattern, FC_POSTSCRIPT_NAME));
462 desc->setStyle(this->fontStyle());
463 *serialize = false;
464 }
465
onOpenStream(int * ttcIndex) const466 std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override {
467 FCLocker lock;
468 *ttcIndex = get_int(fPattern, FC_INDEX, 0);
469 const char* filename = get_string(fPattern, FC_FILE);
470 // See FontAccessible for note on searching sysroot then non-sysroot path.
471 SkString resolvedFilename;
472 if (!fSysroot.isEmpty()) {
473 resolvedFilename = fSysroot;
474 resolvedFilename += filename;
475 if (sk_exists(resolvedFilename.c_str(), kRead_SkFILE_Flag)) {
476 filename = resolvedFilename.c_str();
477 }
478 }
479 return SkStream::MakeFromFile(filename);
480 }
481
onFilterRec(SkScalerContextRec * rec) const482 void onFilterRec(SkScalerContextRec* rec) const override {
483 // FontConfig provides 10-scale-bitmap-fonts.conf which applies an inverse "pixelsize"
484 // matrix. It is not known if this .conf is active or not, so it is not clear if
485 // "pixelsize" should be applied before this matrix. Since using a matrix with a bitmap
486 // font isn't a great idea, only apply the matrix to outline fonts.
487 const FcMatrix* fcMatrix = get_matrix(fPattern, FC_MATRIX);
488 bool fcOutline = get_bool(fPattern, FC_OUTLINE, true);
489 if (fcOutline && fcMatrix) {
490 // fPost2x2 is column-major, left handed (y down).
491 // FcMatrix is column-major, right handed (y up).
492 SkMatrix fm;
493 fm.setAll(fcMatrix->xx,-fcMatrix->xy, 0,
494 -fcMatrix->yx, fcMatrix->yy, 0,
495 0 , 0 , 1);
496
497 SkMatrix sm;
498 rec->getMatrixFrom2x2(&sm);
499
500 sm.preConcat(fm);
501 rec->fPost2x2[0][0] = sm.getScaleX();
502 rec->fPost2x2[0][1] = sm.getSkewX();
503 rec->fPost2x2[1][0] = sm.getSkewY();
504 rec->fPost2x2[1][1] = sm.getScaleY();
505 }
506 if (get_bool(fPattern, FC_EMBOLDEN)) {
507 rec->fFlags |= SkScalerContext::kEmbolden_Flag;
508 }
509 this->INHERITED::onFilterRec(rec);
510 }
511
onGetAdvancedMetrics() const512 std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override {
513 std::unique_ptr<SkAdvancedTypefaceMetrics> info =
514 this->INHERITED::onGetAdvancedMetrics();
515
516 // Simulated fonts shouldn't be considered to be of the type of their data.
517 if (get_matrix(fPattern, FC_MATRIX) || get_bool(fPattern, FC_EMBOLDEN)) {
518 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
519 }
520 return info;
521 }
522
onMakeClone(const SkFontArguments & args) const523 sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override {
524 std::unique_ptr<SkFontData> data = this->cloneFontData(args);
525 if (!data) {
526 return nullptr;
527 }
528
529 SkString familyName;
530 this->getFamilyName(&familyName);
531
532 return sk_make_sp<SkTypeface_stream>(std::move(data),
533 familyName,
534 this->fontStyle(),
535 this->isFixedPitch());
536 }
537
onMakeFontData() const538 std::unique_ptr<SkFontData> onMakeFontData() const override {
539 int index;
540 std::unique_ptr<SkStreamAsset> stream(this->onOpenStream(&index));
541 if (!stream) {
542 return nullptr;
543 }
544 // TODO: FC_VARIABLE and FC_FONT_VARIATIONS
545 return std::make_unique<SkFontData>(std::move(stream), index, 0, nullptr, 0, nullptr, 0);
546 }
547
~SkTypeface_fontconfig()548 ~SkTypeface_fontconfig() override {
549 // Hold the lock while unrefing the pattern.
550 FCLocker lock;
551 fPattern.reset();
552 }
553
554 private:
SkTypeface_fontconfig(SkAutoFcPattern pattern,SkString sysroot)555 SkTypeface_fontconfig(SkAutoFcPattern pattern, SkString sysroot)
556 : INHERITED(skfontstyle_from_fcpattern(pattern),
557 FC_PROPORTIONAL != get_int(pattern, FC_SPACING, FC_PROPORTIONAL))
558 , fPattern(std::move(pattern))
559 , fSysroot(std::move(sysroot))
560 { }
561
562 using INHERITED = SkTypeface_FreeType;
563 };
564
565 class SkFontMgr_fontconfig : public SkFontMgr {
566 mutable SkAutoFcConfig fFC; // Only mutable to avoid const cast when passed to FontConfig API.
567 const SkString fSysroot;
568 const sk_sp<SkDataTable> fFamilyNames;
569 const SkTypeface_FreeType::Scanner fScanner;
570
571 class StyleSet : public SkFontStyleSet {
572 public:
StyleSet(sk_sp<SkFontMgr_fontconfig> parent,SkAutoFcFontSet fontSet)573 StyleSet(sk_sp<SkFontMgr_fontconfig> parent, SkAutoFcFontSet fontSet)
574 : fFontMgr(std::move(parent)), fFontSet(std::move(fontSet))
575 { }
576
~StyleSet()577 ~StyleSet() override {
578 // Hold the lock while unrefing the font set.
579 FCLocker lock;
580 fFontSet.reset();
581 }
582
count()583 int count() override { return fFontSet->nfont; }
584
getStyle(int index,SkFontStyle * style,SkString * styleName)585 void getStyle(int index, SkFontStyle* style, SkString* styleName) override {
586 if (index < 0 || fFontSet->nfont <= index) {
587 return;
588 }
589
590 FCLocker lock;
591 if (style) {
592 *style = skfontstyle_from_fcpattern(fFontSet->fonts[index]);
593 }
594 if (styleName) {
595 *styleName = get_string(fFontSet->fonts[index], FC_STYLE);
596 }
597 }
598
createTypeface(int index)599 SkTypeface* createTypeface(int index) override {
600 if (index < 0 || fFontSet->nfont <= index) {
601 return nullptr;
602 }
603 SkAutoFcPattern match([this, &index]() {
604 FCLocker lock;
605 FcPatternReference(fFontSet->fonts[index]);
606 return fFontSet->fonts[index];
607 }());
608 return fFontMgr->createTypefaceFromFcPattern(std::move(match)).release();
609 }
610
matchStyle(const SkFontStyle & style)611 SkTypeface* matchStyle(const SkFontStyle& style) override {
612 SkAutoFcPattern match([this, &style]() {
613 FCLocker lock;
614
615 SkAutoFcPattern pattern;
616 fcpattern_from_skfontstyle(style, pattern);
617 FcConfigSubstitute(fFontMgr->fFC, pattern, FcMatchPattern);
618 FcDefaultSubstitute(pattern);
619
620 FcResult result;
621 FcFontSet* fontSets[1] = { fFontSet };
622 return FcFontSetMatch(fFontMgr->fFC,
623 fontSets, SK_ARRAY_COUNT(fontSets),
624 pattern, &result);
625
626 }());
627 return fFontMgr->createTypefaceFromFcPattern(std::move(match)).release();
628 }
629
630 private:
631 sk_sp<SkFontMgr_fontconfig> fFontMgr;
632 SkAutoFcFontSet fFontSet;
633 };
634
FindName(const SkTDArray<const char * > & list,const char * str)635 static bool FindName(const SkTDArray<const char*>& list, const char* str) {
636 int count = list.count();
637 for (int i = 0; i < count; ++i) {
638 if (!strcmp(list[i], str)) {
639 return true;
640 }
641 }
642 return false;
643 }
644
GetFamilyNames(FcConfig * fcconfig)645 static sk_sp<SkDataTable> GetFamilyNames(FcConfig* fcconfig) {
646 FCLocker lock;
647
648 SkTDArray<const char*> names;
649 SkTDArray<size_t> sizes;
650
651 static const FcSetName fcNameSet[] = { FcSetSystem, FcSetApplication };
652 for (int setIndex = 0; setIndex < (int)SK_ARRAY_COUNT(fcNameSet); ++setIndex) {
653 // Return value of FcConfigGetFonts must not be destroyed.
654 FcFontSet* allFonts(FcConfigGetFonts(fcconfig, fcNameSet[setIndex]));
655 if (nullptr == allFonts) {
656 continue;
657 }
658
659 for (int fontIndex = 0; fontIndex < allFonts->nfont; ++fontIndex) {
660 FcPattern* current = allFonts->fonts[fontIndex];
661 for (int id = 0; ; ++id) {
662 FcChar8* fcFamilyName;
663 FcResult result = FcPatternGetString(current, FC_FAMILY, id, &fcFamilyName);
664 if (FcResultNoId == result) {
665 break;
666 }
667 if (FcResultMatch != result) {
668 continue;
669 }
670 const char* familyName = reinterpret_cast<const char*>(fcFamilyName);
671 if (familyName && !FindName(names, familyName)) {
672 *names.append() = familyName;
673 *sizes.append() = strlen(familyName) + 1;
674 }
675 }
676 }
677 }
678
679 return SkDataTable::MakeCopyArrays((void const *const *)names.begin(),
680 sizes.begin(), names.count());
681 }
682
FindByFcPattern(SkTypeface * cached,void * ctx)683 static bool FindByFcPattern(SkTypeface* cached, void* ctx) {
684 SkTypeface_fontconfig* cshFace = static_cast<SkTypeface_fontconfig*>(cached);
685 FcPattern* ctxPattern = static_cast<FcPattern*>(ctx);
686 return FcTrue == FcPatternEqual(cshFace->fPattern, ctxPattern);
687 }
688
689 mutable SkMutex fTFCacheMutex;
690 mutable SkTypefaceCache fTFCache;
691 /** Creates a typeface using a typeface cache.
692 * @param pattern a complete pattern from FcFontRenderPrepare.
693 */
createTypefaceFromFcPattern(SkAutoFcPattern pattern) const694 sk_sp<SkTypeface> createTypefaceFromFcPattern(SkAutoFcPattern pattern) const {
695 if (!pattern) {
696 return nullptr;
697 }
698 // Cannot hold FCLocker when calling fTFCache.add; an evicted typeface may need to lock.
699 // Must hold fTFCacheMutex when interacting with fTFCache.
700 SkAutoMutexExclusive ama(fTFCacheMutex);
701 sk_sp<SkTypeface> face = [&]() {
702 FCLocker lock;
703 sk_sp<SkTypeface> face = fTFCache.findByProcAndRef(FindByFcPattern, pattern);
704 if (face) {
705 pattern.reset();
706 }
707 return face;
708 }();
709 if (!face) {
710 face = SkTypeface_fontconfig::Make(std::move(pattern), fSysroot);
711 if (face) {
712 // Cannot hold FCLocker in fTFCache.add; evicted typefaces may need to lock.
713 fTFCache.add(face);
714 }
715 }
716 return face;
717 }
718
719 public:
720 /** Takes control of the reference to 'config'. */
SkFontMgr_fontconfig(FcConfig * config)721 explicit SkFontMgr_fontconfig(FcConfig* config)
722 : fFC(config ? config : FcInitLoadConfigAndFonts())
723 , fSysroot(reinterpret_cast<const char*>(FcConfigGetSysRoot(fFC)))
724 , fFamilyNames(GetFamilyNames(fFC)) { }
725
~SkFontMgr_fontconfig()726 ~SkFontMgr_fontconfig() override {
727 // Hold the lock while unrefing the config.
728 FCLocker lock;
729 fFC.reset();
730 }
731
732 protected:
onCountFamilies() const733 int onCountFamilies() const override {
734 return fFamilyNames->count();
735 }
736
onGetFamilyName(int index,SkString * familyName) const737 void onGetFamilyName(int index, SkString* familyName) const override {
738 familyName->set(fFamilyNames->atStr(index));
739 }
740
onCreateStyleSet(int index) const741 SkFontStyleSet* onCreateStyleSet(int index) const override {
742 return this->onMatchFamily(fFamilyNames->atStr(index));
743 }
744
745 /** True if any string object value in the font is the same
746 * as a string object value in the pattern.
747 */
AnyMatching(FcPattern * font,FcPattern * pattern,const char * object)748 static bool AnyMatching(FcPattern* font, FcPattern* pattern, const char* object) {
749 FcChar8* fontString;
750 FcChar8* patternString;
751 FcResult result;
752 // Set an arbitrary limit on the number of pattern object values to consider.
753 // TODO: re-write this to avoid N*M
754 static const int maxId = 16;
755 for (int patternId = 0; patternId < maxId; ++patternId) {
756 result = FcPatternGetString(pattern, object, patternId, &patternString);
757 if (FcResultNoId == result) {
758 break;
759 }
760 if (FcResultMatch != result) {
761 continue;
762 }
763 for (int fontId = 0; fontId < maxId; ++fontId) {
764 result = FcPatternGetString(font, object, fontId, &fontString);
765 if (FcResultNoId == result) {
766 break;
767 }
768 if (FcResultMatch != result) {
769 continue;
770 }
771 if (0 == FcStrCmpIgnoreCase(patternString, fontString)) {
772 return true;
773 }
774 }
775 }
776 return false;
777 }
778
FontAccessible(FcPattern * font) const779 bool FontAccessible(FcPattern* font) const {
780 // FontConfig can return fonts which are unreadable.
781 const char* filename = get_string(font, FC_FILE, nullptr);
782 if (nullptr == filename) {
783 return false;
784 }
785
786 // When sysroot was implemented in e96d7760886a3781a46b3271c76af99e15cb0146 (before 2.11.0)
787 // it was broken; mostly fixed in d17f556153fbaf8fe57fdb4fc1f0efa4313f0ecf (after 2.11.1).
788 // This leaves Debian 8 and 9 with broken support for this feature.
789 // As a result, this feature should not be used until at least 2.11.91.
790 // The broken support is mostly around not making all paths relative to the sysroot.
791 // However, even at 2.13.1 it is possible to get a mix of sysroot and non-sysroot paths,
792 // as any added file path not lexically starting with the sysroot will be unchanged.
793 // To allow users to add local app files outside the sysroot,
794 // prefer the sysroot but also look without the sysroot.
795 if (!fSysroot.isEmpty()) {
796 SkString resolvedFilename;
797 resolvedFilename = fSysroot;
798 resolvedFilename += filename;
799 if (sk_exists(resolvedFilename.c_str(), kRead_SkFILE_Flag)) {
800 return true;
801 }
802 }
803 return sk_exists(filename, kRead_SkFILE_Flag);
804 }
805
FontFamilyNameMatches(FcPattern * font,FcPattern * pattern)806 static bool FontFamilyNameMatches(FcPattern* font, FcPattern* pattern) {
807 return AnyMatching(font, pattern, FC_FAMILY);
808 }
809
FontContainsCharacter(FcPattern * font,uint32_t character)810 static bool FontContainsCharacter(FcPattern* font, uint32_t character) {
811 FcResult result;
812 FcCharSet* matchCharSet;
813 for (int charSetId = 0; ; ++charSetId) {
814 result = FcPatternGetCharSet(font, FC_CHARSET, charSetId, &matchCharSet);
815 if (FcResultNoId == result) {
816 break;
817 }
818 if (FcResultMatch != result) {
819 continue;
820 }
821 if (FcCharSetHasChar(matchCharSet, character)) {
822 return true;
823 }
824 }
825 return false;
826 }
827
onMatchFamily(const char familyName[]) const828 SkFontStyleSet* onMatchFamily(const char familyName[]) const override {
829 if (!familyName) {
830 return nullptr;
831 }
832 FCLocker lock;
833
834 SkAutoFcPattern pattern;
835 FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
836 FcConfigSubstitute(fFC, pattern, FcMatchPattern);
837 FcDefaultSubstitute(pattern);
838
839 FcPattern* matchPattern;
840 SkAutoFcPattern strongPattern(nullptr);
841 if (familyName) {
842 strongPattern.reset(FcPatternDuplicate(pattern));
843 remove_weak(strongPattern, FC_FAMILY);
844 matchPattern = strongPattern;
845 } else {
846 matchPattern = pattern;
847 }
848
849 SkAutoFcFontSet matches;
850 // TODO: Some families have 'duplicates' due to symbolic links.
851 // The patterns are exactly the same except for the FC_FILE.
852 // It should be possible to collapse these patterns by normalizing.
853 static const FcSetName fcNameSet[] = { FcSetSystem, FcSetApplication };
854 for (int setIndex = 0; setIndex < (int)SK_ARRAY_COUNT(fcNameSet); ++setIndex) {
855 // Return value of FcConfigGetFonts must not be destroyed.
856 FcFontSet* allFonts(FcConfigGetFonts(fFC, fcNameSet[setIndex]));
857 if (nullptr == allFonts) {
858 continue;
859 }
860
861 for (int fontIndex = 0; fontIndex < allFonts->nfont; ++fontIndex) {
862 FcPattern* font = allFonts->fonts[fontIndex];
863 if (FontAccessible(font) && FontFamilyNameMatches(font, matchPattern)) {
864 FcFontSetAdd(matches, FcFontRenderPrepare(fFC, pattern, font));
865 }
866 }
867 }
868
869 return new StyleSet(sk_ref_sp(this), std::move(matches));
870 }
871
onMatchFamilyStyle(const char familyName[],const SkFontStyle & style) const872 SkTypeface* onMatchFamilyStyle(const char familyName[],
873 const SkFontStyle& style) const override
874 {
875 SkAutoFcPattern font([this, &familyName, &style]() {
876 FCLocker lock;
877
878 SkAutoFcPattern pattern;
879 FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
880 fcpattern_from_skfontstyle(style, pattern);
881 FcConfigSubstitute(fFC, pattern, FcMatchPattern);
882 FcDefaultSubstitute(pattern);
883
884 // We really want to match strong (preferred) and same (acceptable) only here.
885 // If a family name was specified, assume that any weak matches after the last strong
886 // match are weak (default) and ignore them.
887 // After substitution the pattern for 'sans-serif' looks like "wwwwwwwwwwwwwwswww" where
888 // there are many weak but preferred names, followed by defaults.
889 // So it is possible to have weakly matching but preferred names.
890 // In aliases, bindings are weak by default, so this is easy and common.
891 // If no family name was specified, we'll probably only get weak matches, but that's ok.
892 FcPattern* matchPattern;
893 SkAutoFcPattern strongPattern(nullptr);
894 if (familyName) {
895 strongPattern.reset(FcPatternDuplicate(pattern));
896 remove_weak(strongPattern, FC_FAMILY);
897 matchPattern = strongPattern;
898 } else {
899 matchPattern = pattern;
900 }
901
902 FcResult result;
903 SkAutoFcPattern font(FcFontMatch(fFC, pattern, &result));
904 if (!font || !FontAccessible(font) || !FontFamilyNameMatches(font, matchPattern)) {
905 font.reset();
906 }
907 return font;
908 }());
909 return createTypefaceFromFcPattern(std::move(font)).release();
910 }
911
onMatchFamilyStyleCharacter(const char familyName[],const SkFontStyle & style,const char * bcp47[],int bcp47Count,SkUnichar character) const912 SkTypeface* onMatchFamilyStyleCharacter(const char familyName[],
913 const SkFontStyle& style,
914 const char* bcp47[],
915 int bcp47Count,
916 SkUnichar character) const override
917 {
918 SkAutoFcPattern font([&](){
919 FCLocker lock;
920
921 SkAutoFcPattern pattern;
922 if (familyName) {
923 FcValue familyNameValue;
924 familyNameValue.type = FcTypeString;
925 familyNameValue.u.s = reinterpret_cast<const FcChar8*>(familyName);
926 FcPatternAddWeak(pattern, FC_FAMILY, familyNameValue, FcFalse);
927 }
928 fcpattern_from_skfontstyle(style, pattern);
929
930 SkAutoFcCharSet charSet;
931 FcCharSetAddChar(charSet, character);
932 FcPatternAddCharSet(pattern, FC_CHARSET, charSet);
933
934 if (bcp47Count > 0) {
935 SkASSERT(bcp47);
936 SkAutoFcLangSet langSet;
937 for (int i = bcp47Count; i --> 0;) {
938 FcLangSetAdd(langSet, (const FcChar8*)bcp47[i]);
939 }
940 FcPatternAddLangSet(pattern, FC_LANG, langSet);
941 }
942
943 FcConfigSubstitute(fFC, pattern, FcMatchPattern);
944 FcDefaultSubstitute(pattern);
945
946 FcResult result;
947 SkAutoFcPattern font(FcFontMatch(fFC, pattern, &result));
948 if (!font || !FontAccessible(font) || !FontContainsCharacter(font, character)) {
949 font.reset();
950 }
951 return font;
952 }());
953 return createTypefaceFromFcPattern(std::move(font)).release();
954 }
955
onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,int ttcIndex) const956 sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
957 int ttcIndex) const override {
958 const size_t length = stream->getLength();
959 if (length <= 0 || (1u << 30) < length) {
960 return nullptr;
961 }
962
963 SkString name;
964 SkFontStyle style;
965 bool isFixedWidth = false;
966 if (!fScanner.scanFont(stream.get(), ttcIndex, &name, &style, &isFixedWidth, nullptr)) {
967 return nullptr;
968 }
969
970 auto data = std::make_unique<SkFontData>(std::move(stream), ttcIndex, 0,
971 nullptr, 0, nullptr, 0);
972 return sk_sp<SkTypeface>(new SkTypeface_stream(std::move(data), std::move(name),
973 style, isFixedWidth));
974 }
975
onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,const SkFontArguments & args) const976 sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream,
977 const SkFontArguments& args) const override {
978 using Scanner = SkTypeface_FreeType::Scanner;
979 bool isFixedPitch;
980 SkFontStyle style;
981 SkString name;
982 Scanner::AxisDefinitions axisDefinitions;
983 if (!fScanner.scanFont(stream.get(), args.getCollectionIndex(),
984 &name, &style, &isFixedPitch, &axisDefinitions))
985 {
986 return nullptr;
987 }
988
989 SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
990 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
991 axisValues, name);
992
993 auto data = std::make_unique<SkFontData>(
994 std::move(stream), args.getCollectionIndex(), args.getPalette().index,
995 axisValues.get(), axisDefinitions.count(),
996 args.getPalette().overrides, args.getPalette().overrideCount);
997 return sk_sp<SkTypeface>(new SkTypeface_stream(std::move(data), std::move(name),
998 style, isFixedPitch));
999 }
1000
onMakeFromData(sk_sp<SkData> data,int ttcIndex) const1001 sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override {
1002 return this->makeFromStream(std::make_unique<SkMemoryStream>(std::move(data)), ttcIndex);
1003 }
1004
onMakeFromFile(const char path[],int ttcIndex) const1005 sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override {
1006 return this->makeFromStream(SkStream::MakeFromFile(path), ttcIndex);
1007 }
1008
onLegacyMakeTypeface(const char familyName[],SkFontStyle style) const1009 sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[], SkFontStyle style) const override {
1010 sk_sp<SkTypeface> typeface(this->matchFamilyStyle(familyName, style));
1011 if (typeface) {
1012 return typeface;
1013 }
1014
1015 return sk_sp<SkTypeface>(this->matchFamilyStyle(nullptr, style));
1016 }
1017 };
1018
SkFontMgr_New_FontConfig(FcConfig * fc)1019 SK_API sk_sp<SkFontMgr> SkFontMgr_New_FontConfig(FcConfig* fc) {
1020 return sk_make_sp<SkFontMgr_fontconfig>(fc);
1021 }
1022