SkFontMgr_fontconfig.cpp 40 KB

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