blob: 75099f4c8769146e6e3ba9f431e8c0cc925c1710 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
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
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +00008#include "SkAdvancedTypefaceMetrics.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +00009#include "SkBitmap.h"
10#include "SkCanvas.h"
Cary Clarka4083c92017-09-15 11:59:23 -040011#include "SkColorData.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000012#include "SkDescriptor.h"
13#include "SkFDot6.h"
bungeman41868fe2015-05-20 09:21:04 -070014#include "SkFontDescriptor.h"
george@mozilla.comc59b5da2012-08-23 00:39:08 +000015#include "SkFontHost_FreeType_common.h"
bungeman@google.combbe50132012-07-24 20:33:21 +000016#include "SkGlyph.h"
bungeman7cfd46a2016-10-20 16:06:52 -040017#include "SkMakeUnique.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040018#include "SkMalloc.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000019#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000020#include "SkMaskGamma.h"
bungeman@google.comd3fbd342014-04-15 15:52:07 +000021#include "SkMatrix22.h"
mtklein1b249332015-07-07 12:21:21 -070022#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000023#include "SkOTUtils.h"
bungemand3ebb482015-08-05 13:57:49 -070024#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000025#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000026#include "SkStream.h"
27#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000028#include "SkTemplates.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040029#include "SkTo.h"
30
mtklein5f939ab2016-03-16 10:28:35 -070031#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000032
33#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080034#include FT_ADVANCES_H
35#include FT_BITMAP_H
Bruce Wangf3ca1c62018-07-09 10:08:36 -040036#ifdef FT_COLOR_H
37# include FT_COLOR_H
38#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000039#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080040#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080041#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070042#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000043#include FT_OUTLINE_H
44#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080045#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000046#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000047#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000048#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000049
Ben Wagnerfc497342017-02-24 11:15:26 -050050// SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
51// Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
52#define SK_FREETYPE_DLOPEN (0x1)
53#ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
Mike Klein6613cc52017-12-19 09:09:33 -050054# if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (SK_BUILD_FOR_GOOGLE3)
Ben Wagnerfc497342017-02-24 11:15:26 -050055# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
56# else
57# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
58# endif
59#endif
60#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
61# include <dlfcn.h>
62#endif
63
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000064// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
65// were introduced in FreeType 2.5.0.
66// The following may be removed once FreeType 2.5.0 is required to build.
67#ifndef FT_LOAD_COLOR
68# define FT_LOAD_COLOR ( 1L << 20 )
69# define FT_PIXEL_MODE_BGRA 7
70#endif
71
Seigo Nonaka52ab2f52016-12-05 02:41:53 +090072// FT_LOAD_BITMAP_METRICS_ONLY was introduced in FreeType 2.7.1
73// The following may be removed once FreeType 2.7.1 is required to build.
74#ifndef FT_LOAD_BITMAP_METRICS_ONLY
75# define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
76#endif
77
Ben Wagnere346b1e2018-06-26 11:22:37 -040078// FT_VAR_AXIS_FLAG_HIDDEN was introduced in FreeType 2.8.1
79// The variation axis should not be exposed to user interfaces.
80#ifndef FT_VAR_AXIS_FLAG_HIDDEN
81# define FT_VAR_AXIS_FLAG_HIDDEN 1
82#endif
83
reed@android.com8a1c16f2008-12-17 15:59:43 +000084//#define ENABLE_GLYPH_SPEW // for tracing calls
85//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080086//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000087//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000088
Ben Wagner3e45a2f2017-11-01 11:47:39 -040089static bool isLCD(const SkScalerContextRec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080090 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000091}
92
Ben Wagner082a7a72018-06-08 14:15:47 -040093static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
94 return SkFixedToScalar(x);
95}
96
reed@android.com8a1c16f2008-12-17 15:59:43 +000097//////////////////////////////////////////////////////////////////////////
98
bungeman9dc24682014-12-01 14:01:32 -080099extern "C" {
100 static void* sk_ft_alloc(FT_Memory, long size) {
101 return sk_malloc_throw(size);
102 }
103 static void sk_ft_free(FT_Memory, void* block) {
104 sk_free(block);
105 }
106 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
107 return sk_realloc_throw(block, new_size);
108 }
109};
halcanary96fcdcc2015-08-27 07:41:13 -0700110FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -0800111
112class FreeTypeLibrary : SkNoncopyable {
113public:
Ben Wagnerfc497342017-02-24 11:15:26 -0500114 FreeTypeLibrary()
115 : fGetVarDesignCoordinates(nullptr)
Ben Wagnere346b1e2018-06-26 11:22:37 -0400116 , fGetVarAxisFlags(nullptr)
Ben Wagnerfc497342017-02-24 11:15:26 -0500117 , fLibrary(nullptr)
118 , fIsLCDSupported(false)
119 , fLCDExtra(0)
120 {
bungeman9dc24682014-12-01 14:01:32 -0800121 if (FT_New_Library(&gFTMemory, &fLibrary)) {
122 return;
123 }
124 FT_Add_Default_Modules(fLibrary);
125
Ben Wagner2a098d02017-03-01 13:00:53 -0500126 // When using dlsym
127 // *(void**)(&procPtr) = dlsym(self, "proc");
128 // is non-standard, but safe for POSIX. Cannot write
129 // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
130 // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
131
132 FT_Int major, minor, patch;
133 FT_Library_Version(fLibrary, &major, &minor, &patch);
134
Ben Wagnerfc497342017-02-24 11:15:26 -0500135#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
136 fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
137#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
Ben Wagner2a098d02017-03-01 13:00:53 -0500138 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500139 //The FreeType library is already loaded, so symbols are available in process.
140 void* self = dlopen(nullptr, RTLD_LAZY);
141 if (self) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500142 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
143 dlclose(self);
144 }
145 }
146#endif
147
Ben Wagner2a098d02017-03-01 13:00:53 -0500148#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
149 FT_Set_Default_Properties(fLibrary);
150#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
151 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
bungeman9dc24682014-12-01 14:01:32 -0800152 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700153 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800154 if (self) {
Ben Wagner2a098d02017-03-01 13:00:53 -0500155 FT_Set_Default_PropertiesProc setDefaultProperties;
156 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
bungeman9dc24682014-12-01 14:01:32 -0800157 dlclose(self);
158
Ben Wagner2a098d02017-03-01 13:00:53 -0500159 if (setDefaultProperties) {
160 setDefaultProperties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800161 }
162 }
Ben Wagner2a098d02017-03-01 13:00:53 -0500163 }
bungeman9dc24682014-12-01 14:01:32 -0800164#endif
Ben Wagner2a098d02017-03-01 13:00:53 -0500165
Ben Wagnere346b1e2018-06-26 11:22:37 -0400166#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080100
167 fGetVarAxisFlags = FT_Get_Var_Axis_Flags;
168#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
169 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
170 //The FreeType library is already loaded, so symbols are available in process.
171 void* self = dlopen(nullptr, RTLD_LAZY);
172 if (self) {
173 *(void**)(&fGetVarAxisFlags) = dlsym(self, "FT_Get_Var_Axis_Flags");
174 dlclose(self);
175 }
176 }
177#endif
178
Ben Wagner2a098d02017-03-01 13:00:53 -0500179 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
180 // The default has changed over time, so this doesn't mean the same thing to all users.
181 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
182 fIsLCDSupported = true;
183 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
bungeman9dc24682014-12-01 14:01:32 -0800184 }
185 }
186 ~FreeTypeLibrary() {
187 if (fLibrary) {
188 FT_Done_Library(fLibrary);
189 }
190 }
191
192 FT_Library library() { return fLibrary; }
193 bool isLCDSupported() { return fIsLCDSupported; }
194 int lcdExtra() { return fLCDExtra; }
195
Ben Wagnerfc497342017-02-24 11:15:26 -0500196 // 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
Ben Wagnere346b1e2018-06-26 11:22:37 -0400203 // FT_Get_Var_Axis_Flags was introduced in FreeType 2.8.1
204 // Get the ‘flags’ field of an OpenType Variation Axis Record.
205 // Not meaningful for Adobe MM fonts (‘*flags’ is always zero).
206 using FT_Get_Var_Axis_FlagsProc = FT_Error (*)(FT_MM_Var*, FT_UInt, FT_UInt*);
207 FT_Get_Var_Axis_FlagsProc fGetVarAxisFlags;
208
bungeman9dc24682014-12-01 14:01:32 -0800209private:
210 FT_Library fLibrary;
211 bool fIsLCDSupported;
212 int fLCDExtra;
213
214 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
215 // The following platforms provide FreeType of at least 2.4.0.
216 // Ubuntu >= 11.04 (previous deprecated April 2013)
217 // Debian >= 6.0 (good)
218 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
219 // Fedora >= 14 (good)
220 // Android >= Gingerbread (good)
Ben Wagnerfc497342017-02-24 11:15:26 -0500221 // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
222 using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
Ben Wagner2a098d02017-03-01 13:00:53 -0500223
224 // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
225 // of FT_New_Library to request these global properties to be read was added.
226 using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
bungeman9dc24682014-12-01 14:01:32 -0800227};
228
reed@android.com8a1c16f2008-12-17 15:59:43 +0000229struct SkFaceRec;
230
reed086eea92016-05-04 17:12:46 -0700231SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800232static FreeTypeLibrary* gFTLibrary;
233static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000234
bungemanaabd71c2016-03-01 15:15:09 -0800235// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800236static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000237
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000238// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800239static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800240 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800241 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800242
bungeman9dc24682014-12-01 14:01:32 -0800243 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700244 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700245 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000246 }
bungeman9dc24682014-12-01 14:01:32 -0800247 ++gFTCount;
248 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000249}
250
bungeman9dc24682014-12-01 14:01:32 -0800251// Caller must lock gFTMutex before calling this function.
252static void unref_ft_library() {
253 gFTMutex.assertHeld();
254 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000255
bungeman9dc24682014-12-01 14:01:32 -0800256 --gFTCount;
257 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800258 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700259 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700260 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700261 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800262 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000263}
264
Ben Wagnerfc497342017-02-24 11:15:26 -0500265///////////////////////////////////////////////////////////////////////////
266
267struct SkFaceRec {
268 SkFaceRec* fNext;
269 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
270 FT_StreamRec fFTStream;
271 std::unique_ptr<SkStreamAsset> fSkStream;
272 uint32_t fRefCnt;
273 uint32_t fFontID;
274
275 // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
276 // Cache the variation design metrics used to create the font if the user specifies them.
277 SkAutoSTMalloc<4, SkFixed> fAxes;
278 int fAxesCount;
279
280 // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
281 // and named variation index on input, but masks the named variation index part on output.
282 // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
283 bool fNamedVariationSpecified;
284
285 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
286};
287
288extern "C" {
289 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
290 unsigned long offset,
291 unsigned char* buffer,
292 unsigned long count)
293 {
294 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
295
296 if (count) {
297 if (!stream->seek(offset)) {
298 return 0;
299 }
300 count = stream->read(buffer, count);
301 }
302 return count;
303 }
304
305 static void sk_ft_stream_close(FT_Stream) {}
306}
307
308SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
309 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
310 , fAxesCount(0), fNamedVariationSpecified(false)
311{
312 sk_bzero(&fFTStream, sizeof(fFTStream));
313 fFTStream.size = fSkStream->getLength();
314 fFTStream.descriptor.pointer = fSkStream.get();
315 fFTStream.read = sk_ft_stream_io;
316 fFTStream.close = sk_ft_stream_close;
317}
318
319static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
320 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
321 return;
322 }
323
324 // If a named variation is requested, don't overwrite the named variation's position.
325 if (data.getIndex() > 0xFFFF) {
326 rec->fNamedVariationSpecified = true;
327 return;
328 }
329
330 SkDEBUGCODE(
331 FT_MM_Var* variations = nullptr;
332 if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400333 SkDEBUGF("INFO: font %s claims variations, but none found.\n",
334 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500335 return;
336 }
337 SkAutoFree autoFreeVariations(variations);
338
339 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400340 SkDEBUGF("INFO: font %s has %d variations, but %d were specified.\n",
341 rec->fFace->family_name, variations->num_axis, data.getAxisCount());
Ben Wagnerfc497342017-02-24 11:15:26 -0500342 return;
343 }
344 )
345
346 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
347 for (int i = 0; i < data.getAxisCount(); ++i) {
348 coords[i] = data.getAxis()[i];
349 }
350 if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400351 SkDEBUGF("INFO: font %s has variations, but specified variations could not be set.\n",
352 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500353 return;
354 }
355
356 rec->fAxesCount = data.getAxisCount();
357 rec->fAxes.reset(rec->fAxesCount);
358 for (int i = 0; i < rec->fAxesCount; ++i) {
359 rec->fAxes[i] = data.getAxis()[i];
360 }
361}
362
363// Will return nullptr on failure
364// Caller must lock gFTMutex before calling this function.
365static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
366 gFTMutex.assertHeld();
367
368 const SkFontID fontID = typeface->uniqueID();
369 SkFaceRec* cachedRec = gFaceRecHead;
370 while (cachedRec) {
371 if (cachedRec->fFontID == fontID) {
372 SkASSERT(cachedRec->fFace);
373 cachedRec->fRefCnt += 1;
374 return cachedRec;
375 }
376 cachedRec = cachedRec->fNext;
377 }
378
379 std::unique_ptr<SkFontData> data = typeface->makeFontData();
380 if (nullptr == data || !data->hasStream()) {
381 return nullptr;
382 }
383
384 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
385
386 FT_Open_Args args;
387 memset(&args, 0, sizeof(args));
388 const void* memoryBase = rec->fSkStream->getMemoryBase();
389 if (memoryBase) {
390 args.flags = FT_OPEN_MEMORY;
391 args.memory_base = (const FT_Byte*)memoryBase;
392 args.memory_size = rec->fSkStream->getLength();
393 } else {
394 args.flags = FT_OPEN_STREAM;
395 args.stream = &rec->fFTStream;
396 }
397
398 {
399 FT_Face rawFace;
400 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
401 if (err) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500402 SK_TRACEFTR(err, "unable to open font '%x'", fontID);
Ben Wagnerfc497342017-02-24 11:15:26 -0500403 return nullptr;
404 }
405 rec->fFace.reset(rawFace);
406 }
407 SkASSERT(rec->fFace);
408
409 ft_face_setup_axes(rec.get(), *data);
410
411 // FreeType will set the charmap to the "most unicode" cmap if it exists.
412 // If there are no unicode cmaps, the charmap is set to nullptr.
413 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
414 // because they are effectively private use area only (even if they aren't).
415 // This is the last on the fallback list at
416 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
417 if (!rec->fFace->charmap) {
418 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
419 }
420
421 rec->fNext = gFaceRecHead;
422 gFaceRecHead = rec.get();
423 return rec.release();
424}
425
426// Caller must lock gFTMutex before calling this function.
Ben Wagnerf1b61af2017-03-09 15:12:09 -0500427// Marked extern because vc++ does not support internal linkage template parameters.
428extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500429 gFTMutex.assertHeld();
430
431 SkFaceRec* rec = gFaceRecHead;
432 SkFaceRec* prev = nullptr;
433 while (rec) {
434 SkFaceRec* next = rec->fNext;
435 if (rec->fFace == faceRec->fFace) {
436 if (--rec->fRefCnt == 0) {
437 if (prev) {
438 prev->fNext = next;
439 } else {
440 gFaceRecHead = next;
441 }
442 delete rec;
443 }
444 return;
445 }
446 prev = rec;
447 rec = next;
448 }
449 SkDEBUGFAIL("shouldn't get here, face not in list");
450}
451
452class AutoFTAccess {
453public:
454 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
455 gFTMutex.acquire();
Ben Wagner7ca9a742017-08-17 14:05:04 -0400456 SkASSERT_RELEASE(ref_ft_library());
Ben Wagnerfc497342017-02-24 11:15:26 -0500457 fFaceRec = ref_ft_face(tf);
458 }
459
460 ~AutoFTAccess() {
461 if (fFaceRec) {
462 unref_ft_face(fFaceRec);
463 }
464 unref_ft_library();
465 gFTMutex.release();
466 }
467
468 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
469 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
470 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
471 bool isNamedVariationSpecified() {
472 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
473 }
474
475private:
476 SkFaceRec* fFaceRec;
477};
478
479///////////////////////////////////////////////////////////////////////////
480
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000481class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000482public:
bungeman7cfd46a2016-10-20 16:06:52 -0400483 SkScalerContext_FreeType(sk_sp<SkTypeface>,
484 const SkScalerContextEffects&,
485 const SkDescriptor* desc);
Brian Salomond3b65972017-03-22 12:05:03 -0400486 ~SkScalerContext_FreeType() override;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000487
reed@android.com62900b42009-02-11 15:07:19 +0000488 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700489 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000490 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000491
492protected:
mtklein36352bf2015-03-25 18:17:31 -0700493 unsigned generateGlyphCount() override;
494 uint16_t generateCharToGlyph(SkUnichar uni) override;
Ben Wagnere5416452018-08-09 14:03:42 -0400495 bool generateAdvance(SkGlyph* glyph) override;
mtklein36352bf2015-03-25 18:17:31 -0700496 void generateMetrics(SkGlyph* glyph) override;
497 void generateImage(const SkGlyph& glyph) override;
Ben Wagner5ddb3082018-03-29 11:18:06 -0400498 bool generatePath(SkGlyphID glyphID, SkPath* path) override;
mtklein36352bf2015-03-25 18:17:31 -0700499 void generateFontMetrics(SkPaint::FontMetrics*) override;
500 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000501
502private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500503 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
504 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
505
506 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700507 FT_Size fFTSize; // The size on the fFace for this scaler.
508 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000509
bungeman401ae2d2016-07-18 15:46:27 -0700510 /** The rest of the matrix after FreeType handles the size.
511 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
512 * With bitmap only fonts this matrix must be applied to scale the bitmap.
513 */
514 SkMatrix fMatrix22Scalar;
515 /** Same as fMatrix22Scalar, but in FreeType units and space. */
516 FT_Matrix fMatrix22;
517 /** The actual size requested. */
518 SkVector fScale;
519
520 uint32_t fLoadGlyphFlags;
521 bool fDoLinearMetrics;
522 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000523
reed@android.com8a1c16f2008-12-17 15:59:43 +0000524 FT_Error setupSize();
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400525 void getBBoxForCurrentGlyph(const SkGlyph* glyph, FT_BBox* bbox,
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000526 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000527 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000528 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000529 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000530 // Caller must lock gFTMutex before calling this function.
531 // update FreeType2 glyph slot with glyph emboldened
Ben Wagnerc3aef182017-06-26 12:47:33 -0400532 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
bungeman401ae2d2016-07-18 15:46:27 -0700533 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000534};
535
536///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000537
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000538static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000539 FT_UShort fsType = FT_Get_FSType_Flags(face);
540 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
541 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000542}
543
vandebo0f9bad02014-06-19 11:05:39 -0700544static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700545 FT_UShort fsType = FT_Get_FSType_Flags(face);
546 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700547}
548
Hal Canary5bdc4d52018-04-10 11:13:24 -0400549static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
550 const char* fontType = FT_Get_X11_Font_Format(face);
551 static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
552 { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
553 { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
554 { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
555 { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
556 };
557 for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
558 return SkAdvancedTypefaceMetrics::kOther_Font;
559}
560
Hal Canary209e4b12017-05-04 14:23:55 -0400561std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000562 AutoFTAccess fta(this);
563 FT_Face face = fta.face();
564 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700565 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000566 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000567
Hal Canary209e4b12017-05-04 14:23:55 -0400568 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
Hal Canary8031b322018-03-29 13:20:30 -0700569 info->fPostScriptName.set(FT_Get_Postscript_Name(face));
570 info->fFontName = info->fPostScriptName;
halcanary32875882016-08-16 09:36:23 -0700571
vandebo0f9bad02014-06-19 11:05:39 -0700572 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700573 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700574 }
575 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700576 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700577 }
578 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700579 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700580 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000581
Hal Canary5bdc4d52018-04-10 11:13:24 -0400582 info->fType = get_font_type(face);
halcanary32875882016-08-16 09:36:23 -0700583 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700584 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000585 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700586 }
587 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000588 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700589 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000590
bungemanf1491692016-07-22 11:19:24 -0700591 PS_FontInfoRec psFontInfo;
592 TT_Postscript* postTable;
593 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
594 info->fItalicAngle = psFontInfo.italic_angle;
595 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
Ben Wagner4f6fc832017-09-15 16:00:40 -0400596 info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000597 } else {
598 info->fItalicAngle = 0;
599 }
600
601 info->fAscent = face->ascender;
602 info->fDescent = face->descender;
603
bungemanf1491692016-07-22 11:19:24 -0700604 TT_PCLT* pcltTable;
605 TT_OS2* os2Table;
606 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
607 info->fCapHeight = pcltTable->CapHeight;
608 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
609 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000610 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700611 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000612 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700613 }
614 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000615 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700616 os2Table->version != 0xFFFF &&
617 os2Table->version >= 2)
618 {
619 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000620 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000621 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
622 face->bbox.xMax, face->bbox.yMin);
Greg Daniel97c11082018-05-09 15:35:54 +0000623 return info;
Hal Canary1c2bcd82018-04-10 11:27:48 -0400624}
625
Hal Canary46cc3da2018-05-09 11:50:34 -0400626void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
627 SkASSERT(dstArray);
628 AutoFTAccess fta(this);
629 FT_Face face = fta.face();
630 FT_Long numGlyphs = face->num_glyphs;
631 sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
632
633 FT_UInt glyphIndex;
634 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
635 while (glyphIndex) {
636 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
637 // Use the first character that maps to this glyphID. https://crbug.com/359065
638 if (0 == dstArray[glyphIndex]) {
639 dstArray[glyphIndex] = charCode;
640 }
641 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
642 }
643}
644
Hal Canary5bdc4d52018-04-10 11:13:24 -0400645void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
646 SkASSERT(dstArray);
647 AutoFTAccess fta(this);
648 FT_Face face = fta.face();
649 if (face && FT_HAS_GLYPH_NAMES(face)) {
650 for (int gID = 0; gID < face->num_glyphs; gID++) {
651 char glyphName[128]; // PS limit for names is 127 bytes.
652 FT_Get_Glyph_Name(face, gID, glyphName, 128);
653 dstArray[gID] = glyphName;
654 }
655 }
656}
657
reed@google.com618ef5e2011-01-26 22:10:41 +0000658///////////////////////////////////////////////////////////////////////////
659
reed@google.com8ed436c2011-07-21 14:12:36 +0000660static bool bothZero(SkScalar a, SkScalar b) {
661 return 0 == a && 0 == b;
662}
663
664// returns false if there is any non-90-rotation or skew
Ben Wagner3e45a2f2017-11-01 11:47:39 -0400665static bool isAxisAligned(const SkScalerContextRec& rec) {
reed@google.com8ed436c2011-07-21 14:12:36 +0000666 return 0 == rec.fPreSkewX &&
667 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
668 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
669}
670
reeda9322c22016-04-12 06:47:05 -0700671SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
672 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400673 auto c = skstd::make_unique<SkScalerContext_FreeType>(
674 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000675 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400676 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000677 }
bungeman7cfd46a2016-10-20 16:06:52 -0400678 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000679}
680
Bruce Wangebf0cf52018-06-18 14:04:19 -0400681std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(
682 const SkFontArguments& args) const {
683 SkString name;
684 AutoFTAccess fta(this);
685 FT_Face face = fta.face();
686 Scanner::AxisDefinitions axisDefinitions;
687
688 if (!Scanner::GetAxes(face, &axisDefinitions)) {
689 return nullptr;
690 }
691 SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
692 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
693 axisValues, name);
694 int ttcIndex;
695 auto stream = std::unique_ptr<SkStreamAsset>(this->openStream(&ttcIndex));
696 return skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, axisValues.get(),
697 axisDefinitions.count());
698}
699
reed@google.com0da48612013-03-19 16:06:52 +0000700void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000701 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
702 //Cap the requested size as larger sizes give bogus values.
703 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800704 //Note that this also currently only protects against large text size requests,
705 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000706 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000707 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000708 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000709
bungemanec7e12f2015-01-21 11:55:16 -0800710 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800711 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
712 SkAutoMutexAcquire ama(gFTMutex);
713 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800714 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800715 // If the runtime Freetype library doesn't support LCD, disable it here.
716 rec->fMaskFormat = SkMask::kA8_Format;
717 }
718 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000719 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000720
reed@google.com618ef5e2011-01-26 22:10:41 +0000721 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000722 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000723 // collapse full->normal hinting if we're not doing LCD
724 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000725 }
reed@google.com1ac83502012-02-28 17:06:02 +0000726
reed@google.com8ed436c2011-07-21 14:12:36 +0000727 // rotated text looks bad with hinting, so we disable it as needed
728 if (!isAxisAligned(*rec)) {
729 h = SkPaint::kNo_Hinting;
730 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000731 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000732
bungeman@google.com97efada2012-07-30 20:40:50 +0000733#ifndef SK_GAMMA_APPLY_TO_A8
734 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700735 // SRGBTODO: Is this correct? Do we want contrast boost?
736 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000737 }
reed@google.com1ac83502012-02-28 17:06:02 +0000738#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000739}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000740
reed@google.com38c37dd2013-03-21 15:36:26 +0000741int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000742 AutoFTAccess fta(this);
743 FT_Face face = fta.face();
744 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000745}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000746
reed@google.com35fe7372013-10-30 15:07:03 +0000747bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
748 int count, int32_t adjustments[]) const {
749 AutoFTAccess fta(this);
750 FT_Face face = fta.face();
751 if (!face || !FT_HAS_KERNING(face)) {
752 return false;
753 }
754
755 for (int i = 0; i < count - 1; ++i) {
756 FT_Vector delta;
757 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
758 FT_KERNING_UNSCALED, &delta);
759 if (err) {
760 return false;
761 }
762 adjustments[i] = delta.x;
763 }
764 return true;
765}
766
bungeman401ae2d2016-07-18 15:46:27 -0700767/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800768static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700769 if (face == nullptr) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400770 SkDEBUGF("chooseBitmapStrike aborted due to nullptr face.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000771 return -1;
772 }
bungeman401ae2d2016-07-18 15:46:27 -0700773
774 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000775 FT_Int chosenStrikeIndex = -1;
776 FT_Pos chosenPPEM = 0;
777 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700778 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
779 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000780 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700781 return strikeIndex;
782 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000783 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700784 if (chosenPPEM < strikePPEM) {
785 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000786 chosenStrikeIndex = strikeIndex;
787 }
788 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700789 // attempt to decrease chosenPPEM, but not below requestedPPEM
790 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
791 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000792 chosenStrikeIndex = strikeIndex;
793 }
794 }
795 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000796 return chosenStrikeIndex;
797}
798
bungeman7cfd46a2016-10-20 16:06:52 -0400799SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700800 const SkScalerContextEffects& effects,
801 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400802 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800803 , fFace(nullptr)
804 , fFTSize(nullptr)
805 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700806{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000807 SkAutoMutexAcquire ac(gFTMutex);
Ben Wagner7ca9a742017-08-17 14:05:04 -0400808 SkASSERT_RELEASE(ref_ft_library());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000809
Ben Wagnerfc497342017-02-24 11:15:26 -0500810 fFaceRec.reset(ref_ft_face(this->getTypeface()));
811
reed@android.com8a1c16f2008-12-17 15:59:43 +0000812 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500813 if (nullptr == fFaceRec) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400814 SkDEBUGF("Could not create FT_Face.\n");
reed@android.com62900b42009-02-11 15:07:19 +0000815 return;
816 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000817
reed@google.coma1bfa212012-03-08 21:57:12 +0000818 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
819
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820 // compute the flags we send to Load_Glyph
Ben Wagneraa166bd2018-08-14 14:58:18 -0400821 bool linearMetrics = this->isSubpixel();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000823 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000824
agl@chromium.org70a303f2010-05-10 14:15:50 +0000825 if (SkMask::kBW_Format == fRec.fMaskFormat) {
826 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
827 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000828 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000829 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000830 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000831 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000832 } else {
833 switch (fRec.getHinting()) {
834 case SkPaint::kNo_Hinting:
835 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000836 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000837 break;
838 case SkPaint::kSlight_Hinting:
839 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
840 break;
841 case SkPaint::kNormal_Hinting:
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400842 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000843 break;
844 case SkPaint::kFull_Hinting:
845 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000846 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000847 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000848 loadFlags = FT_LOAD_TARGET_LCD_V;
849 } else {
850 loadFlags = FT_LOAD_TARGET_LCD;
851 }
reed@google.comea2333d2011-03-14 16:44:56 +0000852 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000853 break;
854 default:
855 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
856 break;
857 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000858 }
859
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400860 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
861 loadFlags |= FT_LOAD_FORCE_AUTOHINT;
862#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
863 } else {
864 loadFlags |= FT_LOAD_NO_AUTOHINT;
865#endif
866 }
867
reed@google.comeffc5012011-06-27 16:44:46 +0000868 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000869 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000870 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000871
reed@google.com96a9f7912011-05-06 11:49:30 +0000872 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
873 // advances, as fontconfig and cairo do.
874 // See http://code.google.com/p/skia/issues/detail?id=222.
875 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
876
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000877 // Use vertical layout if requested.
Ben Wagneraa166bd2018-08-14 14:58:18 -0400878 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000879 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
880 }
881
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000882 loadFlags |= FT_LOAD_COLOR;
883
reed@android.come4d0bc02009-07-24 19:53:20 +0000884 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000885 }
886
bungemanaabd71c2016-03-01 15:15:09 -0800887 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500888 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800889 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500890 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800891 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500892 SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800893 return nullptr;
894 }
895 return size;
896 }());
897 if (nullptr == ftSize) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400898 SkDEBUGF("Could not create FT_Size.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000899 return;
900 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000901
bungemanaabd71c2016-03-01 15:15:09 -0800902 FT_Error err = FT_Activate_Size(ftSize.get());
903 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500904 SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800905 return;
906 }
907
Ben Wagner082a7a72018-06-08 14:15:47 -0400908 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
909 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
910 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
911
Ben Wagnerfc497342017-02-24 11:15:26 -0500912 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
913 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000914 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500915 SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400916 fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000917 return;
918 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400919
920#ifndef SK_IGNORE_TINY_FREETYPE_SIZE_FIX
921 // Adjust the matrix to reflect the actually chosen scale.
922 // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
923 // Don't do this at all sizes as that will interfere with hinting.
924 if (fScale.fX < 1 || fScale.fY < 1) {
925 SkScalar upem = fFaceRec->fFace->units_per_EM;
926 FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
927 SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
928 SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
929 fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
930 }
931#endif
932
Ben Wagnerfc497342017-02-24 11:15:26 -0500933 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
934 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000935 if (fStrikeIndex == -1) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400936 SkDEBUGF("No glyphs for font \"%s\" size %f.\n",
937 fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700938 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000939 }
bungeman401ae2d2016-07-18 15:46:27 -0700940
Ben Wagnerfc497342017-02-24 11:15:26 -0500941 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700942 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500943 SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400944 fFaceRec->fFace->family_name, fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700945 fStrikeIndex = -1;
946 return;
947 }
948
Ben Wagner082a7a72018-06-08 14:15:47 -0400949 // Adjust the matrix to reflect the actually chosen scale.
950 // It is likely that the ppem chosen was not the one requested, this allows for scaling.
Ben Wagnerfc497342017-02-24 11:15:26 -0500951 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
952 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700953
954 // FreeType does not provide linear metrics for bitmap fonts.
955 linearMetrics = false;
956
957 // FreeType documentation says:
958 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
959 // Bitmap-only fonts ignore this flag.
960 //
961 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
962 // Force this flag off for bitmap only fonts.
963 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000964 } else {
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400965 SkDEBUGF("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700966 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000967 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000968
Ben Wagner082a7a72018-06-08 14:15:47 -0400969 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
970 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
971 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
972 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
973
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400974#ifdef FT_COLOR_H
975 FT_Palette_Select(fFaceRec->fFace.get(), 0, nullptr);
976#endif
977
bungemanaabd71c2016-03-01 15:15:09 -0800978 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500979 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000980 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000981}
982
983SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000984 SkAutoMutexAcquire ac(gFTMutex);
985
halcanary96fcdcc2015-08-27 07:41:13 -0700986 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000987 FT_Done_Size(fFTSize);
988 }
989
Ben Wagnerfc497342017-02-24 11:15:26 -0500990 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -0800991
992 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000993}
994
995/* We call this before each use of the fFace, since we may be sharing
996 this face with other context (at different sizes).
997*/
998FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800999 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001000 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001001 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001002 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001003 }
halcanary96fcdcc2015-08-27 07:41:13 -07001004 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001005 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006}
1007
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001008unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001009 return fFace->num_glyphs;
1010}
1011
1012uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -08001013 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001014 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1015}
1016
reed@android.com9d3a9852010-01-08 14:07:42 +00001017SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -08001018 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +00001019 // iterate through each cmap entry, looking for matching glyph indices
1020 FT_UInt glyphIndex;
1021 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1022
1023 while (glyphIndex != 0) {
1024 if (glyphIndex == glyph) {
1025 return charCode;
1026 }
1027 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1028 }
1029
1030 return 0;
1031}
1032
Ben Wagnere5416452018-08-09 14:03:42 -04001033bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001034 /* unhinted and light hinted text have linearly scaled advances
1035 * which are very cheap to compute with some font formats...
1036 */
Ben Wagnere5416452018-08-09 14:03:42 -04001037 if (!fDoLinearMetrics) {
1038 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001039 }
bungeman5ec443c2014-11-21 13:18:34 -08001040
Ben Wagnere5416452018-08-09 14:03:42 -04001041 SkAutoMutexAcquire ac(gFTMutex);
1042
1043 if (this->setupSize()) {
1044 glyph->zeroMetrics();
1045 return true;
1046 }
1047
1048 FT_Error error;
1049 FT_Fixed advance;
1050
1051 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
1052 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1053 &advance );
1054
1055 if (error != 0) {
1056 return false;
1057 }
1058
1059 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1060 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1061 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1062 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001063}
1064
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001065void SkScalerContext_FreeType::getBBoxForCurrentGlyph(const SkGlyph* glyph,
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001066 FT_BBox* bbox,
1067 bool snapToPixelBoundary) {
1068
1069 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1070
Ben Wagneraa166bd2018-08-14 14:58:18 -04001071 if (this->isSubpixel()) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001072 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1073 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001074 // negate dy since freetype-y-goes-up and skia-y-goes-down
1075 bbox->xMin += dx;
1076 bbox->yMin -= dy;
1077 bbox->xMax += dx;
1078 bbox->yMax -= dy;
1079 }
1080
1081 // outset the box to integral boundaries
1082 if (snapToPixelBoundary) {
1083 bbox->xMin &= ~63;
1084 bbox->yMin &= ~63;
1085 bbox->xMax = (bbox->xMax + 63) & ~63;
1086 bbox->yMax = (bbox->yMax + 63) & ~63;
1087 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001088
1089 // Must come after snapToPixelBoundary so that the width and height are
1090 // consistent. Otherwise asserts will fire later on when generating the
1091 // glyph image.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001092 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001093 FT_Vector vector;
1094 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1095 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1096 FT_Vector_Transform(&vector, &fMatrix22);
1097 bbox->xMin += vector.x;
1098 bbox->xMax += vector.x;
1099 bbox->yMin += vector.y;
1100 bbox->yMax += vector.y;
1101 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001102}
1103
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001104bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1105 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001106 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001107 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001108 }
1109 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001110 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001111 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001112 emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001113 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1114 return true;
1115}
1116
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001117void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
Ben Wagnere5416452018-08-09 14:03:42 -04001118 if (glyph->fMaskFormat == SkMask::kLCD16_Format) {
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001119 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001120 glyph->fHeight += gFTLibrary->lcdExtra();
1121 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001122 } else {
bungeman9dc24682014-12-01 14:01:32 -08001123 glyph->fWidth += gFTLibrary->lcdExtra();
1124 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001125 }
1126 }
1127}
1128
bungeman401ae2d2016-07-18 15:46:27 -07001129bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1130 // If subpixel rendering of a bitmap *can* be done.
1131 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
Ben Wagneraa166bd2018-08-14 14:58:18 -04001132 this->isSubpixel() &&
bungeman401ae2d2016-07-18 15:46:27 -07001133 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001134
bungeman401ae2d2016-07-18 15:46:27 -07001135 // If subpixel rendering of a bitmap *should* be done.
1136 // 1. If the face is not scalable then always allow subpixel rendering.
1137 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1138 // 2. If the matrix is already not identity the bitmap will already be resampled,
1139 // so resampling slightly differently shouldn't make much difference.
1140 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1141
1142 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001143}
1144
reed@android.com8a1c16f2008-12-17 15:59:43 +00001145void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1146 SkAutoMutexAcquire ac(gFTMutex);
1147
Ben Wagnere5416452018-08-09 14:03:42 -04001148 glyph->fMaskFormat = fRec.fMaskFormat;
1149
reed@android.com8a1c16f2008-12-17 15:59:43 +00001150 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001151 glyph->zeroMetrics();
1152 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001153 }
1154
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001155 FT_Error err;
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001156 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1157 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001158 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001159 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001160 return;
1161 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001162 emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001163
1164 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001165 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001166 if (0 == fFace->glyph->outline.n_contours) {
1167 glyph->fWidth = 0;
1168 glyph->fHeight = 0;
1169 glyph->fTop = 0;
1170 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001171 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001172 FT_BBox bbox;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001173
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001174#ifdef FT_COLOR_H
1175 SkRect bounds = SkRect::MakeEmpty();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001176
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001177 FT_LayerIterator layerIterator;
1178 layerIterator.p = NULL;
1179 FT_Bool haveLayers = false;
1180 FT_UInt layerGlyphIndex;
1181 FT_UInt layerColorIndex;
1182 while (FT_Get_Color_Glyph_Layer(fFace,
1183 glyph->getGlyphID(),
1184 &layerGlyphIndex,
1185 &layerColorIndex,
1186 &layerIterator)) {
1187 haveLayers = true;
1188 err = FT_Load_Glyph(fFace, layerGlyphIndex,
1189 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
1190 if (err != 0) {
1191 glyph->zeroMetrics();
1192 return;
1193 }
1194 emboldenIfNeeded(fFace, fFace->glyph, layerGlyphIndex);
1195
1196 if (0 < fFace->glyph->outline.n_contours) {
1197 getBBoxForCurrentGlyph(glyph, &bbox, true);
1198
1199 SkRect layerBounds = SkRect::MakeLTRB(SkFDot6ToScalar(bbox.xMin),
1200 SkFDot6ToScalar(-bbox.yMax),
1201 SkFDot6ToScalar(bbox.xMax),
1202 SkFDot6ToScalar(-bbox.yMin)
1203 );
1204
1205 bounds.join(layerBounds);
1206 }
1207 }
1208
1209 if (haveLayers) {
1210 glyph->fMaskFormat = SkMask::kARGB32_Format;
1211
1212 SkIRect ibounds = bounds.roundOut();
1213 glyph->fWidth = SkToU16(ibounds.width());
1214 glyph->fHeight = SkToU16(ibounds.height());
1215 glyph->fTop = SkToS16(ibounds.top());
1216 glyph->fLeft = SkToS16(ibounds.left());
1217 } else {
1218#endif
1219 getBBoxForCurrentGlyph(glyph, &bbox, true);
1220
1221 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1222 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1223 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1224 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1225#ifdef FT_COLOR_H
1226 }
1227#endif
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001228 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001229 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001230 break;
1231
1232 case FT_GLYPH_FORMAT_BITMAP:
Ben Wagneraa166bd2018-08-14 14:58:18 -04001233 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001234 FT_Vector vector;
1235 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1236 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1237 FT_Vector_Transform(&vector, &fMatrix22);
1238 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1239 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1240 }
1241
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001242 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1243 glyph->fMaskFormat = SkMask::kARGB32_Format;
1244 }
1245
bungeman401ae2d2016-07-18 15:46:27 -07001246 {
1247 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1248 -SkIntToScalar(fFace->glyph->bitmap_top),
1249 SkIntToScalar(fFace->glyph->bitmap.width),
1250 SkIntToScalar(fFace->glyph->bitmap.rows));
1251 fMatrix22Scalar.mapRect(&rect);
1252 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1253 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1254 SkFixedToScalar(glyph->getSubYFixed()));
1255 }
1256 SkIRect irect = rect.roundOut();
1257 glyph->fWidth = SkToU16(irect.width());
1258 glyph->fHeight = SkToU16(irect.height());
1259 glyph->fTop = SkToS16(irect.top());
1260 glyph->fLeft = SkToS16(irect.left());
1261 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001262 break;
1263
1264 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001265 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001266 glyph->zeroMetrics();
1267 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001268 }
1269
Ben Wagneraa166bd2018-08-14 14:58:18 -04001270 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001271 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001272 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001273 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001274 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001275 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001276 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1277 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001278 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001279 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001280 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001281 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1282 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001283 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001284 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001285 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1286 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001287 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001288 }
1289
reed@android.com8a1c16f2008-12-17 15:59:43 +00001290#ifdef ENABLE_GLYPH_SPEW
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001291 SkDEBUGF("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001292#endif
1293}
1294
bungeman5ec443c2014-11-21 13:18:34 -08001295static void clear_glyph_image(const SkGlyph& glyph) {
1296 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1297}
reed@google.comea2333d2011-03-14 16:44:56 +00001298
bungeman@google.coma76de722012-10-26 19:35:54 +00001299void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001300 SkAutoMutexAcquire ac(gFTMutex);
1301
reed@android.com8a1c16f2008-12-17 15:59:43 +00001302 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001303 clear_glyph_image(glyph);
1304 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001305 }
1306
bungeman5ec443c2014-11-21 13:18:34 -08001307 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001308 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -05001309 SK_TRACEFTR(err, "SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d "
1310 "width:%d height:%d rb:%d flags:%d) failed.",
1311 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(),
1312 fLoadGlyphFlags);
bungeman5ec443c2014-11-21 13:18:34 -08001313 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314 return;
1315 }
1316
Ben Wagnerc3aef182017-06-26 12:47:33 -04001317 emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
bungeman401ae2d2016-07-18 15:46:27 -07001318 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1319 SkMatrix subpixelBitmapMatrix;
1320 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1321 subpixelBitmapMatrix = fMatrix22Scalar;
1322 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1323 SkFixedToScalar(glyph.getSubYFixed()));
1324 bitmapMatrix = &subpixelBitmapMatrix;
1325 }
1326 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001327}
1328
reed@android.com8a1c16f2008-12-17 15:59:43 +00001329
Ben Wagner5ddb3082018-03-29 11:18:06 -04001330bool SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
caryclarka10742c2014-09-18 11:00:40 -07001331 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001332
Ben Wagner5ddb3082018-03-29 11:18:06 -04001333 SkAutoMutexAcquire ac(gFTMutex);
1334
reed@android.com8a1c16f2008-12-17 15:59:43 +00001335 if (this->setupSize()) {
1336 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001337 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001338 }
1339
1340 uint32_t flags = fLoadGlyphFlags;
1341 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1342 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1343
Ben Wagner6e9ac122016-11-11 14:31:06 -05001344 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001345 if (err != 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001346 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001347 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001348 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001349 emboldenIfNeeded(fFace, fFace->glyph, glyphID);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001350
Ben Wagner5ddb3082018-03-29 11:18:06 -04001351 if (!generateGlyphPath(fFace, path)) {
1352 path->reset();
1353 return false;
1354 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001355
1356 // The path's origin from FreeType is always the horizontal layout origin.
1357 // Offset the path so that it is relative to the vertical origin if needed.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001358 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001359 FT_Vector vector;
1360 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1361 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1362 FT_Vector_Transform(&vector, &fMatrix22);
1363 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1364 }
Ben Wagner5ddb3082018-03-29 11:18:06 -04001365 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001366}
1367
bungeman41078062014-07-07 08:16:37 -07001368void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001369 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001370 return;
1371 }
1372
bungeman41078062014-07-07 08:16:37 -07001373 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001374
1375 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001376 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377 return;
1378 }
1379
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001380 FT_Face face = fFace;
Ben Wagner219f3622017-07-17 15:32:25 -04001381 metrics->fFlags = 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001382
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001383 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1384 SkScalar upem = SkIntToScalar(face->units_per_EM);
1385 if (!upem) {
1386 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1387 if (ttHeader) {
1388 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001389 }
1390 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001391
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001392 // use the os/2 table as a source of reasonable defaults.
1393 SkScalar x_height = 0.0f;
1394 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001395 SkScalar cap_height = 0.0f;
Kevin Lubick42846132018-01-05 10:11:11 -05001396 SkScalar strikeoutThickness = 0.0f, strikeoutPosition = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001397 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1398 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001399 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001400 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
Ben Wagner219f3622017-07-17 15:32:25 -04001401 strikeoutThickness = SkIntToScalar(os2->yStrikeoutSize) / upem;
1402 strikeoutPosition = -SkIntToScalar(os2->yStrikeoutPosition) / upem;
1403 metrics->fFlags |= SkPaint::FontMetrics::kStrikeoutThicknessIsValid_Flag;
1404 metrics->fFlags |= SkPaint::FontMetrics::kStrikeoutPositionIsValid_Flag;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001405 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001406 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001407 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001408 }
1409
1410 // pull from format-specific metrics as needed
1411 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001412 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001413 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001414 // FreeType will always use HHEA metrics if they're not zero.
1415 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1416 // It also ignores the VDMX tables, which are also of interest here
1417 // (and override everything else when they apply).
1418 static const int kUseTypoMetricsMask = (1 << 7);
1419 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1420 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1421 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1422 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1423 } else {
1424 ascent = -SkIntToScalar(face->ascender) / upem;
1425 descent = -SkIntToScalar(face->descender) / upem;
1426 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1427 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001428 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1429 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1430 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1431 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001432 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001433 underlinePosition = -SkIntToScalar(face->underline_position +
1434 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001435
Ben Wagner3318da52017-03-23 14:01:22 -04001436 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThicknessIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001437 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1438
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001439 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001440 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001441 FT_BBox bbox;
1442 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001443 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1444 }
1445 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001446 if (!cap_height) {
1447 FT_BBox bbox;
1448 if (getCBoxForLetter('H', &bbox)) {
1449 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1450 }
1451 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001452 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1453 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1454 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1455 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1456 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001457 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001458 xmin = 0.0f;
1459 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001460 ymin = descent;
1461 ymax = ascent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001462 underlineThickness = 0;
1463 underlinePosition = 0;
Ben Wagner3318da52017-03-23 14:01:22 -04001464 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThicknessIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001465 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001466
1467 TT_Postscript* post = (TT_Postscript*) FT_Get_Sfnt_Table(face, ft_sfnt_post);
1468 if (post) {
1469 underlineThickness = SkIntToScalar(post->underlineThickness) / upem;
1470 underlinePosition = -SkIntToScalar(post->underlinePosition) / upem;
1471 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThicknessIsValid_Flag;
1472 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1473 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001474 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001475 sk_bzero(metrics, sizeof(*metrics));
1476 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001477 }
1478
1479 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1480 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001481 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001482 }
1483 if (!avgCharWidth) {
1484 avgCharWidth = xmax - xmin;
1485 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001486 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001487 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001488 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001489
1490 // disallow negative linespacing
1491 if (leading < 0.0f) {
1492 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001493 }
1494
bungeman53790512016-07-21 13:32:09 -07001495 metrics->fTop = ymax * fScale.y();
1496 metrics->fAscent = ascent * fScale.y();
1497 metrics->fDescent = descent * fScale.y();
1498 metrics->fBottom = ymin * fScale.y();
1499 metrics->fLeading = leading * fScale.y();
1500 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1501 metrics->fXMin = xmin * fScale.y();
1502 metrics->fXMax = xmax * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001503 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
bungeman7316b102014-10-29 12:46:52 -07001504 metrics->fXHeight = x_height;
1505 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001506 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1507 metrics->fUnderlinePosition = underlinePosition * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001508 metrics->fStrikeoutThickness = strikeoutThickness * fScale.y();
1509 metrics->fStrikeoutPosition = strikeoutPosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001510}
1511
djsollenfcfea992015-01-09 08:18:13 -08001512///////////////////////////////////////////////////////////////////////////////
1513
1514// hand-tuned value to reduce outline embolden strength
1515#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1516 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1517 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1518 #else
1519 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1520 #endif
1521#endif
1522
1523///////////////////////////////////////////////////////////////////////////////
1524
Ben Wagnerc3aef182017-06-26 12:47:33 -04001525void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid) {
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001526 // check to see if the embolden bit is set
1527 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1528 return;
1529 }
1530
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001531 switch (glyph->format) {
1532 case FT_GLYPH_FORMAT_OUTLINE:
1533 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001534 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1535 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001536 FT_Outline_Embolden(&glyph->outline, strength);
1537 break;
1538 case FT_GLYPH_FORMAT_BITMAP:
Ben Wagnerc3aef182017-06-26 12:47:33 -04001539 if (!fFace->glyph->bitmap.buffer) {
1540 FT_Load_Glyph(fFace, gid, fLoadGlyphFlags);
1541 }
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001542 FT_GlyphSlot_Own_Bitmap(glyph);
1543 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1544 break;
1545 default:
1546 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001547 }
1548}
1549
reed@google.comb4162b12013-07-02 16:32:29 +00001550///////////////////////////////////////////////////////////////////////////////
1551
1552#include "SkUtils.h"
1553
1554static SkUnichar next_utf8(const void** chars) {
1555 return SkUTF8_NextUnichar((const char**)chars);
1556}
1557
1558static SkUnichar next_utf16(const void** chars) {
1559 return SkUTF16_NextUnichar((const uint16_t**)chars);
1560}
1561
1562static SkUnichar next_utf32(const void** chars) {
1563 const SkUnichar** uniChars = (const SkUnichar**)chars;
1564 SkUnichar uni = **uniChars;
1565 *uniChars += 1;
1566 return uni;
1567}
1568
1569typedef SkUnichar (*EncodingProc)(const void**);
1570
1571static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1572 static const EncodingProc gProcs[] = {
1573 next_utf8, next_utf16, next_utf32
1574 };
1575 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1576 return gProcs[enc];
1577}
1578
1579int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001580 uint16_t glyphs[], int glyphCount) const
1581{
reed@google.comb4162b12013-07-02 16:32:29 +00001582 AutoFTAccess fta(this);
1583 FT_Face face = fta.face();
1584 if (!face) {
1585 if (glyphs) {
1586 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1587 }
1588 return 0;
1589 }
1590
1591 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1592
halcanary96fcdcc2015-08-27 07:41:13 -07001593 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001594 for (int i = 0; i < glyphCount; ++i) {
1595 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1596 return i;
1597 }
1598 }
1599 return glyphCount;
1600 } else {
1601 int first = glyphCount;
1602 for (int i = 0; i < glyphCount; ++i) {
1603 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1604 glyphs[i] = SkToU16(id);
1605 if (0 == id && i < first) {
1606 first = i;
1607 }
1608 }
1609 return first;
1610 }
1611}
1612
1613int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001614 AutoFTAccess fta(this);
1615 FT_Face face = fta.face();
1616 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001617}
1618
bungeman@google.com839702b2013-08-07 17:09:22 +00001619SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
Ben Wagnerad031f52018-08-20 13:45:57 -04001620 sk_sp<SkTypeface::LocalizedStrings> nameIter =
1621 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
1622 if (!nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001623 SkString familyName;
1624 this->getFamilyName(&familyName);
1625 SkString language("und"); //undetermined
Ben Wagnerad031f52018-08-20 13:45:57 -04001626 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
bungeman@google.coma9802692013-08-07 02:45:25 +00001627 }
Ben Wagnerad031f52018-08-20 13:45:57 -04001628 return nameIter.release();
bungeman@google.coma9802692013-08-07 02:45:25 +00001629}
1630
Ben Wagnerfc497342017-02-24 11:15:26 -05001631int SkTypeface_FreeType::onGetVariationDesignPosition(
Ben Wagnere346b1e2018-06-26 11:22:37 -04001632 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
Ben Wagnerfc497342017-02-24 11:15:26 -05001633{
1634 AutoFTAccess fta(this);
1635 FT_Face face = fta.face();
Ben Wagnere346b1e2018-06-26 11:22:37 -04001636 if (!face) {
1637 return -1;
1638 }
Ben Wagnerfc497342017-02-24 11:15:26 -05001639
Ben Wagnere346b1e2018-06-26 11:22:37 -04001640 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001641 return 0;
1642 }
1643
1644 FT_MM_Var* variations = nullptr;
1645 if (FT_Get_MM_Var(face, &variations)) {
Ben Wagnere346b1e2018-06-26 11:22:37 -04001646 return -1;
Ben Wagnerfc497342017-02-24 11:15:26 -05001647 }
1648 SkAutoFree autoFreeVariations(variations);
1649
1650 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1651 return variations->num_axis;
1652 }
1653
1654 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1655 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1656 if (gFTLibrary->fGetVarDesignCoordinates &&
1657 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1658 {
1659 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1660 coordinates[i].axis = variations->axis[i].tag;
1661 coordinates[i].value = SkFixedToScalar(coords[i]);
1662 }
1663 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1664 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1665 coordinates[i].axis = variations->axis[i].tag;
1666 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1667 }
1668 } else if (fta.isNamedVariationSpecified()) {
1669 // The font has axes, they cannot be retrieved, and some named axis was specified.
1670 return -1;
1671 } else {
1672 // The font has axes, they cannot be retrieved, but no named instance was specified.
1673 return 0;
1674 }
1675
1676 return variations->num_axis;
1677}
1678
Ben Wagnere346b1e2018-06-26 11:22:37 -04001679int SkTypeface_FreeType::onGetVariationDesignParameters(
1680 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
1681{
1682 AutoFTAccess fta(this);
1683 FT_Face face = fta.face();
1684 if (!face) {
1685 return -1;
1686 }
1687
1688 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1689 return 0;
1690 }
1691
1692 FT_MM_Var* variations = nullptr;
1693 if (FT_Get_MM_Var(face, &variations)) {
1694 return -1;
1695 }
1696 SkAutoFree autoFreeVariations(variations);
1697
1698 if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
1699 return variations->num_axis;
1700 }
1701
1702 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1703 parameters[i].tag = variations->axis[i].tag;
1704 parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
1705 parameters[i].def = SkFixedToScalar(variations->axis[i].def);
1706 parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
1707 FT_UInt flags = 0;
1708 bool hidden = gFTLibrary->fGetVarAxisFlags &&
1709 !gFTLibrary->fGetVarAxisFlags(variations, i, &flags) &&
1710 (flags & FT_VAR_AXIS_FLAG_HIDDEN);
1711 parameters[i].setHidden(hidden);
1712 }
1713
1714 return variations->num_axis;
1715}
1716
bungeman@google.comddc218e2013-08-01 22:29:43 +00001717int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1718 AutoFTAccess fta(this);
1719 FT_Face face = fta.face();
1720
1721 FT_ULong tableCount = 0;
1722 FT_Error error;
1723
halcanary96fcdcc2015-08-27 07:41:13 -07001724 // When 'tag' is nullptr, returns number of tables in 'length'.
1725 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001726 if (error) {
1727 return 0;
1728 }
1729
1730 if (tags) {
1731 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1732 FT_ULong tableTag;
1733 FT_ULong tablelength;
1734 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1735 if (error) {
1736 return 0;
1737 }
1738 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1739 }
1740 }
1741 return tableCount;
1742}
1743
1744size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1745 size_t length, void* data) const
1746{
1747 AutoFTAccess fta(this);
1748 FT_Face face = fta.face();
1749
1750 FT_ULong tableLength = 0;
1751 FT_Error error;
1752
1753 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001754 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001755 if (error) {
1756 return 0;
1757 }
1758
1759 if (offset > tableLength) {
1760 return 0;
1761 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001762 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001763 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001764 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1765 if (error) {
1766 return 0;
1767 }
1768 }
1769
1770 return size;
1771}
1772
reed@google.comb4162b12013-07-02 16:32:29 +00001773///////////////////////////////////////////////////////////////////////////////
1774///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001775
halcanary96fcdcc2015-08-27 07:41:13 -07001776SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001777 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1778 return;
bungeman14df8332014-10-28 15:07:23 -07001779 }
bungeman9dc24682014-12-01 14:01:32 -08001780 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001781}
1782SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001783 if (fLibrary) {
1784 FT_Done_Library(fLibrary);
1785 }
bungeman14df8332014-10-28 15:07:23 -07001786}
1787
bungemanf93d7112016-09-16 06:24:20 -07001788FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001789 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001790{
halcanary96fcdcc2015-08-27 07:41:13 -07001791 if (fLibrary == nullptr) {
1792 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001793 }
1794
bungeman14df8332014-10-28 15:07:23 -07001795 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001796 memset(&args, 0, sizeof(args));
1797
1798 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001799
bsalomon49f085d2014-09-05 13:34:00 -07001800 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001801 args.flags = FT_OPEN_MEMORY;
1802 args.memory_base = (const FT_Byte*)memoryBase;
1803 args.memory_size = stream->getLength();
1804 } else {
bungeman14df8332014-10-28 15:07:23 -07001805 memset(ftStream, 0, sizeof(*ftStream));
1806 ftStream->size = stream->getLength();
1807 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001808 ftStream->read = sk_ft_stream_io;
1809 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001810
1811 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001812 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001813 }
1814
1815 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001816 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001817 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001818 }
1819 return face;
1820}
1821
bungemanf93d7112016-09-16 06:24:20 -07001822bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001823 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1824
1825 FT_StreamRec streamRec;
1826 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001827 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001828 return false;
1829 }
1830
1831 *numFaces = face->num_faces;
1832
1833 FT_Done_Face(face);
1834 return true;
1835}
1836
1837#include "SkTSearch.h"
1838bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001839 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001840 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001841{
1842 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1843
1844 FT_StreamRec streamRec;
1845 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001846 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001847 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001848 }
1849
bungemana4c4a2d2014-10-20 13:33:19 -07001850 int weight = SkFontStyle::kNormal_Weight;
1851 int width = SkFontStyle::kNormal_Width;
1852 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001853 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001854 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001855 }
1856 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001857 slant = SkFontStyle::kItalic_Slant;
1858 }
1859
1860 PS_FontInfoRec psFontInfo;
1861 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1862 if (os2 && os2->version != 0xffff) {
1863 weight = os2->usWeightClass;
1864 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001865
1866 // OS/2::fsSelection bit 9 indicates oblique.
1867 if (SkToBool(os2->fsSelection & (1u << 9))) {
1868 slant = SkFontStyle::kOblique_Slant;
1869 }
bungemana4c4a2d2014-10-20 13:33:19 -07001870 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1871 static const struct {
1872 char const * const name;
1873 int const weight;
1874 } commonWeights [] = {
1875 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001876 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001877 { "black", SkFontStyle::kBlack_Weight },
1878 { "bold", SkFontStyle::kBold_Weight },
1879 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1880 { "demi", SkFontStyle::kSemiBold_Weight },
1881 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001882 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001883 { "extrabold", SkFontStyle::kExtraBold_Weight },
1884 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001885 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001886 { "heavy", SkFontStyle::kBlack_Weight },
1887 { "light", SkFontStyle::kLight_Weight },
1888 { "medium", SkFontStyle::kMedium_Weight },
1889 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001890 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001891 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001892 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001893 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001894 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001895 { "thin", SkFontStyle::kThin_Weight },
1896 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001897 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001898 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001899 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001900 { "ultralight", SkFontStyle::kExtraLight_Weight },
1901 };
1902 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001903 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001904 if (index >= 0) {
1905 weight = commonWeights[index].weight;
1906 } else {
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001907 SkDEBUGF("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
bungemana4c4a2d2014-10-20 13:33:19 -07001908 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001909 }
1910
1911 if (name) {
1912 name->set(face->family_name);
1913 }
1914 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001915 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001916 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001917 if (isFixedPitch) {
1918 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001919 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001920
Bruce Wangebf0cf52018-06-18 14:04:19 -04001921 bool success = GetAxes(face, axes);
1922 FT_Done_Face(face);
1923 return success;
1924}
1925
1926bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
bungeman41868fe2015-05-20 09:21:04 -07001927 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001928 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001929 FT_Error err = FT_Get_MM_Var(face, &variations);
1930 if (err) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001931 SkDEBUGF("INFO: font %s claims to have variations, but none found.\n",
1932 face->family_name);
bungeman41868fe2015-05-20 09:21:04 -07001933 return false;
1934 }
1935 SkAutoFree autoFreeVariations(variations);
1936
1937 axes->reset(variations->num_axis);
1938 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1939 const FT_Var_Axis& ftAxis = variations->axis[i];
1940 (*axes)[i].fTag = ftAxis.tag;
1941 (*axes)[i].fMinimum = ftAxis.minimum;
1942 (*axes)[i].fDefault = ftAxis.def;
1943 (*axes)[i].fMaximum = ftAxis.maximum;
1944 }
1945 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001946 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001947}
bungemanf6c71072016-01-21 14:17:47 -08001948
1949/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1950 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001951 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001952 SkFixed* axisValues,
1953 const SkString& name)
1954{
1955 for (int i = 0; i < axisDefinitions.count(); ++i) {
1956 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001957 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1958 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001959 axisValues[i] = axisDefinition.fDefault;
bungeman9aec8942017-03-29 13:38:53 -04001960 // The position may be over specified. If there are multiple values for a given axis,
1961 // use the last one since that's what css-fonts-4 requires.
1962 for (int j = position.coordinateCount; j --> 0;) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001963 const auto& coordinate = position.coordinates[j];
1964 if (axisDefinition.fTag == coordinate.axis) {
1965 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1966 if (coordinate.value != axisValue) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001967 SkDEBUGF("Requested font axis value out of range: "
1968 "%s '%c%c%c%c' %f; pinned to %f.\n",
1969 name.c_str(),
1970 (axisDefinition.fTag >> 24) & 0xFF,
1971 (axisDefinition.fTag >> 16) & 0xFF,
1972 (axisDefinition.fTag >> 8) & 0xFF,
1973 (axisDefinition.fTag ) & 0xFF,
1974 SkScalarToDouble(coordinate.value),
1975 SkScalarToDouble(axisValue));
bungemanf6c71072016-01-21 14:17:47 -08001976 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001977 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001978 break;
1979 }
1980 }
1981 // TODO: warn on defaulted axis?
1982 }
1983
1984 SkDEBUGCODE(
1985 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001986 for (int i = 0; i < position.coordinateCount; ++i) {
1987 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001988 bool found = false;
1989 for (int j = 0; j < axisDefinitions.count(); ++j) {
1990 if (skTag == axisDefinitions[j].fTag) {
1991 found = true;
1992 break;
1993 }
1994 }
1995 if (!found) {
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001996 SkDEBUGF("Requested font axis not found: %s '%c%c%c%c'\n",
1997 name.c_str(),
1998 (skTag >> 24) & 0xFF,
1999 (skTag >> 16) & 0xFF,
2000 (skTag >> 8) & 0xFF,
2001 (skTag) & 0xFF);
bungemanf6c71072016-01-21 14:17:47 -08002002 }
2003 }
2004 )
2005}