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