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