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