blob: 8d8b45a541c96796d83126ec58ff0832f81258dc [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/core/SkBitmap.h"
9#include "include/core/SkCanvas.h"
10#include "include/core/SkFontMetrics.h"
11#include "include/core/SkPath.h"
12#include "include/core/SkStream.h"
13#include "include/core/SkString.h"
14#include "include/private/SkColorData.h"
15#include "include/private/SkMalloc.h"
16#include "include/private/SkMutex.h"
17#include "include/private/SkTemplates.h"
18#include "include/private/SkTo.h"
19#include "src/core/SkAdvancedTypefaceMetrics.h"
20#include "src/core/SkDescriptor.h"
21#include "src/core/SkFDot6.h"
22#include "src/core/SkFontDescriptor.h"
23#include "src/core/SkGlyph.h"
24#include "src/core/SkMakeUnique.h"
25#include "src/core/SkMask.h"
26#include "src/core/SkMaskGamma.h"
27#include "src/core/SkScalerContext.h"
28#include "src/ports/SkFontHost_FreeType_common.h"
29#include "src/sfnt/SkOTUtils.h"
30#include "src/utils/SkCallableTraits.h"
31#include "src/utils/SkMatrix22.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040032
mtklein5f939ab2016-03-16 10:28:35 -070033#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000034
35#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080036#include FT_ADVANCES_H
37#include FT_BITMAP_H
Bruce Wangf3ca1c62018-07-09 10:08:36 -040038#ifdef FT_COLOR_H
39# include FT_COLOR_H
40#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000041#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080042#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080043#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070044#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000045#include FT_OUTLINE_H
46#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080047#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000048#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000049#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000050#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000051
Ben Wagnerfc497342017-02-24 11:15:26 -050052// SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
53// Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
54#define SK_FREETYPE_DLOPEN (0x1)
55#ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
Mike Klein6613cc52017-12-19 09:09:33 -050056# if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (SK_BUILD_FOR_GOOGLE3)
Ben Wagnerfc497342017-02-24 11:15:26 -050057# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
58# else
59# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
60# endif
61#endif
62#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
63# include <dlfcn.h>
64#endif
65
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000066// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
67// were introduced in FreeType 2.5.0.
68// The following may be removed once FreeType 2.5.0 is required to build.
69#ifndef FT_LOAD_COLOR
70# define FT_LOAD_COLOR ( 1L << 20 )
71# define FT_PIXEL_MODE_BGRA 7
72#endif
73
Seigo Nonaka52ab2f52016-12-05 02:41:53 +090074// FT_LOAD_BITMAP_METRICS_ONLY was introduced in FreeType 2.7.1
75// The following may be removed once FreeType 2.7.1 is required to build.
76#ifndef FT_LOAD_BITMAP_METRICS_ONLY
77# define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
78#endif
79
Ben Wagnere346b1e2018-06-26 11:22:37 -040080// FT_VAR_AXIS_FLAG_HIDDEN was introduced in FreeType 2.8.1
81// The variation axis should not be exposed to user interfaces.
82#ifndef FT_VAR_AXIS_FLAG_HIDDEN
83# define FT_VAR_AXIS_FLAG_HIDDEN 1
84#endif
85
reed@android.com8a1c16f2008-12-17 15:59:43 +000086//#define ENABLE_GLYPH_SPEW // for tracing calls
87//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080088//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000089//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000090
Mike Klein3e0141a2019-03-26 10:41:18 -050091#if 1
92 #define LOG_INFO(...)
93#else
94 #define LOG_INFO SkDEBUGF
95#endif
96
Ben Wagner3e45a2f2017-11-01 11:47:39 -040097static bool isLCD(const SkScalerContextRec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080098 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000099}
100
Ben Wagner082a7a72018-06-08 14:15:47 -0400101static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
102 return SkFixedToScalar(x);
103}
104
reed@android.com8a1c16f2008-12-17 15:59:43 +0000105//////////////////////////////////////////////////////////////////////////
106
Ben Wagner230a71b2018-10-01 14:54:01 -0400107using FT_Alloc_size_t = SkCallableTraits<FT_Alloc_Func>::argument<1>::type;
108static_assert(std::is_same<FT_Alloc_size_t, long >::value ||
109 std::is_same<FT_Alloc_size_t, size_t>::value,"");
110
bungeman9dc24682014-12-01 14:01:32 -0800111extern "C" {
Ben Wagner230a71b2018-10-01 14:54:01 -0400112 static void* sk_ft_alloc(FT_Memory, FT_Alloc_size_t size) {
bungeman9dc24682014-12-01 14:01:32 -0800113 return sk_malloc_throw(size);
114 }
115 static void sk_ft_free(FT_Memory, void* block) {
116 sk_free(block);
117 }
Ben Wagner230a71b2018-10-01 14:54:01 -0400118 static void* sk_ft_realloc(FT_Memory, FT_Alloc_size_t cur_size,
119 FT_Alloc_size_t new_size, void* block) {
bungeman9dc24682014-12-01 14:01:32 -0800120 return sk_realloc_throw(block, new_size);
121 }
122};
halcanary96fcdcc2015-08-27 07:41:13 -0700123FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -0800124
125class FreeTypeLibrary : SkNoncopyable {
126public:
Ben Wagnerfc497342017-02-24 11:15:26 -0500127 FreeTypeLibrary()
128 : fGetVarDesignCoordinates(nullptr)
Ben Wagnere346b1e2018-06-26 11:22:37 -0400129 , fGetVarAxisFlags(nullptr)
Ben Wagnerfc497342017-02-24 11:15:26 -0500130 , fLibrary(nullptr)
131 , fIsLCDSupported(false)
132 , fLCDExtra(0)
133 {
bungeman9dc24682014-12-01 14:01:32 -0800134 if (FT_New_Library(&gFTMemory, &fLibrary)) {
135 return;
136 }
137 FT_Add_Default_Modules(fLibrary);
138
Ben Wagner2a098d02017-03-01 13:00:53 -0500139 // When using dlsym
140 // *(void**)(&procPtr) = dlsym(self, "proc");
141 // is non-standard, but safe for POSIX. Cannot write
142 // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
143 // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
144
145 FT_Int major, minor, patch;
146 FT_Library_Version(fLibrary, &major, &minor, &patch);
147
Ben Wagnerfc497342017-02-24 11:15:26 -0500148#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
149 fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
150#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
Ben Wagner2a098d02017-03-01 13:00:53 -0500151 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500152 //The FreeType library is already loaded, so symbols are available in process.
153 void* self = dlopen(nullptr, RTLD_LAZY);
154 if (self) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500155 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
156 dlclose(self);
157 }
158 }
159#endif
160
Ben Wagner2a098d02017-03-01 13:00:53 -0500161#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
162 FT_Set_Default_Properties(fLibrary);
163#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
164 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
bungeman9dc24682014-12-01 14:01:32 -0800165 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700166 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800167 if (self) {
Ben Wagner2a098d02017-03-01 13:00:53 -0500168 FT_Set_Default_PropertiesProc setDefaultProperties;
169 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
bungeman9dc24682014-12-01 14:01:32 -0800170 dlclose(self);
171
Ben Wagner2a098d02017-03-01 13:00:53 -0500172 if (setDefaultProperties) {
173 setDefaultProperties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800174 }
175 }
Ben Wagner2a098d02017-03-01 13:00:53 -0500176 }
bungeman9dc24682014-12-01 14:01:32 -0800177#endif
Ben Wagner2a098d02017-03-01 13:00:53 -0500178
Ben Wagnere346b1e2018-06-26 11:22:37 -0400179#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080100
180 fGetVarAxisFlags = FT_Get_Var_Axis_Flags;
181#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
182 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
183 //The FreeType library is already loaded, so symbols are available in process.
184 void* self = dlopen(nullptr, RTLD_LAZY);
185 if (self) {
186 *(void**)(&fGetVarAxisFlags) = dlsym(self, "FT_Get_Var_Axis_Flags");
187 dlclose(self);
188 }
189 }
190#endif
191
Ben Wagner2a098d02017-03-01 13:00:53 -0500192 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
193 // The default has changed over time, so this doesn't mean the same thing to all users.
194 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
195 fIsLCDSupported = true;
196 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
bungeman9dc24682014-12-01 14:01:32 -0800197 }
198 }
199 ~FreeTypeLibrary() {
200 if (fLibrary) {
201 FT_Done_Library(fLibrary);
202 }
203 }
204
205 FT_Library library() { return fLibrary; }
206 bool isLCDSupported() { return fIsLCDSupported; }
207 int lcdExtra() { return fLCDExtra; }
208
Ben Wagnerfc497342017-02-24 11:15:26 -0500209 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
210 // Prior to this there was no way to get the coordinates out of the FT_Face.
211 // This wasn't too bad because you needed to specify them anyway, and the clamp was provided.
212 // However, this doesn't work when face_index specifies named variations as introduced in 2.6.1.
213 using FT_Get_Var_Blend_CoordinatesProc = FT_Error (*)(FT_Face, FT_UInt, FT_Fixed*);
214 FT_Get_Var_Blend_CoordinatesProc fGetVarDesignCoordinates;
215
Ben Wagnere346b1e2018-06-26 11:22:37 -0400216 // FT_Get_Var_Axis_Flags was introduced in FreeType 2.8.1
217 // Get the ‘flags’ field of an OpenType Variation Axis Record.
218 // Not meaningful for Adobe MM fonts (‘*flags’ is always zero).
219 using FT_Get_Var_Axis_FlagsProc = FT_Error (*)(FT_MM_Var*, FT_UInt, FT_UInt*);
220 FT_Get_Var_Axis_FlagsProc fGetVarAxisFlags;
221
bungeman9dc24682014-12-01 14:01:32 -0800222private:
223 FT_Library fLibrary;
224 bool fIsLCDSupported;
225 int fLCDExtra;
226
227 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
228 // The following platforms provide FreeType of at least 2.4.0.
229 // Ubuntu >= 11.04 (previous deprecated April 2013)
230 // Debian >= 6.0 (good)
231 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
232 // Fedora >= 14 (good)
233 // Android >= Gingerbread (good)
Ben Wagnerfc497342017-02-24 11:15:26 -0500234 // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
235 using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
Ben Wagner2a098d02017-03-01 13:00:53 -0500236
237 // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
238 // of FT_New_Library to request these global properties to be read was added.
239 using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
bungeman9dc24682014-12-01 14:01:32 -0800240};
241
reed@android.com8a1c16f2008-12-17 15:59:43 +0000242struct SkFaceRec;
243
reed086eea92016-05-04 17:12:46 -0700244SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800245static FreeTypeLibrary* gFTLibrary;
246static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000247
bungemanaabd71c2016-03-01 15:15:09 -0800248// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800249static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000250
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000251// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800252static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800253 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800254 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800255
bungeman9dc24682014-12-01 14:01:32 -0800256 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700257 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700258 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000259 }
bungeman9dc24682014-12-01 14:01:32 -0800260 ++gFTCount;
261 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000262}
263
bungeman9dc24682014-12-01 14:01:32 -0800264// Caller must lock gFTMutex before calling this function.
265static void unref_ft_library() {
266 gFTMutex.assertHeld();
267 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000268
bungeman9dc24682014-12-01 14:01:32 -0800269 --gFTCount;
270 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800271 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700272 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700273 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700274 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800275 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000276}
277
Ben Wagnerfc497342017-02-24 11:15:26 -0500278///////////////////////////////////////////////////////////////////////////
279
280struct SkFaceRec {
281 SkFaceRec* fNext;
282 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
283 FT_StreamRec fFTStream;
284 std::unique_ptr<SkStreamAsset> fSkStream;
285 uint32_t fRefCnt;
286 uint32_t fFontID;
287
288 // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
289 // Cache the variation design metrics used to create the font if the user specifies them.
290 SkAutoSTMalloc<4, SkFixed> fAxes;
291 int fAxesCount;
292
293 // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
294 // and named variation index on input, but masks the named variation index part on output.
295 // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
296 bool fNamedVariationSpecified;
297
298 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
299};
300
301extern "C" {
302 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
303 unsigned long offset,
304 unsigned char* buffer,
305 unsigned long count)
306 {
307 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
308
309 if (count) {
310 if (!stream->seek(offset)) {
311 return 0;
312 }
313 count = stream->read(buffer, count);
314 }
315 return count;
316 }
317
318 static void sk_ft_stream_close(FT_Stream) {}
319}
320
321SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
322 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
323 , fAxesCount(0), fNamedVariationSpecified(false)
324{
325 sk_bzero(&fFTStream, sizeof(fFTStream));
326 fFTStream.size = fSkStream->getLength();
327 fFTStream.descriptor.pointer = fSkStream.get();
328 fFTStream.read = sk_ft_stream_io;
329 fFTStream.close = sk_ft_stream_close;
330}
331
332static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
333 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
334 return;
335 }
336
337 // If a named variation is requested, don't overwrite the named variation's position.
338 if (data.getIndex() > 0xFFFF) {
339 rec->fNamedVariationSpecified = true;
340 return;
341 }
342
343 SkDEBUGCODE(
344 FT_MM_Var* variations = nullptr;
345 if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500346 LOG_INFO("INFO: font %s claims variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400347 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500348 return;
349 }
350 SkAutoFree autoFreeVariations(variations);
351
352 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500353 LOG_INFO("INFO: font %s has %d variations, but %d were specified.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400354 rec->fFace->family_name, variations->num_axis, data.getAxisCount());
Ben Wagnerfc497342017-02-24 11:15:26 -0500355 return;
356 }
357 )
358
359 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
360 for (int i = 0; i < data.getAxisCount(); ++i) {
361 coords[i] = data.getAxis()[i];
362 }
363 if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500364 LOG_INFO("INFO: font %s has variations, but specified variations could not be set.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400365 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500366 return;
367 }
368
369 rec->fAxesCount = data.getAxisCount();
370 rec->fAxes.reset(rec->fAxesCount);
371 for (int i = 0; i < rec->fAxesCount; ++i) {
372 rec->fAxes[i] = data.getAxis()[i];
373 }
374}
375
376// Will return nullptr on failure
377// Caller must lock gFTMutex before calling this function.
378static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
379 gFTMutex.assertHeld();
380
381 const SkFontID fontID = typeface->uniqueID();
382 SkFaceRec* cachedRec = gFaceRecHead;
383 while (cachedRec) {
384 if (cachedRec->fFontID == fontID) {
385 SkASSERT(cachedRec->fFace);
386 cachedRec->fRefCnt += 1;
387 return cachedRec;
388 }
389 cachedRec = cachedRec->fNext;
390 }
391
392 std::unique_ptr<SkFontData> data = typeface->makeFontData();
393 if (nullptr == data || !data->hasStream()) {
394 return nullptr;
395 }
396
397 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
398
399 FT_Open_Args args;
400 memset(&args, 0, sizeof(args));
401 const void* memoryBase = rec->fSkStream->getMemoryBase();
402 if (memoryBase) {
403 args.flags = FT_OPEN_MEMORY;
404 args.memory_base = (const FT_Byte*)memoryBase;
405 args.memory_size = rec->fSkStream->getLength();
406 } else {
407 args.flags = FT_OPEN_STREAM;
408 args.stream = &rec->fFTStream;
409 }
410
411 {
412 FT_Face rawFace;
413 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
414 if (err) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500415 SK_TRACEFTR(err, "unable to open font '%x'", fontID);
Ben Wagnerfc497342017-02-24 11:15:26 -0500416 return nullptr;
417 }
418 rec->fFace.reset(rawFace);
419 }
420 SkASSERT(rec->fFace);
421
422 ft_face_setup_axes(rec.get(), *data);
423
424 // FreeType will set the charmap to the "most unicode" cmap if it exists.
425 // If there are no unicode cmaps, the charmap is set to nullptr.
426 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
427 // because they are effectively private use area only (even if they aren't).
428 // This is the last on the fallback list at
429 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
430 if (!rec->fFace->charmap) {
431 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
432 }
433
434 rec->fNext = gFaceRecHead;
435 gFaceRecHead = rec.get();
436 return rec.release();
437}
438
439// Caller must lock gFTMutex before calling this function.
Ben Wagnerf1b61af2017-03-09 15:12:09 -0500440// Marked extern because vc++ does not support internal linkage template parameters.
441extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500442 gFTMutex.assertHeld();
443
444 SkFaceRec* rec = gFaceRecHead;
445 SkFaceRec* prev = nullptr;
446 while (rec) {
447 SkFaceRec* next = rec->fNext;
448 if (rec->fFace == faceRec->fFace) {
449 if (--rec->fRefCnt == 0) {
450 if (prev) {
451 prev->fNext = next;
452 } else {
453 gFaceRecHead = next;
454 }
455 delete rec;
456 }
457 return;
458 }
459 prev = rec;
460 rec = next;
461 }
462 SkDEBUGFAIL("shouldn't get here, face not in list");
463}
464
465class AutoFTAccess {
466public:
467 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
468 gFTMutex.acquire();
Ben Wagner7ca9a742017-08-17 14:05:04 -0400469 SkASSERT_RELEASE(ref_ft_library());
Ben Wagnerfc497342017-02-24 11:15:26 -0500470 fFaceRec = ref_ft_face(tf);
471 }
472
473 ~AutoFTAccess() {
474 if (fFaceRec) {
475 unref_ft_face(fFaceRec);
476 }
477 unref_ft_library();
478 gFTMutex.release();
479 }
480
481 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
482 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
483 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
484 bool isNamedVariationSpecified() {
485 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
486 }
487
488private:
489 SkFaceRec* fFaceRec;
490};
491
492///////////////////////////////////////////////////////////////////////////
493
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000494class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000495public:
bungeman7cfd46a2016-10-20 16:06:52 -0400496 SkScalerContext_FreeType(sk_sp<SkTypeface>,
497 const SkScalerContextEffects&,
498 const SkDescriptor* desc);
Brian Salomond3b65972017-03-22 12:05:03 -0400499 ~SkScalerContext_FreeType() override;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000500
reed@android.com62900b42009-02-11 15:07:19 +0000501 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700502 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000503 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000504
505protected:
mtklein36352bf2015-03-25 18:17:31 -0700506 unsigned generateGlyphCount() override;
Ben Wagnere5416452018-08-09 14:03:42 -0400507 bool generateAdvance(SkGlyph* glyph) override;
mtklein36352bf2015-03-25 18:17:31 -0700508 void generateMetrics(SkGlyph* glyph) override;
509 void generateImage(const SkGlyph& glyph) override;
Ben Wagner5ddb3082018-03-29 11:18:06 -0400510 bool generatePath(SkGlyphID glyphID, SkPath* path) override;
Mike Reedb5784ac2018-11-12 09:35:15 -0500511 void generateFontMetrics(SkFontMetrics*) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000512
513private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500514 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
515 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
516
517 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700518 FT_Size fFTSize; // The size on the fFace for this scaler.
519 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000520
bungeman401ae2d2016-07-18 15:46:27 -0700521 /** The rest of the matrix after FreeType handles the size.
522 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
523 * With bitmap only fonts this matrix must be applied to scale the bitmap.
524 */
525 SkMatrix fMatrix22Scalar;
526 /** Same as fMatrix22Scalar, but in FreeType units and space. */
527 FT_Matrix fMatrix22;
528 /** The actual size requested. */
529 SkVector fScale;
530
531 uint32_t fLoadGlyphFlags;
532 bool fDoLinearMetrics;
533 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000534
reed@android.com8a1c16f2008-12-17 15:59:43 +0000535 FT_Error setupSize();
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400536 void getBBoxForCurrentGlyph(const SkGlyph* glyph, FT_BBox* bbox,
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000537 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000538 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000539 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000540 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000541 // Caller must lock gFTMutex before calling this function.
542 // update FreeType2 glyph slot with glyph emboldened
Ben Wagnerc3aef182017-06-26 12:47:33 -0400543 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
bungeman401ae2d2016-07-18 15:46:27 -0700544 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000545};
546
547///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000548
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000549static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000550 FT_UShort fsType = FT_Get_FSType_Flags(face);
551 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
552 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000553}
554
vandebo0f9bad02014-06-19 11:05:39 -0700555static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700556 FT_UShort fsType = FT_Get_FSType_Flags(face);
557 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700558}
559
Hal Canary5bdc4d52018-04-10 11:13:24 -0400560static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
561 const char* fontType = FT_Get_X11_Font_Format(face);
562 static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
563 { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
564 { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
565 { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
566 { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
567 };
568 for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
569 return SkAdvancedTypefaceMetrics::kOther_Font;
570}
571
Hal Canary209e4b12017-05-04 14:23:55 -0400572std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000573 AutoFTAccess fta(this);
574 FT_Face face = fta.face();
575 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700576 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000577 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000578
Hal Canary209e4b12017-05-04 14:23:55 -0400579 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
Hal Canary8031b322018-03-29 13:20:30 -0700580 info->fPostScriptName.set(FT_Get_Postscript_Name(face));
581 info->fFontName = info->fPostScriptName;
halcanary32875882016-08-16 09:36:23 -0700582
vandebo0f9bad02014-06-19 11:05:39 -0700583 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700584 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700585 }
586 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700587 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700588 }
589 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700590 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700591 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000592
Hal Canary5bdc4d52018-04-10 11:13:24 -0400593 info->fType = get_font_type(face);
halcanary32875882016-08-16 09:36:23 -0700594 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700595 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000596 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700597 }
598 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000599 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700600 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000601
bungemanf1491692016-07-22 11:19:24 -0700602 PS_FontInfoRec psFontInfo;
603 TT_Postscript* postTable;
604 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
605 info->fItalicAngle = psFontInfo.italic_angle;
606 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
Ben Wagner4f6fc832017-09-15 16:00:40 -0400607 info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000608 } else {
609 info->fItalicAngle = 0;
610 }
611
612 info->fAscent = face->ascender;
613 info->fDescent = face->descender;
614
bungemanf1491692016-07-22 11:19:24 -0700615 TT_PCLT* pcltTable;
616 TT_OS2* os2Table;
617 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
618 info->fCapHeight = pcltTable->CapHeight;
619 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
620 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000621 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700622 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000623 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700624 }
625 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000626 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700627 os2Table->version != 0xFFFF &&
628 os2Table->version >= 2)
629 {
630 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000631 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000632 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
633 face->bbox.xMax, face->bbox.yMin);
Greg Daniel97c11082018-05-09 15:35:54 +0000634 return info;
Hal Canary1c2bcd82018-04-10 11:27:48 -0400635}
636
Hal Canary46cc3da2018-05-09 11:50:34 -0400637void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
638 SkASSERT(dstArray);
639 AutoFTAccess fta(this);
640 FT_Face face = fta.face();
641 FT_Long numGlyphs = face->num_glyphs;
642 sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
643
644 FT_UInt glyphIndex;
645 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
646 while (glyphIndex) {
647 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
648 // Use the first character that maps to this glyphID. https://crbug.com/359065
649 if (0 == dstArray[glyphIndex]) {
650 dstArray[glyphIndex] = charCode;
651 }
652 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
653 }
654}
655
Hal Canary5bdc4d52018-04-10 11:13:24 -0400656void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
657 SkASSERT(dstArray);
658 AutoFTAccess fta(this);
659 FT_Face face = fta.face();
660 if (face && FT_HAS_GLYPH_NAMES(face)) {
661 for (int gID = 0; gID < face->num_glyphs; gID++) {
662 char glyphName[128]; // PS limit for names is 127 bytes.
663 FT_Get_Glyph_Name(face, gID, glyphName, 128);
664 dstArray[gID] = glyphName;
665 }
666 }
667}
668
reed@google.com618ef5e2011-01-26 22:10:41 +0000669///////////////////////////////////////////////////////////////////////////
670
reed@google.com8ed436c2011-07-21 14:12:36 +0000671static bool bothZero(SkScalar a, SkScalar b) {
672 return 0 == a && 0 == b;
673}
674
675// returns false if there is any non-90-rotation or skew
Ben Wagner3e45a2f2017-11-01 11:47:39 -0400676static bool isAxisAligned(const SkScalerContextRec& rec) {
reed@google.com8ed436c2011-07-21 14:12:36 +0000677 return 0 == rec.fPreSkewX &&
678 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
679 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
680}
681
reeda9322c22016-04-12 06:47:05 -0700682SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
683 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400684 auto c = skstd::make_unique<SkScalerContext_FreeType>(
685 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000686 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400687 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000688 }
bungeman7cfd46a2016-10-20 16:06:52 -0400689 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000690}
691
Bruce Wangebf0cf52018-06-18 14:04:19 -0400692std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(
693 const SkFontArguments& args) const {
694 SkString name;
695 AutoFTAccess fta(this);
696 FT_Face face = fta.face();
697 Scanner::AxisDefinitions axisDefinitions;
698
699 if (!Scanner::GetAxes(face, &axisDefinitions)) {
700 return nullptr;
701 }
702 SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
703 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
704 axisValues, name);
705 int ttcIndex;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500706 std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
Bruce Wangebf0cf52018-06-18 14:04:19 -0400707 return skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, axisValues.get(),
708 axisDefinitions.count());
709}
710
reed@google.com0da48612013-03-19 16:06:52 +0000711void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000712 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
713 //Cap the requested size as larger sizes give bogus values.
714 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800715 //Note that this also currently only protects against large text size requests,
716 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000717 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000718 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000719 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000720
bungemanec7e12f2015-01-21 11:55:16 -0800721 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800722 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
723 SkAutoMutexAcquire ama(gFTMutex);
724 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800725 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800726 // If the runtime Freetype library doesn't support LCD, disable it here.
727 rec->fMaskFormat = SkMask::kA8_Format;
728 }
729 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000730 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000731
Mike Reed04346d52018-11-05 12:45:32 -0500732 SkFontHinting h = rec->getHinting();
733 if (kFull_SkFontHinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000734 // collapse full->normal hinting if we're not doing LCD
Mike Reed04346d52018-11-05 12:45:32 -0500735 h = kNormal_SkFontHinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000736 }
reed@google.com1ac83502012-02-28 17:06:02 +0000737
reed@google.com8ed436c2011-07-21 14:12:36 +0000738 // rotated text looks bad with hinting, so we disable it as needed
739 if (!isAxisAligned(*rec)) {
Mike Reed04346d52018-11-05 12:45:32 -0500740 h = kNo_SkFontHinting;
reed@google.com8ed436c2011-07-21 14:12:36 +0000741 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000742 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000743
bungeman@google.com97efada2012-07-30 20:40:50 +0000744#ifndef SK_GAMMA_APPLY_TO_A8
745 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700746 // SRGBTODO: Is this correct? Do we want contrast boost?
747 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000748 }
reed@google.com1ac83502012-02-28 17:06:02 +0000749#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000750}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000751
Ben Wagner26a005a2018-08-31 17:41:45 -0400752int SkTypeface_FreeType::GetUnitsPerEm(FT_Face face) {
753 if (!face) {
754 return 0;
755 }
756
757 SkScalar upem = SkIntToScalar(face->units_per_EM);
758 // At least some versions of FreeType set face->units_per_EM to 0 for bitmap only fonts.
759 if (upem == 0) {
760 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
761 if (ttHeader) {
762 upem = SkIntToScalar(ttHeader->Units_Per_EM);
763 }
764 }
765 return upem;
766}
767
reed@google.com38c37dd2013-03-21 15:36:26 +0000768int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000769 AutoFTAccess fta(this);
770 FT_Face face = fta.face();
Ben Wagner26a005a2018-08-31 17:41:45 -0400771 return GetUnitsPerEm(face);
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000772}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000773
reed@google.com35fe7372013-10-30 15:07:03 +0000774bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
775 int count, int32_t adjustments[]) const {
776 AutoFTAccess fta(this);
777 FT_Face face = fta.face();
778 if (!face || !FT_HAS_KERNING(face)) {
779 return false;
780 }
781
782 for (int i = 0; i < count - 1; ++i) {
783 FT_Vector delta;
784 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
785 FT_KERNING_UNSCALED, &delta);
786 if (err) {
787 return false;
788 }
789 adjustments[i] = delta.x;
790 }
791 return true;
792}
793
bungeman401ae2d2016-07-18 15:46:27 -0700794/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800795static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700796 if (face == nullptr) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500797 LOG_INFO("chooseBitmapStrike aborted due to nullptr face.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000798 return -1;
799 }
bungeman401ae2d2016-07-18 15:46:27 -0700800
801 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000802 FT_Int chosenStrikeIndex = -1;
803 FT_Pos chosenPPEM = 0;
804 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700805 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
806 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000807 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700808 return strikeIndex;
809 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000810 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700811 if (chosenPPEM < strikePPEM) {
812 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000813 chosenStrikeIndex = strikeIndex;
814 }
815 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700816 // attempt to decrease chosenPPEM, but not below requestedPPEM
817 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
818 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000819 chosenStrikeIndex = strikeIndex;
820 }
821 }
822 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000823 return chosenStrikeIndex;
824}
825
bungeman7cfd46a2016-10-20 16:06:52 -0400826SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700827 const SkScalerContextEffects& effects,
828 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400829 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800830 , fFace(nullptr)
831 , fFTSize(nullptr)
832 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700833{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000834 SkAutoMutexAcquire ac(gFTMutex);
Ben Wagner7ca9a742017-08-17 14:05:04 -0400835 SkASSERT_RELEASE(ref_ft_library());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000836
Ben Wagnerfc497342017-02-24 11:15:26 -0500837 fFaceRec.reset(ref_ft_face(this->getTypeface()));
838
reed@android.com8a1c16f2008-12-17 15:59:43 +0000839 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500840 if (nullptr == fFaceRec) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500841 LOG_INFO("Could not create FT_Face.\n");
reed@android.com62900b42009-02-11 15:07:19 +0000842 return;
843 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000844
reed@google.coma1bfa212012-03-08 21:57:12 +0000845 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
846
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847 // compute the flags we send to Load_Glyph
Ben Wagneraa166bd2018-08-14 14:58:18 -0400848 bool linearMetrics = this->isSubpixel();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000849 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000850 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000851
agl@chromium.org70a303f2010-05-10 14:15:50 +0000852 if (SkMask::kBW_Format == fRec.fMaskFormat) {
853 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
854 loadFlags = FT_LOAD_TARGET_MONO;
Mike Reed04346d52018-11-05 12:45:32 -0500855 if (fRec.getHinting() == kNo_SkFontHinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000856 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000857 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000858 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000859 } else {
860 switch (fRec.getHinting()) {
Mike Reed04346d52018-11-05 12:45:32 -0500861 case kNo_SkFontHinting:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000862 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000863 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000864 break;
Mike Reed04346d52018-11-05 12:45:32 -0500865 case kSlight_SkFontHinting:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000866 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
867 break;
Mike Reed04346d52018-11-05 12:45:32 -0500868 case kNormal_SkFontHinting:
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400869 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000870 break;
Mike Reed04346d52018-11-05 12:45:32 -0500871 case kFull_SkFontHinting:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000872 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000873 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000874 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000875 loadFlags = FT_LOAD_TARGET_LCD_V;
876 } else {
877 loadFlags = FT_LOAD_TARGET_LCD;
878 }
reed@google.comea2333d2011-03-14 16:44:56 +0000879 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000880 break;
881 default:
Mike Klein3e0141a2019-03-26 10:41:18 -0500882 LOG_INFO("---------- UNKNOWN hinting %d\n", fRec.getHinting());
agl@chromium.org70a303f2010-05-10 14:15:50 +0000883 break;
884 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000885 }
886
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400887 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
888 loadFlags |= FT_LOAD_FORCE_AUTOHINT;
889#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
890 } else {
891 loadFlags |= FT_LOAD_NO_AUTOHINT;
892#endif
893 }
894
reed@google.comeffc5012011-06-27 16:44:46 +0000895 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000896 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000897 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000898
reed@google.com96a9f7912011-05-06 11:49:30 +0000899 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
900 // advances, as fontconfig and cairo do.
901 // See http://code.google.com/p/skia/issues/detail?id=222.
902 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
903
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000904 // Use vertical layout if requested.
Ben Wagneraa166bd2018-08-14 14:58:18 -0400905 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000906 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
907 }
908
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000909 loadFlags |= FT_LOAD_COLOR;
910
reed@android.come4d0bc02009-07-24 19:53:20 +0000911 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000912 }
913
bungemanaabd71c2016-03-01 15:15:09 -0800914 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500915 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800916 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500917 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800918 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500919 SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800920 return nullptr;
921 }
922 return size;
923 }());
924 if (nullptr == ftSize) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500925 LOG_INFO("Could not create FT_Size.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000926 return;
927 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000928
bungemanaabd71c2016-03-01 15:15:09 -0800929 FT_Error err = FT_Activate_Size(ftSize.get());
930 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500931 SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800932 return;
933 }
934
Ben Wagner082a7a72018-06-08 14:15:47 -0400935 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
936 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
937 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
938
Ben Wagnerfc497342017-02-24 11:15:26 -0500939 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
940 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000941 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500942 SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400943 fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944 return;
945 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400946
Ben Wagner082a7a72018-06-08 14:15:47 -0400947 // Adjust the matrix to reflect the actually chosen scale.
948 // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
949 // Don't do this at all sizes as that will interfere with hinting.
950 if (fScale.fX < 1 || fScale.fY < 1) {
951 SkScalar upem = fFaceRec->fFace->units_per_EM;
952 FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
953 SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
954 SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
955 fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
956 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400957
Ben Wagnerfc497342017-02-24 11:15:26 -0500958 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
959 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000960 if (fStrikeIndex == -1) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500961 LOG_INFO("No glyphs for font \"%s\" size %f.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400962 fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700963 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000964 }
bungeman401ae2d2016-07-18 15:46:27 -0700965
Ben Wagnerfc497342017-02-24 11:15:26 -0500966 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700967 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500968 SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400969 fFaceRec->fFace->family_name, fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700970 fStrikeIndex = -1;
971 return;
972 }
973
Ben Wagner082a7a72018-06-08 14:15:47 -0400974 // Adjust the matrix to reflect the actually chosen scale.
975 // It is likely that the ppem chosen was not the one requested, this allows for scaling.
Ben Wagnerfc497342017-02-24 11:15:26 -0500976 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
977 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700978
979 // FreeType does not provide linear metrics for bitmap fonts.
980 linearMetrics = false;
981
982 // FreeType documentation says:
983 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
984 // Bitmap-only fonts ignore this flag.
985 //
986 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
987 // Force this flag off for bitmap only fonts.
988 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000989 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -0500990 LOG_INFO("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700991 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000992 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000993
Ben Wagner082a7a72018-06-08 14:15:47 -0400994 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
995 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
996 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
997 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
998
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400999#ifdef FT_COLOR_H
1000 FT_Palette_Select(fFaceRec->fFace.get(), 0, nullptr);
1001#endif
1002
bungemanaabd71c2016-03-01 15:15:09 -08001003 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -05001004 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001005 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006}
1007
1008SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +00001009 SkAutoMutexAcquire ac(gFTMutex);
1010
halcanary96fcdcc2015-08-27 07:41:13 -07001011 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001012 FT_Done_Size(fFTSize);
1013 }
1014
Ben Wagnerfc497342017-02-24 11:15:26 -05001015 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -08001016
1017 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001018}
1019
1020/* We call this before each use of the fFace, since we may be sharing
1021 this face with other context (at different sizes).
1022*/
1023FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -08001024 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001025 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001026 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001027 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001028 }
halcanary96fcdcc2015-08-27 07:41:13 -07001029 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001030 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001031}
1032
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001033unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001034 return fFace->num_glyphs;
1035}
1036
Ben Wagnere5416452018-08-09 14:03:42 -04001037bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001038 /* unhinted and light hinted text have linearly scaled advances
1039 * which are very cheap to compute with some font formats...
1040 */
Ben Wagnere5416452018-08-09 14:03:42 -04001041 if (!fDoLinearMetrics) {
1042 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001043 }
bungeman5ec443c2014-11-21 13:18:34 -08001044
Ben Wagnere5416452018-08-09 14:03:42 -04001045 SkAutoMutexAcquire ac(gFTMutex);
1046
1047 if (this->setupSize()) {
1048 glyph->zeroMetrics();
1049 return true;
1050 }
1051
1052 FT_Error error;
1053 FT_Fixed advance;
1054
1055 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
1056 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1057 &advance );
1058
1059 if (error != 0) {
1060 return false;
1061 }
1062
1063 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1064 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1065 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1066 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001067}
1068
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001069void SkScalerContext_FreeType::getBBoxForCurrentGlyph(const SkGlyph* glyph,
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001070 FT_BBox* bbox,
1071 bool snapToPixelBoundary) {
1072
1073 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1074
Ben Wagneraa166bd2018-08-14 14:58:18 -04001075 if (this->isSubpixel()) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001076 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1077 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001078 // negate dy since freetype-y-goes-up and skia-y-goes-down
1079 bbox->xMin += dx;
1080 bbox->yMin -= dy;
1081 bbox->xMax += dx;
1082 bbox->yMax -= dy;
1083 }
1084
1085 // outset the box to integral boundaries
1086 if (snapToPixelBoundary) {
1087 bbox->xMin &= ~63;
1088 bbox->yMin &= ~63;
1089 bbox->xMax = (bbox->xMax + 63) & ~63;
1090 bbox->yMax = (bbox->yMax + 63) & ~63;
1091 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001092
1093 // Must come after snapToPixelBoundary so that the width and height are
1094 // consistent. Otherwise asserts will fire later on when generating the
1095 // glyph image.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001096 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001097 FT_Vector vector;
1098 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1099 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1100 FT_Vector_Transform(&vector, &fMatrix22);
1101 bbox->xMin += vector.x;
1102 bbox->xMax += vector.x;
1103 bbox->yMin += vector.y;
1104 bbox->yMax += vector.y;
1105 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001106}
1107
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001108bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1109 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001110 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001111 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001112 }
1113 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001114 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001115 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001116 emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001117 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1118 return true;
1119}
1120
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001121void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
Ben Wagnere5416452018-08-09 14:03:42 -04001122 if (glyph->fMaskFormat == SkMask::kLCD16_Format) {
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001123 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001124 glyph->fHeight += gFTLibrary->lcdExtra();
1125 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001126 } else {
bungeman9dc24682014-12-01 14:01:32 -08001127 glyph->fWidth += gFTLibrary->lcdExtra();
1128 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001129 }
1130 }
1131}
1132
bungeman401ae2d2016-07-18 15:46:27 -07001133bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1134 // If subpixel rendering of a bitmap *can* be done.
1135 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
Ben Wagneraa166bd2018-08-14 14:58:18 -04001136 this->isSubpixel() &&
bungeman401ae2d2016-07-18 15:46:27 -07001137 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001138
bungeman401ae2d2016-07-18 15:46:27 -07001139 // If subpixel rendering of a bitmap *should* be done.
1140 // 1. If the face is not scalable then always allow subpixel rendering.
1141 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1142 // 2. If the matrix is already not identity the bitmap will already be resampled,
1143 // so resampling slightly differently shouldn't make much difference.
1144 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1145
1146 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001147}
1148
reed@android.com8a1c16f2008-12-17 15:59:43 +00001149void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1150 SkAutoMutexAcquire ac(gFTMutex);
1151
Ben Wagnere5416452018-08-09 14:03:42 -04001152 glyph->fMaskFormat = fRec.fMaskFormat;
1153
reed@android.com8a1c16f2008-12-17 15:59:43 +00001154 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001155 glyph->zeroMetrics();
1156 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001157 }
1158
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001159 FT_Error err;
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001160 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1161 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001162 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001163 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001164 return;
1165 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001166 emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001167
Ben Wagner094b3ea2018-09-06 18:09:29 -04001168 if (fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
1169 using FT_PosLimits = std::numeric_limits<FT_Pos>;
1170 FT_BBox bounds = { FT_PosLimits::max(), FT_PosLimits::max(),
1171 FT_PosLimits::min(), FT_PosLimits::min() };
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001172#ifdef FT_COLOR_H
Ben Wagner094b3ea2018-09-06 18:09:29 -04001173 FT_Bool haveLayers = false;
1174 FT_LayerIterator layerIterator = { 0, 0, nullptr };
1175 FT_UInt layerGlyphIndex;
1176 FT_UInt layerColorIndex;
1177 while (FT_Get_Color_Glyph_Layer(fFace, glyph->getGlyphID(),
1178 &layerGlyphIndex, &layerColorIndex, &layerIterator))
1179 {
1180 haveLayers = true;
1181 err = FT_Load_Glyph(fFace, layerGlyphIndex,
1182 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
1183 if (err != 0) {
1184 glyph->zeroMetrics();
1185 return;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001186 }
Ben Wagner094b3ea2018-09-06 18:09:29 -04001187 emboldenIfNeeded(fFace, fFace->glyph, layerGlyphIndex);
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001188
Ben Wagner094b3ea2018-09-06 18:09:29 -04001189 if (0 < fFace->glyph->outline.n_contours) {
1190 FT_BBox bbox;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001191 getBBoxForCurrentGlyph(glyph, &bbox, true);
1192
Ben Wagner094b3ea2018-09-06 18:09:29 -04001193 // Union
1194 bounds.xMin = std::min(bbox.xMin, bounds.xMin);
1195 bounds.yMin = std::min(bbox.yMin, bounds.yMin);
1196 bounds.xMax = std::max(bbox.xMax, bounds.xMax);
1197 bounds.yMax = std::max(bbox.yMax, bounds.yMax);
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001198 }
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001199 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001200
Ben Wagner094b3ea2018-09-06 18:09:29 -04001201 if (haveLayers) {
1202 glyph->fMaskFormat = SkMask::kARGB32_Format;
1203 if (!(bounds.xMin < bounds.xMax && bounds.yMin < bounds.yMax)) {
1204 bounds = { 0, 0, 0, 0 };
1205 }
1206 } else {
1207#endif
1208 if (0 < fFace->glyph->outline.n_contours) {
1209 getBBoxForCurrentGlyph(glyph, &bounds, true);
1210 } else {
1211 bounds = { 0, 0, 0, 0 };
1212 }
1213#ifdef FT_COLOR_H
1214 }
1215#endif
1216 // Round out, no longer dot6.
1217 bounds.xMin = SkFDot6Floor(bounds.xMin);
1218 bounds.yMin = SkFDot6Floor(bounds.yMin);
1219 bounds.xMax = SkFDot6Ceil (bounds.xMax);
1220 bounds.yMax = SkFDot6Ceil (bounds.yMax);
1221
1222 FT_Pos width = bounds.xMax - bounds.xMin;
1223 FT_Pos height = bounds.yMax - bounds.yMin;
1224 FT_Pos top = -bounds.yMax; // Freetype y-up, Skia y-down.
1225 FT_Pos left = bounds.xMin;
1226 if (!SkTFitsIn<decltype(glyph->fWidth )>(width ) ||
1227 !SkTFitsIn<decltype(glyph->fHeight)>(height) ||
1228 !SkTFitsIn<decltype(glyph->fTop )>(top ) ||
1229 !SkTFitsIn<decltype(glyph->fLeft )>(left ) )
1230 {
1231 width = height = top = left = 0;
1232 }
1233
1234 glyph->fWidth = SkToU16(width );
1235 glyph->fHeight = SkToU16(height);
1236 glyph->fTop = SkToS16(top );
1237 glyph->fLeft = SkToS16(left );
1238 updateGlyphIfLCD(glyph);
1239
1240 } else if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
Ben Wagneraa166bd2018-08-14 14:58:18 -04001241 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001242 FT_Vector vector;
1243 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1244 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1245 FT_Vector_Transform(&vector, &fMatrix22);
1246 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1247 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1248 }
1249
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001250 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1251 glyph->fMaskFormat = SkMask::kARGB32_Format;
1252 }
1253
bungeman401ae2d2016-07-18 15:46:27 -07001254 {
1255 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1256 -SkIntToScalar(fFace->glyph->bitmap_top),
1257 SkIntToScalar(fFace->glyph->bitmap.width),
1258 SkIntToScalar(fFace->glyph->bitmap.rows));
1259 fMatrix22Scalar.mapRect(&rect);
1260 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1261 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1262 SkFixedToScalar(glyph->getSubYFixed()));
1263 }
1264 SkIRect irect = rect.roundOut();
1265 glyph->fWidth = SkToU16(irect.width());
1266 glyph->fHeight = SkToU16(irect.height());
1267 glyph->fTop = SkToS16(irect.top());
1268 glyph->fLeft = SkToS16(irect.left());
1269 }
Ben Wagner094b3ea2018-09-06 18:09:29 -04001270 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001271 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001272 glyph->zeroMetrics();
1273 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001274 }
1275
Ben Wagneraa166bd2018-08-14 14:58:18 -04001276 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001277 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001278 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001279 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001280 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001281 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001282 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1283 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001284 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001285 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001286 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001287 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1288 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001289 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001290 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001291 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1292 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001293 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001294 }
1295
reed@android.com8a1c16f2008-12-17 15:59:43 +00001296#ifdef ENABLE_GLYPH_SPEW
Mike Klein3e0141a2019-03-26 10:41:18 -05001297 LOG_INFO("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001298#endif
1299}
1300
bungeman5ec443c2014-11-21 13:18:34 -08001301static void clear_glyph_image(const SkGlyph& glyph) {
1302 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1303}
reed@google.comea2333d2011-03-14 16:44:56 +00001304
bungeman@google.coma76de722012-10-26 19:35:54 +00001305void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001306 SkAutoMutexAcquire ac(gFTMutex);
1307
reed@android.com8a1c16f2008-12-17 15:59:43 +00001308 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001309 clear_glyph_image(glyph);
1310 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001311 }
1312
bungeman5ec443c2014-11-21 13:18:34 -08001313 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -05001315 SK_TRACEFTR(err, "SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d "
1316 "width:%d height:%d rb:%d flags:%d) failed.",
1317 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(),
1318 fLoadGlyphFlags);
bungeman5ec443c2014-11-21 13:18:34 -08001319 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001320 return;
1321 }
1322
Ben Wagnerc3aef182017-06-26 12:47:33 -04001323 emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
bungeman401ae2d2016-07-18 15:46:27 -07001324 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1325 SkMatrix subpixelBitmapMatrix;
1326 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1327 subpixelBitmapMatrix = fMatrix22Scalar;
1328 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1329 SkFixedToScalar(glyph.getSubYFixed()));
1330 bitmapMatrix = &subpixelBitmapMatrix;
1331 }
1332 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001333}
1334
reed@android.com8a1c16f2008-12-17 15:59:43 +00001335
Ben Wagner5ddb3082018-03-29 11:18:06 -04001336bool SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
caryclarka10742c2014-09-18 11:00:40 -07001337 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001338
Ben Wagner5ddb3082018-03-29 11:18:06 -04001339 SkAutoMutexAcquire ac(gFTMutex);
1340
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001341 // FT_IS_SCALABLE is documented to mean the face contains outline glyphs.
1342 if (!FT_IS_SCALABLE(fFace) || this->setupSize()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001343 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001344 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001345 }
1346
1347 uint32_t flags = fLoadGlyphFlags;
1348 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1349 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1350
Ben Wagner6e9ac122016-11-11 14:31:06 -05001351 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001352 if (err != 0 || fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001353 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001354 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001355 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001356 emboldenIfNeeded(fFace, fFace->glyph, glyphID);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001357
Ben Wagner5ddb3082018-03-29 11:18:06 -04001358 if (!generateGlyphPath(fFace, path)) {
1359 path->reset();
1360 return false;
1361 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001362
1363 // The path's origin from FreeType is always the horizontal layout origin.
1364 // Offset the path so that it is relative to the vertical origin if needed.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001365 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001366 FT_Vector vector;
1367 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1368 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1369 FT_Vector_Transform(&vector, &fMatrix22);
1370 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1371 }
Ben Wagner5ddb3082018-03-29 11:18:06 -04001372 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001373}
1374
Mike Reedb5784ac2018-11-12 09:35:15 -05001375void SkScalerContext_FreeType::generateFontMetrics(SkFontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001376 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377 return;
1378 }
1379
bungeman41078062014-07-07 08:16:37 -07001380 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001381
1382 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001383 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001384 return;
1385 }
1386
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001387 FT_Face face = fFace;
Ben Wagner219f3622017-07-17 15:32:25 -04001388 metrics->fFlags = 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001389
Ben Wagner26a005a2018-08-31 17:41:45 -04001390 SkScalar upem = SkIntToScalar(SkTypeface_FreeType::GetUnitsPerEm(face));
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;
Mike Reedb5784ac2018-11-12 09:35:15 -05001403 metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
1404 metrics->fFlags |= SkFontMetrics::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
Mike Reedb5784ac2018-11-12 09:35:15 -05001436 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1437 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001438
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;
Mike Reedb5784ac2018-11-12 09:35:15 -05001464 metrics->fFlags &= ~SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1465 metrics->fFlags &= ~SkFontMetrics::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;
Mike Reedb5784ac2018-11-12 09:35:15 -05001471 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1472 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001473 }
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001552#include "src/core/SkUtils.h"
reed@google.comb4162b12013-07-02 16:32:29 +00001553
Mike Reedb07e9a82019-04-19 10:02:10 -04001554// Just made up, so we don't end up storing 1000s of entries
1555constexpr int kMaxC2GCacheCount = 512;
1556
Mike Reed64670cb2019-04-16 11:37:38 -07001557void SkTypeface_FreeType::onCharsToGlyphs(const SkUnichar uni[], int count,
1558 SkGlyphID glyphs[]) const {
Mike Reedb07e9a82019-04-19 10:02:10 -04001559 // Try the cache first, *before* accessing freetype lib/face, as that
1560 // can be very slow. If we do need to compute a new glyphID, then
1561 // access those freetype objects and continue the loop.
1562
1563 SkAutoMutexAcquire ama(fC2GCacheMutex);
1564
1565 int i;
1566 for (i = 0; i < count; ++i) {
1567 int index = fC2GCache.findGlyphIndex(uni[i]);
1568 if (index < 0) {
1569 break;
1570 }
1571 glyphs[i] = SkToU16(index);
1572 }
1573 if (i == count) {
1574 // we're done, no need to access the freetype objects
1575 return;
1576 }
1577
reed@google.comb4162b12013-07-02 16:32:29 +00001578 AutoFTAccess fta(this);
1579 FT_Face face = fta.face();
1580 if (!face) {
Mike Reed64670cb2019-04-16 11:37:38 -07001581 sk_bzero(glyphs, count * sizeof(glyphs[0]));
1582 return;
reed@google.comb4162b12013-07-02 16:32:29 +00001583 }
1584
Mike Reedb07e9a82019-04-19 10:02:10 -04001585 for (; i < count; ++i) {
1586 SkUnichar c = uni[i];
1587 int index = fC2GCache.findGlyphIndex(c);
1588 if (index >= 0) {
1589 glyphs[i] = SkToU16(index);
1590 } else {
1591 glyphs[i] = SkToU16(FT_Get_Char_Index(face, c));
1592 fC2GCache.insertCharAndGlyph(~index, c, glyphs[i]);
1593 }
1594 }
1595
1596 if (fC2GCache.count() > kMaxC2GCacheCount) {
1597 fC2GCache.reset();
reed@google.comb4162b12013-07-02 16:32:29 +00001598 }
1599}
1600
1601int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001602 AutoFTAccess fta(this);
1603 FT_Face face = fta.face();
1604 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001605}
1606
bungeman@google.com839702b2013-08-07 17:09:22 +00001607SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
Ben Wagnerad031f52018-08-20 13:45:57 -04001608 sk_sp<SkTypeface::LocalizedStrings> nameIter =
1609 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
1610 if (!nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001611 SkString familyName;
1612 this->getFamilyName(&familyName);
1613 SkString language("und"); //undetermined
Ben Wagnerad031f52018-08-20 13:45:57 -04001614 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
bungeman@google.coma9802692013-08-07 02:45:25 +00001615 }
Ben Wagnerad031f52018-08-20 13:45:57 -04001616 return nameIter.release();
bungeman@google.coma9802692013-08-07 02:45:25 +00001617}
1618
Ben Wagnerfc497342017-02-24 11:15:26 -05001619int SkTypeface_FreeType::onGetVariationDesignPosition(
Ben Wagnere346b1e2018-06-26 11:22:37 -04001620 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
Ben Wagnerfc497342017-02-24 11:15:26 -05001621{
1622 AutoFTAccess fta(this);
1623 FT_Face face = fta.face();
Ben Wagnere346b1e2018-06-26 11:22:37 -04001624 if (!face) {
1625 return -1;
1626 }
Ben Wagnerfc497342017-02-24 11:15:26 -05001627
Ben Wagnere346b1e2018-06-26 11:22:37 -04001628 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001629 return 0;
1630 }
1631
1632 FT_MM_Var* variations = nullptr;
1633 if (FT_Get_MM_Var(face, &variations)) {
Ben Wagnere346b1e2018-06-26 11:22:37 -04001634 return -1;
Ben Wagnerfc497342017-02-24 11:15:26 -05001635 }
1636 SkAutoFree autoFreeVariations(variations);
1637
1638 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1639 return variations->num_axis;
1640 }
1641
1642 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1643 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1644 if (gFTLibrary->fGetVarDesignCoordinates &&
1645 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1646 {
1647 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1648 coordinates[i].axis = variations->axis[i].tag;
1649 coordinates[i].value = SkFixedToScalar(coords[i]);
1650 }
1651 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1652 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1653 coordinates[i].axis = variations->axis[i].tag;
1654 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1655 }
1656 } else if (fta.isNamedVariationSpecified()) {
1657 // The font has axes, they cannot be retrieved, and some named axis was specified.
1658 return -1;
1659 } else {
1660 // The font has axes, they cannot be retrieved, but no named instance was specified.
1661 return 0;
1662 }
1663
1664 return variations->num_axis;
1665}
1666
Ben Wagnere346b1e2018-06-26 11:22:37 -04001667int SkTypeface_FreeType::onGetVariationDesignParameters(
1668 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
1669{
1670 AutoFTAccess fta(this);
1671 FT_Face face = fta.face();
1672 if (!face) {
1673 return -1;
1674 }
1675
1676 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1677 return 0;
1678 }
1679
1680 FT_MM_Var* variations = nullptr;
1681 if (FT_Get_MM_Var(face, &variations)) {
1682 return -1;
1683 }
1684 SkAutoFree autoFreeVariations(variations);
1685
1686 if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
1687 return variations->num_axis;
1688 }
1689
1690 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1691 parameters[i].tag = variations->axis[i].tag;
1692 parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
1693 parameters[i].def = SkFixedToScalar(variations->axis[i].def);
1694 parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
1695 FT_UInt flags = 0;
1696 bool hidden = gFTLibrary->fGetVarAxisFlags &&
1697 !gFTLibrary->fGetVarAxisFlags(variations, i, &flags) &&
1698 (flags & FT_VAR_AXIS_FLAG_HIDDEN);
1699 parameters[i].setHidden(hidden);
1700 }
1701
1702 return variations->num_axis;
1703}
1704
bungeman@google.comddc218e2013-08-01 22:29:43 +00001705int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1706 AutoFTAccess fta(this);
1707 FT_Face face = fta.face();
1708
1709 FT_ULong tableCount = 0;
1710 FT_Error error;
1711
halcanary96fcdcc2015-08-27 07:41:13 -07001712 // When 'tag' is nullptr, returns number of tables in 'length'.
1713 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001714 if (error) {
1715 return 0;
1716 }
1717
1718 if (tags) {
1719 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1720 FT_ULong tableTag;
1721 FT_ULong tablelength;
1722 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1723 if (error) {
1724 return 0;
1725 }
1726 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1727 }
1728 }
1729 return tableCount;
1730}
1731
1732size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1733 size_t length, void* data) const
1734{
1735 AutoFTAccess fta(this);
1736 FT_Face face = fta.face();
1737
1738 FT_ULong tableLength = 0;
1739 FT_Error error;
1740
1741 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001742 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001743 if (error) {
1744 return 0;
1745 }
1746
1747 if (offset > tableLength) {
1748 return 0;
1749 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001750 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001751 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001752 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1753 if (error) {
1754 return 0;
1755 }
1756 }
1757
1758 return size;
1759}
1760
reed@google.comb4162b12013-07-02 16:32:29 +00001761///////////////////////////////////////////////////////////////////////////////
1762///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001763
halcanary96fcdcc2015-08-27 07:41:13 -07001764SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001765 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1766 return;
bungeman14df8332014-10-28 15:07:23 -07001767 }
bungeman9dc24682014-12-01 14:01:32 -08001768 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001769}
1770SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001771 if (fLibrary) {
1772 FT_Done_Library(fLibrary);
1773 }
bungeman14df8332014-10-28 15:07:23 -07001774}
1775
bungemanf93d7112016-09-16 06:24:20 -07001776FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001777 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001778{
halcanary96fcdcc2015-08-27 07:41:13 -07001779 if (fLibrary == nullptr) {
1780 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001781 }
1782
bungeman14df8332014-10-28 15:07:23 -07001783 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001784 memset(&args, 0, sizeof(args));
1785
1786 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001787
bsalomon49f085d2014-09-05 13:34:00 -07001788 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001789 args.flags = FT_OPEN_MEMORY;
1790 args.memory_base = (const FT_Byte*)memoryBase;
1791 args.memory_size = stream->getLength();
1792 } else {
bungeman14df8332014-10-28 15:07:23 -07001793 memset(ftStream, 0, sizeof(*ftStream));
1794 ftStream->size = stream->getLength();
1795 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001796 ftStream->read = sk_ft_stream_io;
1797 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001798
1799 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001800 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001801 }
1802
1803 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001804 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001805 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001806 }
1807 return face;
1808}
1809
bungemanf93d7112016-09-16 06:24:20 -07001810bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001811 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1812
1813 FT_StreamRec streamRec;
1814 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001815 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001816 return false;
1817 }
1818
1819 *numFaces = face->num_faces;
1820
1821 FT_Done_Face(face);
1822 return true;
1823}
1824
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001825#include "include/private/SkTSearch.h"
bungeman14df8332014-10-28 15:07:23 -07001826bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001827 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001828 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001829{
1830 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1831
1832 FT_StreamRec streamRec;
1833 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001834 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001835 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001836 }
1837
bungemana4c4a2d2014-10-20 13:33:19 -07001838 int weight = SkFontStyle::kNormal_Weight;
1839 int width = SkFontStyle::kNormal_Width;
1840 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001841 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001842 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001843 }
1844 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001845 slant = SkFontStyle::kItalic_Slant;
1846 }
1847
1848 PS_FontInfoRec psFontInfo;
1849 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1850 if (os2 && os2->version != 0xffff) {
1851 weight = os2->usWeightClass;
1852 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001853
1854 // OS/2::fsSelection bit 9 indicates oblique.
1855 if (SkToBool(os2->fsSelection & (1u << 9))) {
1856 slant = SkFontStyle::kOblique_Slant;
1857 }
bungemana4c4a2d2014-10-20 13:33:19 -07001858 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1859 static const struct {
1860 char const * const name;
1861 int const weight;
1862 } commonWeights [] = {
1863 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001864 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001865 { "black", SkFontStyle::kBlack_Weight },
1866 { "bold", SkFontStyle::kBold_Weight },
1867 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1868 { "demi", SkFontStyle::kSemiBold_Weight },
1869 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001870 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001871 { "extrabold", SkFontStyle::kExtraBold_Weight },
1872 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001873 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001874 { "heavy", SkFontStyle::kBlack_Weight },
1875 { "light", SkFontStyle::kLight_Weight },
1876 { "medium", SkFontStyle::kMedium_Weight },
1877 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001878 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001879 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001880 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001881 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001882 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001883 { "thin", SkFontStyle::kThin_Weight },
1884 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001885 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001886 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001887 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001888 { "ultralight", SkFontStyle::kExtraLight_Weight },
1889 };
1890 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001891 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001892 if (index >= 0) {
1893 weight = commonWeights[index].weight;
1894 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -05001895 LOG_INFO("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
bungemana4c4a2d2014-10-20 13:33:19 -07001896 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001897 }
1898
1899 if (name) {
1900 name->set(face->family_name);
1901 }
1902 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001903 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001904 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001905 if (isFixedPitch) {
1906 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001907 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001908
Bruce Wangebf0cf52018-06-18 14:04:19 -04001909 bool success = GetAxes(face, axes);
1910 FT_Done_Face(face);
1911 return success;
1912}
1913
1914bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
bungeman41868fe2015-05-20 09:21:04 -07001915 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001916 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001917 FT_Error err = FT_Get_MM_Var(face, &variations);
1918 if (err) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001919 LOG_INFO("INFO: font %s claims to have variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001920 face->family_name);
bungeman41868fe2015-05-20 09:21:04 -07001921 return false;
1922 }
1923 SkAutoFree autoFreeVariations(variations);
1924
1925 axes->reset(variations->num_axis);
1926 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1927 const FT_Var_Axis& ftAxis = variations->axis[i];
1928 (*axes)[i].fTag = ftAxis.tag;
1929 (*axes)[i].fMinimum = ftAxis.minimum;
1930 (*axes)[i].fDefault = ftAxis.def;
1931 (*axes)[i].fMaximum = ftAxis.maximum;
1932 }
1933 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001934 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001935}
bungemanf6c71072016-01-21 14:17:47 -08001936
1937/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1938 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001939 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001940 SkFixed* axisValues,
1941 const SkString& name)
1942{
1943 for (int i = 0; i < axisDefinitions.count(); ++i) {
1944 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001945 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1946 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001947 axisValues[i] = axisDefinition.fDefault;
bungeman9aec8942017-03-29 13:38:53 -04001948 // The position may be over specified. If there are multiple values for a given axis,
1949 // use the last one since that's what css-fonts-4 requires.
1950 for (int j = position.coordinateCount; j --> 0;) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001951 const auto& coordinate = position.coordinates[j];
1952 if (axisDefinition.fTag == coordinate.axis) {
1953 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1954 if (coordinate.value != axisValue) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001955 LOG_INFO("Requested font axis value out of range: "
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001956 "%s '%c%c%c%c' %f; pinned to %f.\n",
1957 name.c_str(),
1958 (axisDefinition.fTag >> 24) & 0xFF,
1959 (axisDefinition.fTag >> 16) & 0xFF,
1960 (axisDefinition.fTag >> 8) & 0xFF,
1961 (axisDefinition.fTag ) & 0xFF,
1962 SkScalarToDouble(coordinate.value),
1963 SkScalarToDouble(axisValue));
bungemanf6c71072016-01-21 14:17:47 -08001964 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001965 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001966 break;
1967 }
1968 }
1969 // TODO: warn on defaulted axis?
1970 }
1971
1972 SkDEBUGCODE(
1973 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001974 for (int i = 0; i < position.coordinateCount; ++i) {
1975 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001976 bool found = false;
1977 for (int j = 0; j < axisDefinitions.count(); ++j) {
1978 if (skTag == axisDefinitions[j].fTag) {
1979 found = true;
1980 break;
1981 }
1982 }
1983 if (!found) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001984 LOG_INFO("Requested font axis not found: %s '%c%c%c%c'\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001985 name.c_str(),
1986 (skTag >> 24) & 0xFF,
1987 (skTag >> 16) & 0xFF,
1988 (skTag >> 8) & 0xFF,
1989 (skTag) & 0xFF);
bungemanf6c71072016-01-21 14:17:47 -08001990 }
1991 }
1992 )
1993}