SkFontHost_FreeType.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. /*
  2. * Copyright 2006 The Android Open Source Project
  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/SkBitmap.h"
  8. #include "include/core/SkCanvas.h"
  9. #include "include/core/SkData.h"
  10. #include "include/core/SkFontMetrics.h"
  11. #include "include/core/SkPath.h"
  12. #include "include/core/SkStream.h"
  13. #include "include/core/SkString.h"
  14. #include "include/private/SkColorData.h"
  15. #include "include/private/SkMalloc.h"
  16. #include "include/private/SkMutex.h"
  17. #include "include/private/SkTemplates.h"
  18. #include "include/private/SkTo.h"
  19. #include "src/core/SkAdvancedTypefaceMetrics.h"
  20. #include "src/core/SkDescriptor.h"
  21. #include "src/core/SkFDot6.h"
  22. #include "src/core/SkFontDescriptor.h"
  23. #include "src/core/SkGlyph.h"
  24. #include "src/core/SkMakeUnique.h"
  25. #include "src/core/SkMask.h"
  26. #include "src/core/SkMaskGamma.h"
  27. #include "src/core/SkScalerContext.h"
  28. #include "src/ports/SkFontHost_FreeType_common.h"
  29. #include "src/sfnt/SkOTUtils.h"
  30. #include "src/utils/SkCallableTraits.h"
  31. #include "src/utils/SkMatrix22.h"
  32. #include <memory>
  33. #include <ft2build.h>
  34. #include FT_ADVANCES_H
  35. #include FT_BITMAP_H
  36. #ifdef FT_COLOR_H
  37. # include FT_COLOR_H
  38. #endif
  39. #include FT_FREETYPE_H
  40. #include FT_LCD_FILTER_H
  41. #include FT_MODULE_H
  42. #include FT_MULTIPLE_MASTERS_H
  43. #include FT_OUTLINE_H
  44. #include FT_SIZES_H
  45. #include FT_SYSTEM_H
  46. #include FT_TRUETYPE_TABLES_H
  47. #include FT_TYPE1_TABLES_H
  48. #include FT_XFREE86_H
  49. // SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
  50. // Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
  51. #define SK_FREETYPE_DLOPEN (0x1)
  52. #ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
  53. # if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (SK_BUILD_FOR_GOOGLE3)
  54. # define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
  55. # else
  56. # define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
  57. # endif
  58. #endif
  59. #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
  60. # include <dlfcn.h>
  61. #endif
  62. // FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
  63. // were introduced in FreeType 2.5.0.
  64. // The following may be removed once FreeType 2.5.0 is required to build.
  65. #ifndef FT_LOAD_COLOR
  66. # define FT_LOAD_COLOR ( 1L << 20 )
  67. # define FT_PIXEL_MODE_BGRA 7
  68. #endif
  69. // FT_LOAD_BITMAP_METRICS_ONLY was introduced in FreeType 2.7.1
  70. // The following may be removed once FreeType 2.7.1 is required to build.
  71. #ifndef FT_LOAD_BITMAP_METRICS_ONLY
  72. # define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
  73. #endif
  74. // FT_VAR_AXIS_FLAG_HIDDEN was introduced in FreeType 2.8.1
  75. // The variation axis should not be exposed to user interfaces.
  76. #ifndef FT_VAR_AXIS_FLAG_HIDDEN
  77. # define FT_VAR_AXIS_FLAG_HIDDEN 1
  78. #endif
  79. //#define ENABLE_GLYPH_SPEW // for tracing calls
  80. //#define DUMP_STRIKE_CREATION
  81. //#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
  82. //#define SK_GAMMA_APPLY_TO_A8
  83. #if 1
  84. #define LOG_INFO(...)
  85. #else
  86. #define LOG_INFO SkDEBUGF
  87. #endif
  88. static bool isLCD(const SkScalerContextRec& rec) {
  89. return SkMask::kLCD16_Format == rec.fMaskFormat;
  90. }
  91. static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
  92. return SkFixedToScalar(x);
  93. }
  94. //////////////////////////////////////////////////////////////////////////
  95. using FT_Alloc_size_t = SkCallableTraits<FT_Alloc_Func>::argument<1>::type;
  96. static_assert(std::is_same<FT_Alloc_size_t, long >::value ||
  97. std::is_same<FT_Alloc_size_t, size_t>::value,"");
  98. extern "C" {
  99. static void* sk_ft_alloc(FT_Memory, FT_Alloc_size_t size) {
  100. return sk_malloc_throw(size);
  101. }
  102. static void sk_ft_free(FT_Memory, void* block) {
  103. sk_free(block);
  104. }
  105. static void* sk_ft_realloc(FT_Memory, FT_Alloc_size_t cur_size,
  106. FT_Alloc_size_t new_size, void* block) {
  107. return sk_realloc_throw(block, new_size);
  108. }
  109. };
  110. FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
  111. class FreeTypeLibrary : SkNoncopyable {
  112. public:
  113. FreeTypeLibrary()
  114. : fGetVarDesignCoordinates(nullptr)
  115. , fGetVarAxisFlags(nullptr)
  116. , fLibrary(nullptr)
  117. , fIsLCDSupported(false)
  118. , fLightHintingIsYOnly(false)
  119. , fLCDExtra(0)
  120. {
  121. if (FT_New_Library(&gFTMemory, &fLibrary)) {
  122. return;
  123. }
  124. FT_Add_Default_Modules(fLibrary);
  125. // When using dlsym
  126. // *(void**)(&procPtr) = dlsym(self, "proc");
  127. // is non-standard, but safe for POSIX. Cannot write
  128. // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
  129. // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
  130. FT_Int major, minor, patch;
  131. FT_Library_Version(fLibrary, &major, &minor, &patch);
  132. #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
  133. fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
  134. #elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
  135. if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
  136. //The FreeType library is already loaded, so symbols are available in process.
  137. void* self = dlopen(nullptr, RTLD_LAZY);
  138. if (self) {
  139. *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
  140. dlclose(self);
  141. }
  142. }
  143. #endif
  144. #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
  145. FT_Set_Default_Properties(fLibrary);
  146. #elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
  147. if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
  148. //The FreeType library is already loaded, so symbols are available in process.
  149. void* self = dlopen(nullptr, RTLD_LAZY);
  150. if (self) {
  151. FT_Set_Default_PropertiesProc setDefaultProperties;
  152. *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
  153. dlclose(self);
  154. if (setDefaultProperties) {
  155. setDefaultProperties(fLibrary);
  156. }
  157. }
  158. }
  159. #endif
  160. // The 'light' hinting is vertical only starting in 2.8.0.
  161. #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080000
  162. fLightHintingIsYOnly = true;
  163. #else
  164. if (major > 2 || ((major == 2 && minor > 8) || (major == 2 && minor == 8 && patch >= 0))) {
  165. fLightHintingIsYOnly = true;
  166. }
  167. #endif
  168. #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080100
  169. fGetVarAxisFlags = FT_Get_Var_Axis_Flags;
  170. #elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
  171. if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
  172. //The FreeType library is already loaded, so symbols are available in process.
  173. void* self = dlopen(nullptr, RTLD_LAZY);
  174. if (self) {
  175. *(void**)(&fGetVarAxisFlags) = dlsym(self, "FT_Get_Var_Axis_Flags");
  176. dlclose(self);
  177. }
  178. }
  179. #endif
  180. // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
  181. // The default has changed over time, so this doesn't mean the same thing to all users.
  182. if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
  183. fIsLCDSupported = true;
  184. fLCDExtra = 2; //Using a filter adds one full pixel to each side.
  185. }
  186. }
  187. ~FreeTypeLibrary() {
  188. if (fLibrary) {
  189. FT_Done_Library(fLibrary);
  190. }
  191. }
  192. FT_Library library() { return fLibrary; }
  193. bool isLCDSupported() { return fIsLCDSupported; }
  194. int lcdExtra() { return fLCDExtra; }
  195. bool lightHintingIsYOnly() { return fLightHintingIsYOnly; }
  196. // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
  197. // Prior to this there was no way to get the coordinates out of the FT_Face.
  198. // This wasn't too bad because you needed to specify them anyway, and the clamp was provided.
  199. // However, this doesn't work when face_index specifies named variations as introduced in 2.6.1.
  200. using FT_Get_Var_Blend_CoordinatesProc = FT_Error (*)(FT_Face, FT_UInt, FT_Fixed*);
  201. FT_Get_Var_Blend_CoordinatesProc fGetVarDesignCoordinates;
  202. // FT_Get_Var_Axis_Flags was introduced in FreeType 2.8.1
  203. // Get the ‘flags’ field of an OpenType Variation Axis Record.
  204. // Not meaningful for Adobe MM fonts (‘*flags’ is always zero).
  205. using FT_Get_Var_Axis_FlagsProc = FT_Error (*)(FT_MM_Var*, FT_UInt, FT_UInt*);
  206. FT_Get_Var_Axis_FlagsProc fGetVarAxisFlags;
  207. private:
  208. FT_Library fLibrary;
  209. bool fIsLCDSupported;
  210. bool fLightHintingIsYOnly;
  211. int fLCDExtra;
  212. // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
  213. // The following platforms provide FreeType of at least 2.4.0.
  214. // Ubuntu >= 11.04 (previous deprecated April 2013)
  215. // Debian >= 6.0 (good)
  216. // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
  217. // Fedora >= 14 (good)
  218. // Android >= Gingerbread (good)
  219. // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
  220. using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
  221. // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
  222. // of FT_New_Library to request these global properties to be read was added.
  223. using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
  224. };
  225. struct SkFaceRec;
  226. static SkMutex& f_t_mutex() {
  227. static SkMutex& mutex = *(new SkMutex);
  228. return mutex;
  229. }
  230. static FreeTypeLibrary* gFTLibrary;
  231. static SkFaceRec* gFaceRecHead;
  232. // Private to ref_ft_library and unref_ft_library
  233. static int gFTCount;
  234. // Caller must lock f_t_mutex() before calling this function.
  235. static bool ref_ft_library() {
  236. f_t_mutex().assertHeld();
  237. SkASSERT(gFTCount >= 0);
  238. if (0 == gFTCount) {
  239. SkASSERT(nullptr == gFTLibrary);
  240. gFTLibrary = new FreeTypeLibrary;
  241. }
  242. ++gFTCount;
  243. return gFTLibrary->library();
  244. }
  245. // Caller must lock f_t_mutex() before calling this function.
  246. static void unref_ft_library() {
  247. f_t_mutex().assertHeld();
  248. SkASSERT(gFTCount > 0);
  249. --gFTCount;
  250. if (0 == gFTCount) {
  251. SkASSERT(nullptr == gFaceRecHead);
  252. SkASSERT(nullptr != gFTLibrary);
  253. delete gFTLibrary;
  254. SkDEBUGCODE(gFTLibrary = nullptr;)
  255. }
  256. }
  257. ///////////////////////////////////////////////////////////////////////////
  258. struct SkFaceRec {
  259. SkFaceRec* fNext;
  260. std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
  261. FT_StreamRec fFTStream;
  262. std::unique_ptr<SkStreamAsset> fSkStream;
  263. uint32_t fRefCnt;
  264. uint32_t fFontID;
  265. // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
  266. // Cache the variation design metrics used to create the font if the user specifies them.
  267. SkAutoSTMalloc<4, SkFixed> fAxes;
  268. int fAxesCount;
  269. // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
  270. // and named variation index on input, but masks the named variation index part on output.
  271. // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
  272. bool fNamedVariationSpecified;
  273. SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
  274. };
  275. extern "C" {
  276. static unsigned long sk_ft_stream_io(FT_Stream ftStream,
  277. unsigned long offset,
  278. unsigned char* buffer,
  279. unsigned long count)
  280. {
  281. SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
  282. if (count) {
  283. if (!stream->seek(offset)) {
  284. return 0;
  285. }
  286. count = stream->read(buffer, count);
  287. }
  288. return count;
  289. }
  290. static void sk_ft_stream_close(FT_Stream) {}
  291. }
  292. SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
  293. : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
  294. , fAxesCount(0), fNamedVariationSpecified(false)
  295. {
  296. sk_bzero(&fFTStream, sizeof(fFTStream));
  297. fFTStream.size = fSkStream->getLength();
  298. fFTStream.descriptor.pointer = fSkStream.get();
  299. fFTStream.read = sk_ft_stream_io;
  300. fFTStream.close = sk_ft_stream_close;
  301. }
  302. static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
  303. if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
  304. return;
  305. }
  306. // If a named variation is requested, don't overwrite the named variation's position.
  307. if (data.getIndex() > 0xFFFF) {
  308. rec->fNamedVariationSpecified = true;
  309. return;
  310. }
  311. SkDEBUGCODE(
  312. FT_MM_Var* variations = nullptr;
  313. if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
  314. LOG_INFO("INFO: font %s claims variations, but none found.\n",
  315. rec->fFace->family_name);
  316. return;
  317. }
  318. SkAutoFree autoFreeVariations(variations);
  319. if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
  320. LOG_INFO("INFO: font %s has %d variations, but %d were specified.\n",
  321. rec->fFace->family_name, variations->num_axis, data.getAxisCount());
  322. return;
  323. }
  324. )
  325. SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
  326. for (int i = 0; i < data.getAxisCount(); ++i) {
  327. coords[i] = data.getAxis()[i];
  328. }
  329. if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
  330. LOG_INFO("INFO: font %s has variations, but specified variations could not be set.\n",
  331. rec->fFace->family_name);
  332. return;
  333. }
  334. rec->fAxesCount = data.getAxisCount();
  335. rec->fAxes.reset(rec->fAxesCount);
  336. for (int i = 0; i < rec->fAxesCount; ++i) {
  337. rec->fAxes[i] = data.getAxis()[i];
  338. }
  339. }
  340. // Will return nullptr on failure
  341. // Caller must lock f_t_mutex() before calling this function.
  342. static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
  343. f_t_mutex().assertHeld();
  344. const SkFontID fontID = typeface->uniqueID();
  345. SkFaceRec* cachedRec = gFaceRecHead;
  346. while (cachedRec) {
  347. if (cachedRec->fFontID == fontID) {
  348. SkASSERT(cachedRec->fFace);
  349. cachedRec->fRefCnt += 1;
  350. return cachedRec;
  351. }
  352. cachedRec = cachedRec->fNext;
  353. }
  354. std::unique_ptr<SkFontData> data = typeface->makeFontData();
  355. if (nullptr == data || !data->hasStream()) {
  356. return nullptr;
  357. }
  358. std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
  359. FT_Open_Args args;
  360. memset(&args, 0, sizeof(args));
  361. const void* memoryBase = rec->fSkStream->getMemoryBase();
  362. if (memoryBase) {
  363. args.flags = FT_OPEN_MEMORY;
  364. args.memory_base = (const FT_Byte*)memoryBase;
  365. args.memory_size = rec->fSkStream->getLength();
  366. } else {
  367. args.flags = FT_OPEN_STREAM;
  368. args.stream = &rec->fFTStream;
  369. }
  370. {
  371. FT_Face rawFace;
  372. FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
  373. if (err) {
  374. SK_TRACEFTR(err, "unable to open font '%x'", fontID);
  375. return nullptr;
  376. }
  377. rec->fFace.reset(rawFace);
  378. }
  379. SkASSERT(rec->fFace);
  380. ft_face_setup_axes(rec.get(), *data);
  381. // FreeType will set the charmap to the "most unicode" cmap if it exists.
  382. // If there are no unicode cmaps, the charmap is set to nullptr.
  383. // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
  384. // because they are effectively private use area only (even if they aren't).
  385. // This is the last on the fallback list at
  386. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
  387. if (!rec->fFace->charmap) {
  388. FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
  389. }
  390. rec->fNext = gFaceRecHead;
  391. gFaceRecHead = rec.get();
  392. return rec.release();
  393. }
  394. // Caller must lock f_t_mutex() before calling this function.
  395. // Marked extern because vc++ does not support internal linkage template parameters.
  396. extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
  397. f_t_mutex().assertHeld();
  398. SkFaceRec* rec = gFaceRecHead;
  399. SkFaceRec* prev = nullptr;
  400. while (rec) {
  401. SkFaceRec* next = rec->fNext;
  402. if (rec->fFace == faceRec->fFace) {
  403. if (--rec->fRefCnt == 0) {
  404. if (prev) {
  405. prev->fNext = next;
  406. } else {
  407. gFaceRecHead = next;
  408. }
  409. delete rec;
  410. }
  411. return;
  412. }
  413. prev = rec;
  414. rec = next;
  415. }
  416. SkDEBUGFAIL("shouldn't get here, face not in list");
  417. }
  418. class AutoFTAccess {
  419. public:
  420. AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
  421. f_t_mutex().acquire();
  422. SkASSERT_RELEASE(ref_ft_library());
  423. fFaceRec = ref_ft_face(tf);
  424. }
  425. ~AutoFTAccess() {
  426. if (fFaceRec) {
  427. unref_ft_face(fFaceRec);
  428. }
  429. unref_ft_library();
  430. f_t_mutex().release();
  431. }
  432. FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
  433. int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
  434. SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
  435. bool isNamedVariationSpecified() {
  436. return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
  437. }
  438. private:
  439. SkFaceRec* fFaceRec;
  440. };
  441. ///////////////////////////////////////////////////////////////////////////
  442. class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
  443. public:
  444. SkScalerContext_FreeType(sk_sp<SkTypeface>,
  445. const SkScalerContextEffects&,
  446. const SkDescriptor* desc);
  447. ~SkScalerContext_FreeType() override;
  448. bool success() const {
  449. return fFTSize != nullptr && fFace != nullptr;
  450. }
  451. protected:
  452. unsigned generateGlyphCount() override;
  453. bool generateAdvance(SkGlyph* glyph) override;
  454. void generateMetrics(SkGlyph* glyph) override;
  455. void generateImage(const SkGlyph& glyph) override;
  456. bool generatePath(SkGlyphID glyphID, SkPath* path) override;
  457. void generateFontMetrics(SkFontMetrics*) override;
  458. private:
  459. using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
  460. std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
  461. FT_Face fFace; // Borrowed face from gFaceRecHead.
  462. FT_Size fFTSize; // The size on the fFace for this scaler.
  463. FT_Int fStrikeIndex;
  464. /** The rest of the matrix after FreeType handles the size.
  465. * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
  466. * With bitmap only fonts this matrix must be applied to scale the bitmap.
  467. */
  468. SkMatrix fMatrix22Scalar;
  469. /** Same as fMatrix22Scalar, but in FreeType units and space. */
  470. FT_Matrix fMatrix22;
  471. /** The actual size requested. */
  472. SkVector fScale;
  473. uint32_t fLoadGlyphFlags;
  474. bool fDoLinearMetrics;
  475. bool fLCDIsVert;
  476. FT_Error setupSize();
  477. void getBBoxForCurrentGlyph(const SkGlyph* glyph, FT_BBox* bbox,
  478. bool snapToPixelBoundary = false);
  479. bool getCBoxForLetter(char letter, FT_BBox* bbox);
  480. // Caller must lock f_t_mutex() before calling this function.
  481. void updateGlyphIfLCD(SkGlyph* glyph);
  482. // Caller must lock f_t_mutex() before calling this function.
  483. // update FreeType2 glyph slot with glyph emboldened
  484. void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
  485. bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
  486. };
  487. ///////////////////////////////////////////////////////////////////////////
  488. static bool canEmbed(FT_Face face) {
  489. FT_UShort fsType = FT_Get_FSType_Flags(face);
  490. return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
  491. FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
  492. }
  493. static bool canSubset(FT_Face face) {
  494. FT_UShort fsType = FT_Get_FSType_Flags(face);
  495. return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
  496. }
  497. static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
  498. const char* fontType = FT_Get_X11_Font_Format(face);
  499. static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
  500. { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
  501. { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
  502. { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
  503. { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
  504. };
  505. for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
  506. return SkAdvancedTypefaceMetrics::kOther_Font;
  507. }
  508. std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
  509. AutoFTAccess fta(this);
  510. FT_Face face = fta.face();
  511. if (!face) {
  512. return nullptr;
  513. }
  514. std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
  515. info->fPostScriptName.set(FT_Get_Postscript_Name(face));
  516. info->fFontName = info->fPostScriptName;
  517. if (FT_HAS_MULTIPLE_MASTERS(face)) {
  518. info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
  519. }
  520. if (!canEmbed(face)) {
  521. info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
  522. }
  523. if (!canSubset(face)) {
  524. info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
  525. }
  526. info->fType = get_font_type(face);
  527. info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
  528. if (FT_IS_FIXED_WIDTH(face)) {
  529. info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
  530. }
  531. if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
  532. info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
  533. }
  534. PS_FontInfoRec psFontInfo;
  535. TT_Postscript* postTable;
  536. if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
  537. info->fItalicAngle = psFontInfo.italic_angle;
  538. } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
  539. info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
  540. } else {
  541. info->fItalicAngle = 0;
  542. }
  543. info->fAscent = face->ascender;
  544. info->fDescent = face->descender;
  545. TT_PCLT* pcltTable;
  546. TT_OS2* os2Table;
  547. if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
  548. info->fCapHeight = pcltTable->CapHeight;
  549. uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
  550. if (2 <= serif_style && serif_style <= 6) {
  551. info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
  552. } else if (9 <= serif_style && serif_style <= 12) {
  553. info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
  554. }
  555. } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
  556. // sCapHeight is available only when version 2 or later.
  557. os2Table->version != 0xFFFF &&
  558. os2Table->version >= 2)
  559. {
  560. info->fCapHeight = os2Table->sCapHeight;
  561. }
  562. info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
  563. face->bbox.xMax, face->bbox.yMin);
  564. return info;
  565. }
  566. void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
  567. SkASSERT(dstArray);
  568. AutoFTAccess fta(this);
  569. FT_Face face = fta.face();
  570. FT_Long numGlyphs = face->num_glyphs;
  571. sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
  572. FT_UInt glyphIndex;
  573. SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
  574. while (glyphIndex) {
  575. SkASSERT(glyphIndex < SkToUInt(numGlyphs));
  576. // Use the first character that maps to this glyphID. https://crbug.com/359065
  577. if (0 == dstArray[glyphIndex]) {
  578. dstArray[glyphIndex] = charCode;
  579. }
  580. charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
  581. }
  582. }
  583. void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
  584. SkASSERT(dstArray);
  585. AutoFTAccess fta(this);
  586. FT_Face face = fta.face();
  587. if (face && FT_HAS_GLYPH_NAMES(face)) {
  588. for (int gID = 0; gID < face->num_glyphs; gID++) {
  589. char glyphName[128]; // PS limit for names is 127 bytes.
  590. FT_Get_Glyph_Name(face, gID, glyphName, 128);
  591. dstArray[gID] = glyphName;
  592. }
  593. }
  594. }
  595. ///////////////////////////////////////////////////////////////////////////
  596. static bool bothZero(SkScalar a, SkScalar b) {
  597. return 0 == a && 0 == b;
  598. }
  599. // returns false if there is any non-90-rotation or skew
  600. static bool isAxisAligned(const SkScalerContextRec& rec) {
  601. return 0 == rec.fPreSkewX &&
  602. (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
  603. bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
  604. }
  605. SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
  606. const SkDescriptor* desc) const {
  607. auto c = skstd::make_unique<SkScalerContext_FreeType>(
  608. sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
  609. if (!c->success()) {
  610. return nullptr;
  611. }
  612. return c.release();
  613. }
  614. std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(
  615. const SkFontArguments& args) const {
  616. SkString name;
  617. AutoFTAccess fta(this);
  618. FT_Face face = fta.face();
  619. Scanner::AxisDefinitions axisDefinitions;
  620. if (!Scanner::GetAxes(face, &axisDefinitions)) {
  621. return nullptr;
  622. }
  623. SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
  624. Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
  625. axisValues, name);
  626. int ttcIndex;
  627. std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
  628. return skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, axisValues.get(),
  629. axisDefinitions.count());
  630. }
  631. void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
  632. //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
  633. //Cap the requested size as larger sizes give bogus values.
  634. //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
  635. //Note that this also currently only protects against large text size requests,
  636. //the total matrix is not taken into account here.
  637. if (rec->fTextSize > SkIntToScalar(1 << 14)) {
  638. rec->fTextSize = SkIntToScalar(1 << 14);
  639. }
  640. if (isLCD(*rec)) {
  641. // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
  642. SkAutoMutexExclusive ama(f_t_mutex());
  643. ref_ft_library();
  644. if (!gFTLibrary->isLCDSupported()) {
  645. // If the runtime Freetype library doesn't support LCD, disable it here.
  646. rec->fMaskFormat = SkMask::kA8_Format;
  647. }
  648. unref_ft_library();
  649. }
  650. SkFontHinting h = rec->getHinting();
  651. if (SkFontHinting::kFull == h && !isLCD(*rec)) {
  652. // collapse full->normal hinting if we're not doing LCD
  653. h = SkFontHinting::kNormal;
  654. }
  655. // rotated text looks bad with hinting, so we disable it as needed
  656. if (!isAxisAligned(*rec)) {
  657. h = SkFontHinting::kNone;
  658. }
  659. rec->setHinting(h);
  660. #ifndef SK_GAMMA_APPLY_TO_A8
  661. if (!isLCD(*rec)) {
  662. // SRGBTODO: Is this correct? Do we want contrast boost?
  663. rec->ignorePreBlend();
  664. }
  665. #endif
  666. }
  667. int SkTypeface_FreeType::GetUnitsPerEm(FT_Face face) {
  668. if (!face) {
  669. return 0;
  670. }
  671. SkScalar upem = SkIntToScalar(face->units_per_EM);
  672. // At least some versions of FreeType set face->units_per_EM to 0 for bitmap only fonts.
  673. if (upem == 0) {
  674. TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
  675. if (ttHeader) {
  676. upem = SkIntToScalar(ttHeader->Units_Per_EM);
  677. }
  678. }
  679. return upem;
  680. }
  681. int SkTypeface_FreeType::onGetUPEM() const {
  682. AutoFTAccess fta(this);
  683. FT_Face face = fta.face();
  684. return GetUnitsPerEm(face);
  685. }
  686. bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
  687. int count, int32_t adjustments[]) const {
  688. AutoFTAccess fta(this);
  689. FT_Face face = fta.face();
  690. if (!face || !FT_HAS_KERNING(face)) {
  691. return false;
  692. }
  693. for (int i = 0; i < count - 1; ++i) {
  694. FT_Vector delta;
  695. FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
  696. FT_KERNING_UNSCALED, &delta);
  697. if (err) {
  698. return false;
  699. }
  700. adjustments[i] = delta.x;
  701. }
  702. return true;
  703. }
  704. /** Returns the bitmap strike equal to or just larger than the requested size. */
  705. static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
  706. if (face == nullptr) {
  707. LOG_INFO("chooseBitmapStrike aborted due to nullptr face.\n");
  708. return -1;
  709. }
  710. FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
  711. FT_Int chosenStrikeIndex = -1;
  712. FT_Pos chosenPPEM = 0;
  713. for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
  714. FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
  715. if (strikePPEM == requestedPPEM) {
  716. // exact match - our search stops here
  717. return strikeIndex;
  718. } else if (chosenPPEM < requestedPPEM) {
  719. // attempt to increase chosenPPEM
  720. if (chosenPPEM < strikePPEM) {
  721. chosenPPEM = strikePPEM;
  722. chosenStrikeIndex = strikeIndex;
  723. }
  724. } else {
  725. // attempt to decrease chosenPPEM, but not below requestedPPEM
  726. if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
  727. chosenPPEM = strikePPEM;
  728. chosenStrikeIndex = strikeIndex;
  729. }
  730. }
  731. }
  732. return chosenStrikeIndex;
  733. }
  734. SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
  735. const SkScalerContextEffects& effects,
  736. const SkDescriptor* desc)
  737. : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
  738. , fFace(nullptr)
  739. , fFTSize(nullptr)
  740. , fStrikeIndex(-1)
  741. {
  742. SkAutoMutexExclusive ac(f_t_mutex());
  743. SkASSERT_RELEASE(ref_ft_library());
  744. fFaceRec.reset(ref_ft_face(this->getTypeface()));
  745. // load the font file
  746. if (nullptr == fFaceRec) {
  747. LOG_INFO("Could not create FT_Face.\n");
  748. return;
  749. }
  750. fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
  751. // compute the flags we send to Load_Glyph
  752. bool linearMetrics = this->isLinearMetrics();
  753. {
  754. FT_Int32 loadFlags = FT_LOAD_DEFAULT;
  755. if (SkMask::kBW_Format == fRec.fMaskFormat) {
  756. // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
  757. loadFlags = FT_LOAD_TARGET_MONO;
  758. if (fRec.getHinting() == SkFontHinting::kNone) {
  759. loadFlags = FT_LOAD_NO_HINTING;
  760. linearMetrics = true;
  761. }
  762. } else {
  763. switch (fRec.getHinting()) {
  764. case SkFontHinting::kNone:
  765. loadFlags = FT_LOAD_NO_HINTING;
  766. linearMetrics = true;
  767. break;
  768. case SkFontHinting::kSlight:
  769. loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
  770. if (gFTLibrary->lightHintingIsYOnly()) {
  771. linearMetrics = true;
  772. }
  773. break;
  774. case SkFontHinting::kNormal:
  775. loadFlags = FT_LOAD_TARGET_NORMAL;
  776. break;
  777. case SkFontHinting::kFull:
  778. loadFlags = FT_LOAD_TARGET_NORMAL;
  779. if (isLCD(fRec)) {
  780. if (fLCDIsVert) {
  781. loadFlags = FT_LOAD_TARGET_LCD_V;
  782. } else {
  783. loadFlags = FT_LOAD_TARGET_LCD;
  784. }
  785. }
  786. break;
  787. default:
  788. LOG_INFO("---------- UNKNOWN hinting %d\n", fRec.getHinting());
  789. break;
  790. }
  791. }
  792. if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
  793. loadFlags |= FT_LOAD_FORCE_AUTOHINT;
  794. #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
  795. } else {
  796. loadFlags |= FT_LOAD_NO_AUTOHINT;
  797. #endif
  798. }
  799. if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
  800. loadFlags |= FT_LOAD_NO_BITMAP;
  801. }
  802. // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
  803. // advances, as fontconfig and cairo do.
  804. // See http://code.google.com/p/skia/issues/detail?id=222.
  805. loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
  806. // Use vertical layout if requested.
  807. if (this->isVertical()) {
  808. loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
  809. }
  810. loadFlags |= FT_LOAD_COLOR;
  811. fLoadGlyphFlags = loadFlags;
  812. }
  813. using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
  814. std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
  815. FT_Size size;
  816. FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
  817. if (err != 0) {
  818. SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
  819. return nullptr;
  820. }
  821. return size;
  822. }());
  823. if (nullptr == ftSize) {
  824. LOG_INFO("Could not create FT_Size.\n");
  825. return;
  826. }
  827. FT_Error err = FT_Activate_Size(ftSize.get());
  828. if (err != 0) {
  829. SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
  830. return;
  831. }
  832. fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
  833. FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
  834. FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
  835. if (FT_IS_SCALABLE(fFaceRec->fFace)) {
  836. err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
  837. if (err != 0) {
  838. SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
  839. fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
  840. return;
  841. }
  842. // Adjust the matrix to reflect the actually chosen scale.
  843. // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
  844. // Don't do this at all sizes as that will interfere with hinting.
  845. if (fScale.fX < 1 || fScale.fY < 1) {
  846. SkScalar upem = fFaceRec->fFace->units_per_EM;
  847. FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
  848. SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
  849. SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
  850. fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
  851. }
  852. } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
  853. fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
  854. if (fStrikeIndex == -1) {
  855. LOG_INFO("No glyphs for font \"%s\" size %f.\n",
  856. fFaceRec->fFace->family_name, fScale.fY);
  857. return;
  858. }
  859. err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
  860. if (err != 0) {
  861. SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
  862. fFaceRec->fFace->family_name, fStrikeIndex);
  863. fStrikeIndex = -1;
  864. return;
  865. }
  866. // Adjust the matrix to reflect the actually chosen scale.
  867. // It is likely that the ppem chosen was not the one requested, this allows for scaling.
  868. fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
  869. fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
  870. // FreeType does not provide linear metrics for bitmap fonts.
  871. linearMetrics = false;
  872. // FreeType documentation says:
  873. // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
  874. // Bitmap-only fonts ignore this flag.
  875. //
  876. // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
  877. // Force this flag off for bitmap only fonts.
  878. fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
  879. } else {
  880. LOG_INFO("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
  881. return;
  882. }
  883. fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
  884. fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
  885. fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
  886. fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
  887. #ifdef FT_COLOR_H
  888. FT_Palette_Select(fFaceRec->fFace.get(), 0, nullptr);
  889. #endif
  890. fFTSize = ftSize.release();
  891. fFace = fFaceRec->fFace.get();
  892. fDoLinearMetrics = linearMetrics;
  893. }
  894. SkScalerContext_FreeType::~SkScalerContext_FreeType() {
  895. SkAutoMutexExclusive ac(f_t_mutex());
  896. if (fFTSize != nullptr) {
  897. FT_Done_Size(fFTSize);
  898. }
  899. fFaceRec = nullptr;
  900. unref_ft_library();
  901. }
  902. /* We call this before each use of the fFace, since we may be sharing
  903. this face with other context (at different sizes).
  904. */
  905. FT_Error SkScalerContext_FreeType::setupSize() {
  906. f_t_mutex().assertHeld();
  907. FT_Error err = FT_Activate_Size(fFTSize);
  908. if (err != 0) {
  909. return err;
  910. }
  911. FT_Set_Transform(fFace, &fMatrix22, nullptr);
  912. return 0;
  913. }
  914. unsigned SkScalerContext_FreeType::generateGlyphCount() {
  915. return fFace->num_glyphs;
  916. }
  917. bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
  918. /* unhinted and light hinted text have linearly scaled advances
  919. * which are very cheap to compute with some font formats...
  920. */
  921. if (!fDoLinearMetrics) {
  922. return false;
  923. }
  924. SkAutoMutexExclusive ac(f_t_mutex());
  925. if (this->setupSize()) {
  926. glyph->zeroMetrics();
  927. return true;
  928. }
  929. FT_Error error;
  930. FT_Fixed advance;
  931. error = FT_Get_Advance( fFace, glyph->getGlyphID(),
  932. fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
  933. &advance );
  934. if (error != 0) {
  935. return false;
  936. }
  937. const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
  938. glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
  939. glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
  940. return true;
  941. }
  942. void SkScalerContext_FreeType::getBBoxForCurrentGlyph(const SkGlyph* glyph,
  943. FT_BBox* bbox,
  944. bool snapToPixelBoundary) {
  945. FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
  946. if (this->isSubpixel()) {
  947. int dx = SkFixedToFDot6(glyph->getSubXFixed());
  948. int dy = SkFixedToFDot6(glyph->getSubYFixed());
  949. // negate dy since freetype-y-goes-up and skia-y-goes-down
  950. bbox->xMin += dx;
  951. bbox->yMin -= dy;
  952. bbox->xMax += dx;
  953. bbox->yMax -= dy;
  954. }
  955. // outset the box to integral boundaries
  956. if (snapToPixelBoundary) {
  957. bbox->xMin &= ~63;
  958. bbox->yMin &= ~63;
  959. bbox->xMax = (bbox->xMax + 63) & ~63;
  960. bbox->yMax = (bbox->yMax + 63) & ~63;
  961. }
  962. // Must come after snapToPixelBoundary so that the width and height are
  963. // consistent. Otherwise asserts will fire later on when generating the
  964. // glyph image.
  965. if (this->isVertical()) {
  966. FT_Vector vector;
  967. vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
  968. vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
  969. FT_Vector_Transform(&vector, &fMatrix22);
  970. bbox->xMin += vector.x;
  971. bbox->xMax += vector.x;
  972. bbox->yMin += vector.y;
  973. bbox->yMax += vector.y;
  974. }
  975. }
  976. bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
  977. const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
  978. if (!glyph_id) {
  979. return false;
  980. }
  981. if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
  982. return false;
  983. }
  984. emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
  985. FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
  986. return true;
  987. }
  988. void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
  989. if (glyph->fMaskFormat == SkMask::kLCD16_Format) {
  990. if (fLCDIsVert) {
  991. glyph->fHeight += gFTLibrary->lcdExtra();
  992. glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
  993. } else {
  994. glyph->fWidth += gFTLibrary->lcdExtra();
  995. glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
  996. }
  997. }
  998. }
  999. bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
  1000. // If subpixel rendering of a bitmap *can* be done.
  1001. bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
  1002. this->isSubpixel() &&
  1003. (glyph.getSubXFixed() || glyph.getSubYFixed());
  1004. // If subpixel rendering of a bitmap *should* be done.
  1005. // 1. If the face is not scalable then always allow subpixel rendering.
  1006. // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
  1007. // 2. If the matrix is already not identity the bitmap will already be resampled,
  1008. // so resampling slightly differently shouldn't make much difference.
  1009. bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
  1010. return mechanism && policy;
  1011. }
  1012. void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
  1013. SkAutoMutexExclusive ac(f_t_mutex());
  1014. glyph->fMaskFormat = fRec.fMaskFormat;
  1015. if (this->setupSize()) {
  1016. glyph->zeroMetrics();
  1017. return;
  1018. }
  1019. FT_Error err;
  1020. err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
  1021. fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
  1022. if (err != 0) {
  1023. glyph->zeroMetrics();
  1024. return;
  1025. }
  1026. emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
  1027. if (fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
  1028. using FT_PosLimits = std::numeric_limits<FT_Pos>;
  1029. FT_BBox bounds = { FT_PosLimits::max(), FT_PosLimits::max(),
  1030. FT_PosLimits::min(), FT_PosLimits::min() };
  1031. #ifdef FT_COLOR_H
  1032. FT_Bool haveLayers = false;
  1033. FT_LayerIterator layerIterator = { 0, 0, nullptr };
  1034. FT_UInt layerGlyphIndex;
  1035. FT_UInt layerColorIndex;
  1036. while (FT_Get_Color_Glyph_Layer(fFace, glyph->getGlyphID(),
  1037. &layerGlyphIndex, &layerColorIndex, &layerIterator))
  1038. {
  1039. haveLayers = true;
  1040. err = FT_Load_Glyph(fFace, layerGlyphIndex,
  1041. fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
  1042. if (err != 0) {
  1043. glyph->zeroMetrics();
  1044. return;
  1045. }
  1046. emboldenIfNeeded(fFace, fFace->glyph, layerGlyphIndex);
  1047. if (0 < fFace->glyph->outline.n_contours) {
  1048. FT_BBox bbox;
  1049. getBBoxForCurrentGlyph(glyph, &bbox, true);
  1050. // Union
  1051. bounds.xMin = std::min(bbox.xMin, bounds.xMin);
  1052. bounds.yMin = std::min(bbox.yMin, bounds.yMin);
  1053. bounds.xMax = std::max(bbox.xMax, bounds.xMax);
  1054. bounds.yMax = std::max(bbox.yMax, bounds.yMax);
  1055. }
  1056. }
  1057. if (haveLayers) {
  1058. glyph->fMaskFormat = SkMask::kARGB32_Format;
  1059. if (!(bounds.xMin < bounds.xMax && bounds.yMin < bounds.yMax)) {
  1060. bounds = { 0, 0, 0, 0 };
  1061. }
  1062. } else {
  1063. #endif
  1064. if (0 < fFace->glyph->outline.n_contours) {
  1065. getBBoxForCurrentGlyph(glyph, &bounds, true);
  1066. } else {
  1067. bounds = { 0, 0, 0, 0 };
  1068. }
  1069. #ifdef FT_COLOR_H
  1070. }
  1071. #endif
  1072. // Round out, no longer dot6.
  1073. bounds.xMin = SkFDot6Floor(bounds.xMin);
  1074. bounds.yMin = SkFDot6Floor(bounds.yMin);
  1075. bounds.xMax = SkFDot6Ceil (bounds.xMax);
  1076. bounds.yMax = SkFDot6Ceil (bounds.yMax);
  1077. FT_Pos width = bounds.xMax - bounds.xMin;
  1078. FT_Pos height = bounds.yMax - bounds.yMin;
  1079. FT_Pos top = -bounds.yMax; // Freetype y-up, Skia y-down.
  1080. FT_Pos left = bounds.xMin;
  1081. if (!SkTFitsIn<decltype(glyph->fWidth )>(width ) ||
  1082. !SkTFitsIn<decltype(glyph->fHeight)>(height) ||
  1083. !SkTFitsIn<decltype(glyph->fTop )>(top ) ||
  1084. !SkTFitsIn<decltype(glyph->fLeft )>(left ) )
  1085. {
  1086. width = height = top = left = 0;
  1087. }
  1088. glyph->fWidth = SkToU16(width );
  1089. glyph->fHeight = SkToU16(height);
  1090. glyph->fTop = SkToS16(top );
  1091. glyph->fLeft = SkToS16(left );
  1092. updateGlyphIfLCD(glyph);
  1093. } else if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
  1094. if (this->isVertical()) {
  1095. FT_Vector vector;
  1096. vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
  1097. vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
  1098. FT_Vector_Transform(&vector, &fMatrix22);
  1099. fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
  1100. fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
  1101. }
  1102. if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
  1103. glyph->fMaskFormat = SkMask::kARGB32_Format;
  1104. }
  1105. {
  1106. SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
  1107. -SkIntToScalar(fFace->glyph->bitmap_top),
  1108. SkIntToScalar(fFace->glyph->bitmap.width),
  1109. SkIntToScalar(fFace->glyph->bitmap.rows));
  1110. fMatrix22Scalar.mapRect(&rect);
  1111. if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
  1112. rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
  1113. SkFixedToScalar(glyph->getSubYFixed()));
  1114. }
  1115. SkIRect irect = rect.roundOut();
  1116. glyph->fWidth = SkToU16(irect.width());
  1117. glyph->fHeight = SkToU16(irect.height());
  1118. glyph->fTop = SkToS16(irect.top());
  1119. glyph->fLeft = SkToS16(irect.left());
  1120. }
  1121. } else {
  1122. SkDEBUGFAIL("unknown glyph format");
  1123. glyph->zeroMetrics();
  1124. return;
  1125. }
  1126. if (this->isVertical()) {
  1127. if (fDoLinearMetrics) {
  1128. const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
  1129. glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
  1130. glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
  1131. } else {
  1132. glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
  1133. glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
  1134. }
  1135. } else {
  1136. if (fDoLinearMetrics) {
  1137. const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
  1138. glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
  1139. glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
  1140. } else {
  1141. glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
  1142. glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
  1143. }
  1144. }
  1145. #ifdef ENABLE_GLYPH_SPEW
  1146. LOG_INFO("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
  1147. #endif
  1148. }
  1149. void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
  1150. SkAutoMutexExclusive ac(f_t_mutex());
  1151. if (this->setupSize()) {
  1152. sk_bzero(glyph.fImage, glyph.imageSize());
  1153. return;
  1154. }
  1155. FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
  1156. if (err != 0) {
  1157. SK_TRACEFTR(err, "SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d "
  1158. "width:%d height:%d rb:%d flags:%d) failed.",
  1159. glyph.getGlyphID(), glyph.width(), glyph.height(), glyph.rowBytes(),
  1160. fLoadGlyphFlags);
  1161. sk_bzero(glyph.fImage, glyph.imageSize());
  1162. return;
  1163. }
  1164. emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
  1165. SkMatrix* bitmapMatrix = &fMatrix22Scalar;
  1166. SkMatrix subpixelBitmapMatrix;
  1167. if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
  1168. subpixelBitmapMatrix = fMatrix22Scalar;
  1169. subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
  1170. SkFixedToScalar(glyph.getSubYFixed()));
  1171. bitmapMatrix = &subpixelBitmapMatrix;
  1172. }
  1173. generateGlyphImage(fFace, glyph, *bitmapMatrix);
  1174. }
  1175. bool SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
  1176. SkASSERT(path);
  1177. SkAutoMutexExclusive ac(f_t_mutex());
  1178. // FT_IS_SCALABLE is documented to mean the face contains outline glyphs.
  1179. if (!FT_IS_SCALABLE(fFace) || this->setupSize()) {
  1180. path->reset();
  1181. return false;
  1182. }
  1183. uint32_t flags = fLoadGlyphFlags;
  1184. flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
  1185. flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
  1186. FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
  1187. if (err != 0 || fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
  1188. path->reset();
  1189. return false;
  1190. }
  1191. emboldenIfNeeded(fFace, fFace->glyph, glyphID);
  1192. if (!generateGlyphPath(fFace, path)) {
  1193. path->reset();
  1194. return false;
  1195. }
  1196. // The path's origin from FreeType is always the horizontal layout origin.
  1197. // Offset the path so that it is relative to the vertical origin if needed.
  1198. if (this->isVertical()) {
  1199. FT_Vector vector;
  1200. vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
  1201. vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
  1202. FT_Vector_Transform(&vector, &fMatrix22);
  1203. path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
  1204. }
  1205. return true;
  1206. }
  1207. void SkScalerContext_FreeType::generateFontMetrics(SkFontMetrics* metrics) {
  1208. if (nullptr == metrics) {
  1209. return;
  1210. }
  1211. SkAutoMutexExclusive ac(f_t_mutex());
  1212. if (this->setupSize()) {
  1213. sk_bzero(metrics, sizeof(*metrics));
  1214. return;
  1215. }
  1216. FT_Face face = fFace;
  1217. metrics->fFlags = 0;
  1218. SkScalar upem = SkIntToScalar(SkTypeface_FreeType::GetUnitsPerEm(face));
  1219. // use the os/2 table as a source of reasonable defaults.
  1220. SkScalar x_height = 0.0f;
  1221. SkScalar avgCharWidth = 0.0f;
  1222. SkScalar cap_height = 0.0f;
  1223. SkScalar strikeoutThickness = 0.0f, strikeoutPosition = 0.0f;
  1224. TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
  1225. if (os2) {
  1226. x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
  1227. avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
  1228. strikeoutThickness = SkIntToScalar(os2->yStrikeoutSize) / upem;
  1229. strikeoutPosition = -SkIntToScalar(os2->yStrikeoutPosition) / upem;
  1230. metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
  1231. metrics->fFlags |= SkFontMetrics::kStrikeoutPositionIsValid_Flag;
  1232. if (os2->version != 0xFFFF && os2->version >= 2) {
  1233. cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
  1234. }
  1235. }
  1236. // pull from format-specific metrics as needed
  1237. SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
  1238. SkScalar underlineThickness, underlinePosition;
  1239. if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
  1240. // FreeType will always use HHEA metrics if they're not zero.
  1241. // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
  1242. // It also ignores the VDMX tables, which are also of interest here
  1243. // (and override everything else when they apply).
  1244. static const int kUseTypoMetricsMask = (1 << 7);
  1245. if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
  1246. ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
  1247. descent = -SkIntToScalar(os2->sTypoDescender) / upem;
  1248. leading = SkIntToScalar(os2->sTypoLineGap) / upem;
  1249. } else {
  1250. ascent = -SkIntToScalar(face->ascender) / upem;
  1251. descent = -SkIntToScalar(face->descender) / upem;
  1252. leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
  1253. }
  1254. xmin = SkIntToScalar(face->bbox.xMin) / upem;
  1255. xmax = SkIntToScalar(face->bbox.xMax) / upem;
  1256. ymin = -SkIntToScalar(face->bbox.yMin) / upem;
  1257. ymax = -SkIntToScalar(face->bbox.yMax) / upem;
  1258. underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
  1259. underlinePosition = -SkIntToScalar(face->underline_position +
  1260. face->underline_thickness / 2) / upem;
  1261. metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
  1262. metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
  1263. // we may be able to synthesize x_height and cap_height from outline
  1264. if (!x_height) {
  1265. FT_BBox bbox;
  1266. if (getCBoxForLetter('x', &bbox)) {
  1267. x_height = SkIntToScalar(bbox.yMax) / 64.0f;
  1268. }
  1269. }
  1270. if (!cap_height) {
  1271. FT_BBox bbox;
  1272. if (getCBoxForLetter('H', &bbox)) {
  1273. cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
  1274. }
  1275. }
  1276. } else if (fStrikeIndex != -1) { // bitmap strike metrics
  1277. SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
  1278. SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
  1279. ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
  1280. descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
  1281. leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
  1282. xmin = 0.0f;
  1283. xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
  1284. ymin = descent;
  1285. ymax = ascent;
  1286. underlineThickness = 0;
  1287. underlinePosition = 0;
  1288. metrics->fFlags &= ~SkFontMetrics::kUnderlineThicknessIsValid_Flag;
  1289. metrics->fFlags &= ~SkFontMetrics::kUnderlinePositionIsValid_Flag;
  1290. TT_Postscript* post = (TT_Postscript*) FT_Get_Sfnt_Table(face, ft_sfnt_post);
  1291. if (post) {
  1292. underlineThickness = SkIntToScalar(post->underlineThickness) / upem;
  1293. underlinePosition = -SkIntToScalar(post->underlinePosition) / upem;
  1294. metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
  1295. metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
  1296. }
  1297. } else {
  1298. sk_bzero(metrics, sizeof(*metrics));
  1299. return;
  1300. }
  1301. // synthesize elements that were not provided by the os/2 table or format-specific metrics
  1302. if (!x_height) {
  1303. x_height = -ascent * fScale.y();
  1304. }
  1305. if (!avgCharWidth) {
  1306. avgCharWidth = xmax - xmin;
  1307. }
  1308. if (!cap_height) {
  1309. cap_height = -ascent * fScale.y();
  1310. }
  1311. // disallow negative linespacing
  1312. if (leading < 0.0f) {
  1313. leading = 0.0f;
  1314. }
  1315. metrics->fTop = ymax * fScale.y();
  1316. metrics->fAscent = ascent * fScale.y();
  1317. metrics->fDescent = descent * fScale.y();
  1318. metrics->fBottom = ymin * fScale.y();
  1319. metrics->fLeading = leading * fScale.y();
  1320. metrics->fAvgCharWidth = avgCharWidth * fScale.y();
  1321. metrics->fXMin = xmin * fScale.y();
  1322. metrics->fXMax = xmax * fScale.y();
  1323. metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
  1324. metrics->fXHeight = x_height;
  1325. metrics->fCapHeight = cap_height;
  1326. metrics->fUnderlineThickness = underlineThickness * fScale.y();
  1327. metrics->fUnderlinePosition = underlinePosition * fScale.y();
  1328. metrics->fStrikeoutThickness = strikeoutThickness * fScale.y();
  1329. metrics->fStrikeoutPosition = strikeoutPosition * fScale.y();
  1330. }
  1331. ///////////////////////////////////////////////////////////////////////////////
  1332. // hand-tuned value to reduce outline embolden strength
  1333. #ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
  1334. #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
  1335. #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
  1336. #else
  1337. #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
  1338. #endif
  1339. #endif
  1340. ///////////////////////////////////////////////////////////////////////////////
  1341. void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid) {
  1342. // check to see if the embolden bit is set
  1343. if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
  1344. return;
  1345. }
  1346. switch (glyph->format) {
  1347. case FT_GLYPH_FORMAT_OUTLINE:
  1348. FT_Pos strength;
  1349. strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
  1350. / SK_OUTLINE_EMBOLDEN_DIVISOR;
  1351. FT_Outline_Embolden(&glyph->outline, strength);
  1352. break;
  1353. case FT_GLYPH_FORMAT_BITMAP:
  1354. if (!fFace->glyph->bitmap.buffer) {
  1355. FT_Load_Glyph(fFace, gid, fLoadGlyphFlags);
  1356. }
  1357. FT_GlyphSlot_Own_Bitmap(glyph);
  1358. FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
  1359. break;
  1360. default:
  1361. SkDEBUGFAIL("unknown glyph format");
  1362. }
  1363. }
  1364. ///////////////////////////////////////////////////////////////////////////////
  1365. #include "src/core/SkUtils.h"
  1366. // Just made up, so we don't end up storing 1000s of entries
  1367. constexpr int kMaxC2GCacheCount = 512;
  1368. void SkTypeface_FreeType::onCharsToGlyphs(const SkUnichar uni[], int count,
  1369. SkGlyphID glyphs[]) const {
  1370. // Try the cache first, *before* accessing freetype lib/face, as that
  1371. // can be very slow. If we do need to compute a new glyphID, then
  1372. // access those freetype objects and continue the loop.
  1373. SkAutoMutexExclusive ama(fC2GCacheMutex);
  1374. int i;
  1375. for (i = 0; i < count; ++i) {
  1376. int index = fC2GCache.findGlyphIndex(uni[i]);
  1377. if (index < 0) {
  1378. break;
  1379. }
  1380. glyphs[i] = SkToU16(index);
  1381. }
  1382. if (i == count) {
  1383. // we're done, no need to access the freetype objects
  1384. return;
  1385. }
  1386. AutoFTAccess fta(this);
  1387. FT_Face face = fta.face();
  1388. if (!face) {
  1389. sk_bzero(glyphs, count * sizeof(glyphs[0]));
  1390. return;
  1391. }
  1392. for (; i < count; ++i) {
  1393. SkUnichar c = uni[i];
  1394. int index = fC2GCache.findGlyphIndex(c);
  1395. if (index >= 0) {
  1396. glyphs[i] = SkToU16(index);
  1397. } else {
  1398. glyphs[i] = SkToU16(FT_Get_Char_Index(face, c));
  1399. fC2GCache.insertCharAndGlyph(~index, c, glyphs[i]);
  1400. }
  1401. }
  1402. if (fC2GCache.count() > kMaxC2GCacheCount) {
  1403. fC2GCache.reset();
  1404. }
  1405. }
  1406. int SkTypeface_FreeType::onCountGlyphs() const {
  1407. AutoFTAccess fta(this);
  1408. FT_Face face = fta.face();
  1409. return face ? face->num_glyphs : 0;
  1410. }
  1411. SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
  1412. sk_sp<SkTypeface::LocalizedStrings> nameIter =
  1413. SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
  1414. if (!nameIter) {
  1415. SkString familyName;
  1416. this->getFamilyName(&familyName);
  1417. SkString language("und"); //undetermined
  1418. nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
  1419. }
  1420. return nameIter.release();
  1421. }
  1422. int SkTypeface_FreeType::onGetVariationDesignPosition(
  1423. SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
  1424. {
  1425. AutoFTAccess fta(this);
  1426. FT_Face face = fta.face();
  1427. if (!face) {
  1428. return -1;
  1429. }
  1430. if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
  1431. return 0;
  1432. }
  1433. FT_MM_Var* variations = nullptr;
  1434. if (FT_Get_MM_Var(face, &variations)) {
  1435. return -1;
  1436. }
  1437. SkAutoFree autoFreeVariations(variations);
  1438. if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
  1439. return variations->num_axis;
  1440. }
  1441. SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
  1442. // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
  1443. if (gFTLibrary->fGetVarDesignCoordinates &&
  1444. !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
  1445. {
  1446. for (FT_UInt i = 0; i < variations->num_axis; ++i) {
  1447. coordinates[i].axis = variations->axis[i].tag;
  1448. coordinates[i].value = SkFixedToScalar(coords[i]);
  1449. }
  1450. } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
  1451. for (FT_UInt i = 0; i < variations->num_axis; ++i) {
  1452. coordinates[i].axis = variations->axis[i].tag;
  1453. coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
  1454. }
  1455. } else if (fta.isNamedVariationSpecified()) {
  1456. // The font has axes, they cannot be retrieved, and some named axis was specified.
  1457. return -1;
  1458. } else {
  1459. // The font has axes, they cannot be retrieved, but no named instance was specified.
  1460. return 0;
  1461. }
  1462. return variations->num_axis;
  1463. }
  1464. int SkTypeface_FreeType::onGetVariationDesignParameters(
  1465. SkFontParameters::Variation::Axis parameters[], int parameterCount) const
  1466. {
  1467. AutoFTAccess fta(this);
  1468. FT_Face face = fta.face();
  1469. if (!face) {
  1470. return -1;
  1471. }
  1472. if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
  1473. return 0;
  1474. }
  1475. FT_MM_Var* variations = nullptr;
  1476. if (FT_Get_MM_Var(face, &variations)) {
  1477. return -1;
  1478. }
  1479. SkAutoFree autoFreeVariations(variations);
  1480. if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
  1481. return variations->num_axis;
  1482. }
  1483. for (FT_UInt i = 0; i < variations->num_axis; ++i) {
  1484. parameters[i].tag = variations->axis[i].tag;
  1485. parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
  1486. parameters[i].def = SkFixedToScalar(variations->axis[i].def);
  1487. parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
  1488. FT_UInt flags = 0;
  1489. bool hidden = gFTLibrary->fGetVarAxisFlags &&
  1490. !gFTLibrary->fGetVarAxisFlags(variations, i, &flags) &&
  1491. (flags & FT_VAR_AXIS_FLAG_HIDDEN);
  1492. parameters[i].setHidden(hidden);
  1493. }
  1494. return variations->num_axis;
  1495. }
  1496. int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
  1497. AutoFTAccess fta(this);
  1498. FT_Face face = fta.face();
  1499. FT_ULong tableCount = 0;
  1500. FT_Error error;
  1501. // When 'tag' is nullptr, returns number of tables in 'length'.
  1502. error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
  1503. if (error) {
  1504. return 0;
  1505. }
  1506. if (tags) {
  1507. for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
  1508. FT_ULong tableTag;
  1509. FT_ULong tablelength;
  1510. error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
  1511. if (error) {
  1512. return 0;
  1513. }
  1514. tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
  1515. }
  1516. }
  1517. return tableCount;
  1518. }
  1519. size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
  1520. size_t length, void* data) const
  1521. {
  1522. AutoFTAccess fta(this);
  1523. FT_Face face = fta.face();
  1524. FT_ULong tableLength = 0;
  1525. FT_Error error;
  1526. // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
  1527. error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
  1528. if (error) {
  1529. return 0;
  1530. }
  1531. if (offset > tableLength) {
  1532. return 0;
  1533. }
  1534. FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
  1535. if (data) {
  1536. error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
  1537. if (error) {
  1538. return 0;
  1539. }
  1540. }
  1541. return size;
  1542. }
  1543. sk_sp<SkData> SkTypeface_FreeType::onCopyTableData(SkFontTableTag tag) const {
  1544. AutoFTAccess fta(this);
  1545. FT_Face face = fta.face();
  1546. FT_ULong tableLength = 0;
  1547. FT_Error error;
  1548. // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
  1549. error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
  1550. if (error) {
  1551. return nullptr;
  1552. }
  1553. sk_sp<SkData> data = SkData::MakeUninitialized(tableLength);
  1554. if (data) {
  1555. error = FT_Load_Sfnt_Table(face, tag, 0,
  1556. reinterpret_cast<FT_Byte*>(data->writable_data()), &tableLength);
  1557. if (error) {
  1558. data.reset();
  1559. }
  1560. }
  1561. return data;
  1562. }
  1563. ///////////////////////////////////////////////////////////////////////////////
  1564. ///////////////////////////////////////////////////////////////////////////////
  1565. SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
  1566. if (FT_New_Library(&gFTMemory, &fLibrary)) {
  1567. return;
  1568. }
  1569. FT_Add_Default_Modules(fLibrary);
  1570. }
  1571. SkTypeface_FreeType::Scanner::~Scanner() {
  1572. if (fLibrary) {
  1573. FT_Done_Library(fLibrary);
  1574. }
  1575. }
  1576. FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
  1577. FT_Stream ftStream) const
  1578. {
  1579. if (fLibrary == nullptr) {
  1580. return nullptr;
  1581. }
  1582. FT_Open_Args args;
  1583. memset(&args, 0, sizeof(args));
  1584. const void* memoryBase = stream->getMemoryBase();
  1585. if (memoryBase) {
  1586. args.flags = FT_OPEN_MEMORY;
  1587. args.memory_base = (const FT_Byte*)memoryBase;
  1588. args.memory_size = stream->getLength();
  1589. } else {
  1590. memset(ftStream, 0, sizeof(*ftStream));
  1591. ftStream->size = stream->getLength();
  1592. ftStream->descriptor.pointer = stream;
  1593. ftStream->read = sk_ft_stream_io;
  1594. ftStream->close = sk_ft_stream_close;
  1595. args.flags = FT_OPEN_STREAM;
  1596. args.stream = ftStream;
  1597. }
  1598. FT_Face face;
  1599. if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
  1600. return nullptr;
  1601. }
  1602. return face;
  1603. }
  1604. bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
  1605. SkAutoMutexExclusive libraryLock(fLibraryMutex);
  1606. FT_StreamRec streamRec;
  1607. FT_Face face = this->openFace(stream, -1, &streamRec);
  1608. if (nullptr == face) {
  1609. return false;
  1610. }
  1611. *numFaces = face->num_faces;
  1612. FT_Done_Face(face);
  1613. return true;
  1614. }
  1615. #include "src/core/SkTSearch.h"
  1616. bool SkTypeface_FreeType::Scanner::scanFont(
  1617. SkStreamAsset* stream, int ttcIndex,
  1618. SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
  1619. {
  1620. SkAutoMutexExclusive libraryLock(fLibraryMutex);
  1621. FT_StreamRec streamRec;
  1622. FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
  1623. if (nullptr == face) {
  1624. return false;
  1625. }
  1626. int weight = SkFontStyle::kNormal_Weight;
  1627. int width = SkFontStyle::kNormal_Width;
  1628. SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
  1629. if (face->style_flags & FT_STYLE_FLAG_BOLD) {
  1630. weight = SkFontStyle::kBold_Weight;
  1631. }
  1632. if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
  1633. slant = SkFontStyle::kItalic_Slant;
  1634. }
  1635. PS_FontInfoRec psFontInfo;
  1636. TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
  1637. if (os2 && os2->version != 0xffff) {
  1638. weight = os2->usWeightClass;
  1639. width = os2->usWidthClass;
  1640. // OS/2::fsSelection bit 9 indicates oblique.
  1641. if (SkToBool(os2->fsSelection & (1u << 9))) {
  1642. slant = SkFontStyle::kOblique_Slant;
  1643. }
  1644. } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
  1645. static const struct {
  1646. char const * const name;
  1647. int const weight;
  1648. } commonWeights [] = {
  1649. // There are probably more common names, but these are known to exist.
  1650. { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
  1651. { "black", SkFontStyle::kBlack_Weight },
  1652. { "bold", SkFontStyle::kBold_Weight },
  1653. { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
  1654. { "demi", SkFontStyle::kSemiBold_Weight },
  1655. { "demibold", SkFontStyle::kSemiBold_Weight },
  1656. { "extra", SkFontStyle::kExtraBold_Weight },
  1657. { "extrabold", SkFontStyle::kExtraBold_Weight },
  1658. { "extralight", SkFontStyle::kExtraLight_Weight },
  1659. { "hairline", SkFontStyle::kThin_Weight },
  1660. { "heavy", SkFontStyle::kBlack_Weight },
  1661. { "light", SkFontStyle::kLight_Weight },
  1662. { "medium", SkFontStyle::kMedium_Weight },
  1663. { "normal", SkFontStyle::kNormal_Weight },
  1664. { "plain", SkFontStyle::kNormal_Weight },
  1665. { "regular", SkFontStyle::kNormal_Weight },
  1666. { "roman", SkFontStyle::kNormal_Weight },
  1667. { "semibold", SkFontStyle::kSemiBold_Weight },
  1668. { "standard", SkFontStyle::kNormal_Weight },
  1669. { "thin", SkFontStyle::kThin_Weight },
  1670. { "ultra", SkFontStyle::kExtraBold_Weight },
  1671. { "ultrablack", SkFontStyle::kExtraBlack_Weight },
  1672. { "ultrabold", SkFontStyle::kExtraBold_Weight },
  1673. { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
  1674. { "ultralight", SkFontStyle::kExtraLight_Weight },
  1675. };
  1676. int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
  1677. psFontInfo.weight, sizeof(commonWeights[0]));
  1678. if (index >= 0) {
  1679. weight = commonWeights[index].weight;
  1680. } else {
  1681. LOG_INFO("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
  1682. }
  1683. }
  1684. if (name) {
  1685. name->set(face->family_name);
  1686. }
  1687. if (style) {
  1688. *style = SkFontStyle(weight, width, slant);
  1689. }
  1690. if (isFixedPitch) {
  1691. *isFixedPitch = FT_IS_FIXED_WIDTH(face);
  1692. }
  1693. bool success = GetAxes(face, axes);
  1694. FT_Done_Face(face);
  1695. return success;
  1696. }
  1697. bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
  1698. if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
  1699. FT_MM_Var* variations = nullptr;
  1700. FT_Error err = FT_Get_MM_Var(face, &variations);
  1701. if (err) {
  1702. LOG_INFO("INFO: font %s claims to have variations, but none found.\n",
  1703. face->family_name);
  1704. return false;
  1705. }
  1706. SkAutoFree autoFreeVariations(variations);
  1707. axes->reset(variations->num_axis);
  1708. for (FT_UInt i = 0; i < variations->num_axis; ++i) {
  1709. const FT_Var_Axis& ftAxis = variations->axis[i];
  1710. (*axes)[i].fTag = ftAxis.tag;
  1711. (*axes)[i].fMinimum = ftAxis.minimum;
  1712. (*axes)[i].fDefault = ftAxis.def;
  1713. (*axes)[i].fMaximum = ftAxis.maximum;
  1714. }
  1715. }
  1716. return true;
  1717. }
  1718. /*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
  1719. AxisDefinitions axisDefinitions,
  1720. const SkFontArguments::VariationPosition position,
  1721. SkFixed* axisValues,
  1722. const SkString& name)
  1723. {
  1724. for (int i = 0; i < axisDefinitions.count(); ++i) {
  1725. const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
  1726. const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
  1727. const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
  1728. axisValues[i] = axisDefinition.fDefault;
  1729. // The position may be over specified. If there are multiple values for a given axis,
  1730. // use the last one since that's what css-fonts-4 requires.
  1731. for (int j = position.coordinateCount; j --> 0;) {
  1732. const auto& coordinate = position.coordinates[j];
  1733. if (axisDefinition.fTag == coordinate.axis) {
  1734. const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
  1735. if (coordinate.value != axisValue) {
  1736. LOG_INFO("Requested font axis value out of range: "
  1737. "%s '%c%c%c%c' %f; pinned to %f.\n",
  1738. name.c_str(),
  1739. (axisDefinition.fTag >> 24) & 0xFF,
  1740. (axisDefinition.fTag >> 16) & 0xFF,
  1741. (axisDefinition.fTag >> 8) & 0xFF,
  1742. (axisDefinition.fTag ) & 0xFF,
  1743. SkScalarToDouble(coordinate.value),
  1744. SkScalarToDouble(axisValue));
  1745. }
  1746. axisValues[i] = SkScalarToFixed(axisValue);
  1747. break;
  1748. }
  1749. }
  1750. // TODO: warn on defaulted axis?
  1751. }
  1752. SkDEBUGCODE(
  1753. // Check for axis specified, but not matched in font.
  1754. for (int i = 0; i < position.coordinateCount; ++i) {
  1755. SkFourByteTag skTag = position.coordinates[i].axis;
  1756. bool found = false;
  1757. for (int j = 0; j < axisDefinitions.count(); ++j) {
  1758. if (skTag == axisDefinitions[j].fTag) {
  1759. found = true;
  1760. break;
  1761. }
  1762. }
  1763. if (!found) {
  1764. LOG_INFO("Requested font axis not found: %s '%c%c%c%c'\n",
  1765. name.c_str(),
  1766. (skTag >> 24) & 0xFF,
  1767. (skTag >> 16) & 0xFF,
  1768. (skTag >> 8) & 0xFF,
  1769. (skTag) & 0xFF);
  1770. }
  1771. }
  1772. )
  1773. }