blob: c0d0d3c8135bb1642c9f797285643c736aba6914 [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)
Ben Wagnerc7520542019-04-29 15:31:09 -0400132 , fLightHintingIsYOnly(false)
Ben Wagnerfc497342017-02-24 11:15:26 -0500133 , fLCDExtra(0)
134 {
bungeman9dc24682014-12-01 14:01:32 -0800135 if (FT_New_Library(&gFTMemory, &fLibrary)) {
136 return;
137 }
138 FT_Add_Default_Modules(fLibrary);
139
Ben Wagner2a098d02017-03-01 13:00:53 -0500140 // When using dlsym
141 // *(void**)(&procPtr) = dlsym(self, "proc");
142 // is non-standard, but safe for POSIX. Cannot write
143 // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
144 // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
145
146 FT_Int major, minor, patch;
147 FT_Library_Version(fLibrary, &major, &minor, &patch);
148
Ben Wagnerfc497342017-02-24 11:15:26 -0500149#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
150 fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
151#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
Ben Wagner2a098d02017-03-01 13:00:53 -0500152 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500153 //The FreeType library is already loaded, so symbols are available in process.
154 void* self = dlopen(nullptr, RTLD_LAZY);
155 if (self) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500156 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
157 dlclose(self);
158 }
159 }
160#endif
161
Ben Wagner2a098d02017-03-01 13:00:53 -0500162#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
163 FT_Set_Default_Properties(fLibrary);
164#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
165 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
bungeman9dc24682014-12-01 14:01:32 -0800166 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700167 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800168 if (self) {
Ben Wagner2a098d02017-03-01 13:00:53 -0500169 FT_Set_Default_PropertiesProc setDefaultProperties;
170 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
bungeman9dc24682014-12-01 14:01:32 -0800171 dlclose(self);
172
Ben Wagner2a098d02017-03-01 13:00:53 -0500173 if (setDefaultProperties) {
174 setDefaultProperties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800175 }
176 }
Ben Wagner2a098d02017-03-01 13:00:53 -0500177 }
bungeman9dc24682014-12-01 14:01:32 -0800178#endif
Ben Wagner2a098d02017-03-01 13:00:53 -0500179
Ben Wagnerc7520542019-04-29 15:31:09 -0400180// The 'light' hinting is vertical only starting in 2.8.0.
181#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080000
182 fLightHintingIsYOnly = true;
183#else
184 if (major > 2 || ((major == 2 && minor > 8) || (major == 2 && minor == 8 && patch >= 0))) {
185 fLightHintingIsYOnly = true;
186 }
187#endif
188
189
Ben Wagnere346b1e2018-06-26 11:22:37 -0400190#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02080100
191 fGetVarAxisFlags = FT_Get_Var_Axis_Flags;
192#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
193 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
194 //The FreeType library is already loaded, so symbols are available in process.
195 void* self = dlopen(nullptr, RTLD_LAZY);
196 if (self) {
197 *(void**)(&fGetVarAxisFlags) = dlsym(self, "FT_Get_Var_Axis_Flags");
198 dlclose(self);
199 }
200 }
201#endif
202
Ben Wagner2a098d02017-03-01 13:00:53 -0500203 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
204 // The default has changed over time, so this doesn't mean the same thing to all users.
205 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
206 fIsLCDSupported = true;
207 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
bungeman9dc24682014-12-01 14:01:32 -0800208 }
209 }
210 ~FreeTypeLibrary() {
211 if (fLibrary) {
212 FT_Done_Library(fLibrary);
213 }
214 }
215
216 FT_Library library() { return fLibrary; }
217 bool isLCDSupported() { return fIsLCDSupported; }
218 int lcdExtra() { return fLCDExtra; }
Ben Wagnerc7520542019-04-29 15:31:09 -0400219 bool lightHintingIsYOnly() { return fLightHintingIsYOnly; }
bungeman9dc24682014-12-01 14:01:32 -0800220
Ben Wagnerfc497342017-02-24 11:15:26 -0500221 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
222 // Prior to this there was no way to get the coordinates out of the FT_Face.
223 // This wasn't too bad because you needed to specify them anyway, and the clamp was provided.
224 // However, this doesn't work when face_index specifies named variations as introduced in 2.6.1.
225 using FT_Get_Var_Blend_CoordinatesProc = FT_Error (*)(FT_Face, FT_UInt, FT_Fixed*);
226 FT_Get_Var_Blend_CoordinatesProc fGetVarDesignCoordinates;
227
Ben Wagnere346b1e2018-06-26 11:22:37 -0400228 // FT_Get_Var_Axis_Flags was introduced in FreeType 2.8.1
229 // Get the ‘flags’ field of an OpenType Variation Axis Record.
230 // Not meaningful for Adobe MM fonts (‘*flags’ is always zero).
231 using FT_Get_Var_Axis_FlagsProc = FT_Error (*)(FT_MM_Var*, FT_UInt, FT_UInt*);
232 FT_Get_Var_Axis_FlagsProc fGetVarAxisFlags;
233
bungeman9dc24682014-12-01 14:01:32 -0800234private:
235 FT_Library fLibrary;
236 bool fIsLCDSupported;
Ben Wagnerc7520542019-04-29 15:31:09 -0400237 bool fLightHintingIsYOnly;
bungeman9dc24682014-12-01 14:01:32 -0800238 int fLCDExtra;
239
240 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
241 // The following platforms provide FreeType of at least 2.4.0.
242 // Ubuntu >= 11.04 (previous deprecated April 2013)
243 // Debian >= 6.0 (good)
244 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
245 // Fedora >= 14 (good)
246 // Android >= Gingerbread (good)
Ben Wagnerfc497342017-02-24 11:15:26 -0500247 // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
248 using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
Ben Wagner2a098d02017-03-01 13:00:53 -0500249
250 // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
251 // of FT_New_Library to request these global properties to be read was added.
252 using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
bungeman9dc24682014-12-01 14:01:32 -0800253};
254
reed@android.com8a1c16f2008-12-17 15:59:43 +0000255struct SkFaceRec;
256
reed086eea92016-05-04 17:12:46 -0700257SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800258static FreeTypeLibrary* gFTLibrary;
259static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000260
bungemanaabd71c2016-03-01 15:15:09 -0800261// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800262static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000263
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000264// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800265static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800266 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800267 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800268
bungeman9dc24682014-12-01 14:01:32 -0800269 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700270 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700271 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000272 }
bungeman9dc24682014-12-01 14:01:32 -0800273 ++gFTCount;
274 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000275}
276
bungeman9dc24682014-12-01 14:01:32 -0800277// Caller must lock gFTMutex before calling this function.
278static void unref_ft_library() {
279 gFTMutex.assertHeld();
280 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000281
bungeman9dc24682014-12-01 14:01:32 -0800282 --gFTCount;
283 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800284 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700285 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700286 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700287 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800288 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000289}
290
Ben Wagnerfc497342017-02-24 11:15:26 -0500291///////////////////////////////////////////////////////////////////////////
292
293struct SkFaceRec {
294 SkFaceRec* fNext;
295 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
296 FT_StreamRec fFTStream;
297 std::unique_ptr<SkStreamAsset> fSkStream;
298 uint32_t fRefCnt;
299 uint32_t fFontID;
300
301 // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
302 // Cache the variation design metrics used to create the font if the user specifies them.
303 SkAutoSTMalloc<4, SkFixed> fAxes;
304 int fAxesCount;
305
306 // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
307 // and named variation index on input, but masks the named variation index part on output.
308 // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
309 bool fNamedVariationSpecified;
310
311 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
312};
313
314extern "C" {
315 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
316 unsigned long offset,
317 unsigned char* buffer,
318 unsigned long count)
319 {
320 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
321
322 if (count) {
323 if (!stream->seek(offset)) {
324 return 0;
325 }
326 count = stream->read(buffer, count);
327 }
328 return count;
329 }
330
331 static void sk_ft_stream_close(FT_Stream) {}
332}
333
334SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
335 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
336 , fAxesCount(0), fNamedVariationSpecified(false)
337{
338 sk_bzero(&fFTStream, sizeof(fFTStream));
339 fFTStream.size = fSkStream->getLength();
340 fFTStream.descriptor.pointer = fSkStream.get();
341 fFTStream.read = sk_ft_stream_io;
342 fFTStream.close = sk_ft_stream_close;
343}
344
345static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
346 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
347 return;
348 }
349
350 // If a named variation is requested, don't overwrite the named variation's position.
351 if (data.getIndex() > 0xFFFF) {
352 rec->fNamedVariationSpecified = true;
353 return;
354 }
355
356 SkDEBUGCODE(
357 FT_MM_Var* variations = nullptr;
358 if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500359 LOG_INFO("INFO: font %s claims variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400360 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500361 return;
362 }
363 SkAutoFree autoFreeVariations(variations);
364
365 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500366 LOG_INFO("INFO: font %s has %d variations, but %d were specified.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400367 rec->fFace->family_name, variations->num_axis, data.getAxisCount());
Ben Wagnerfc497342017-02-24 11:15:26 -0500368 return;
369 }
370 )
371
372 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
373 for (int i = 0; i < data.getAxisCount(); ++i) {
374 coords[i] = data.getAxis()[i];
375 }
376 if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500377 LOG_INFO("INFO: font %s has variations, but specified variations could not be set.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400378 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500379 return;
380 }
381
382 rec->fAxesCount = data.getAxisCount();
383 rec->fAxes.reset(rec->fAxesCount);
384 for (int i = 0; i < rec->fAxesCount; ++i) {
385 rec->fAxes[i] = data.getAxis()[i];
386 }
387}
388
389// Will return nullptr on failure
390// Caller must lock gFTMutex before calling this function.
391static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
392 gFTMutex.assertHeld();
393
394 const SkFontID fontID = typeface->uniqueID();
395 SkFaceRec* cachedRec = gFaceRecHead;
396 while (cachedRec) {
397 if (cachedRec->fFontID == fontID) {
398 SkASSERT(cachedRec->fFace);
399 cachedRec->fRefCnt += 1;
400 return cachedRec;
401 }
402 cachedRec = cachedRec->fNext;
403 }
404
405 std::unique_ptr<SkFontData> data = typeface->makeFontData();
406 if (nullptr == data || !data->hasStream()) {
407 return nullptr;
408 }
409
410 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
411
412 FT_Open_Args args;
413 memset(&args, 0, sizeof(args));
414 const void* memoryBase = rec->fSkStream->getMemoryBase();
415 if (memoryBase) {
416 args.flags = FT_OPEN_MEMORY;
417 args.memory_base = (const FT_Byte*)memoryBase;
418 args.memory_size = rec->fSkStream->getLength();
419 } else {
420 args.flags = FT_OPEN_STREAM;
421 args.stream = &rec->fFTStream;
422 }
423
424 {
425 FT_Face rawFace;
426 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
427 if (err) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500428 SK_TRACEFTR(err, "unable to open font '%x'", fontID);
Ben Wagnerfc497342017-02-24 11:15:26 -0500429 return nullptr;
430 }
431 rec->fFace.reset(rawFace);
432 }
433 SkASSERT(rec->fFace);
434
435 ft_face_setup_axes(rec.get(), *data);
436
437 // FreeType will set the charmap to the "most unicode" cmap if it exists.
438 // If there are no unicode cmaps, the charmap is set to nullptr.
439 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
440 // because they are effectively private use area only (even if they aren't).
441 // This is the last on the fallback list at
442 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
443 if (!rec->fFace->charmap) {
444 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
445 }
446
447 rec->fNext = gFaceRecHead;
448 gFaceRecHead = rec.get();
449 return rec.release();
450}
451
452// Caller must lock gFTMutex before calling this function.
Ben Wagnerf1b61af2017-03-09 15:12:09 -0500453// Marked extern because vc++ does not support internal linkage template parameters.
454extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500455 gFTMutex.assertHeld();
456
457 SkFaceRec* rec = gFaceRecHead;
458 SkFaceRec* prev = nullptr;
459 while (rec) {
460 SkFaceRec* next = rec->fNext;
461 if (rec->fFace == faceRec->fFace) {
462 if (--rec->fRefCnt == 0) {
463 if (prev) {
464 prev->fNext = next;
465 } else {
466 gFaceRecHead = next;
467 }
468 delete rec;
469 }
470 return;
471 }
472 prev = rec;
473 rec = next;
474 }
475 SkDEBUGFAIL("shouldn't get here, face not in list");
476}
477
478class AutoFTAccess {
479public:
480 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
481 gFTMutex.acquire();
Ben Wagner7ca9a742017-08-17 14:05:04 -0400482 SkASSERT_RELEASE(ref_ft_library());
Ben Wagnerfc497342017-02-24 11:15:26 -0500483 fFaceRec = ref_ft_face(tf);
484 }
485
486 ~AutoFTAccess() {
487 if (fFaceRec) {
488 unref_ft_face(fFaceRec);
489 }
490 unref_ft_library();
491 gFTMutex.release();
492 }
493
494 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
495 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
496 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
497 bool isNamedVariationSpecified() {
498 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
499 }
500
501private:
502 SkFaceRec* fFaceRec;
503};
504
505///////////////////////////////////////////////////////////////////////////
506
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000507class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000508public:
bungeman7cfd46a2016-10-20 16:06:52 -0400509 SkScalerContext_FreeType(sk_sp<SkTypeface>,
510 const SkScalerContextEffects&,
511 const SkDescriptor* desc);
Brian Salomond3b65972017-03-22 12:05:03 -0400512 ~SkScalerContext_FreeType() override;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000513
reed@android.com62900b42009-02-11 15:07:19 +0000514 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700515 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000516 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000517
518protected:
mtklein36352bf2015-03-25 18:17:31 -0700519 unsigned generateGlyphCount() override;
Ben Wagnere5416452018-08-09 14:03:42 -0400520 bool generateAdvance(SkGlyph* glyph) override;
mtklein36352bf2015-03-25 18:17:31 -0700521 void generateMetrics(SkGlyph* glyph) override;
522 void generateImage(const SkGlyph& glyph) override;
Ben Wagner5ddb3082018-03-29 11:18:06 -0400523 bool generatePath(SkGlyphID glyphID, SkPath* path) override;
Mike Reedb5784ac2018-11-12 09:35:15 -0500524 void generateFontMetrics(SkFontMetrics*) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000525
526private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500527 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
528 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
529
530 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700531 FT_Size fFTSize; // The size on the fFace for this scaler.
532 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000533
bungeman401ae2d2016-07-18 15:46:27 -0700534 /** The rest of the matrix after FreeType handles the size.
535 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
536 * With bitmap only fonts this matrix must be applied to scale the bitmap.
537 */
538 SkMatrix fMatrix22Scalar;
539 /** Same as fMatrix22Scalar, but in FreeType units and space. */
540 FT_Matrix fMatrix22;
541 /** The actual size requested. */
542 SkVector fScale;
543
544 uint32_t fLoadGlyphFlags;
545 bool fDoLinearMetrics;
546 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000547
reed@android.com8a1c16f2008-12-17 15:59:43 +0000548 FT_Error setupSize();
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400549 void getBBoxForCurrentGlyph(const SkGlyph* glyph, FT_BBox* bbox,
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000550 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000551 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000552 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000553 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000554 // Caller must lock gFTMutex before calling this function.
555 // update FreeType2 glyph slot with glyph emboldened
Ben Wagnerc3aef182017-06-26 12:47:33 -0400556 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
bungeman401ae2d2016-07-18 15:46:27 -0700557 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000558};
559
560///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000561
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000562static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000563 FT_UShort fsType = FT_Get_FSType_Flags(face);
564 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
565 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000566}
567
vandebo0f9bad02014-06-19 11:05:39 -0700568static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700569 FT_UShort fsType = FT_Get_FSType_Flags(face);
570 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700571}
572
Hal Canary5bdc4d52018-04-10 11:13:24 -0400573static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
574 const char* fontType = FT_Get_X11_Font_Format(face);
575 static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
576 { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
577 { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
578 { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
579 { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
580 };
581 for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
582 return SkAdvancedTypefaceMetrics::kOther_Font;
583}
584
Hal Canary209e4b12017-05-04 14:23:55 -0400585std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000586 AutoFTAccess fta(this);
587 FT_Face face = fta.face();
588 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700589 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000590 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000591
Hal Canary209e4b12017-05-04 14:23:55 -0400592 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
Hal Canary8031b322018-03-29 13:20:30 -0700593 info->fPostScriptName.set(FT_Get_Postscript_Name(face));
594 info->fFontName = info->fPostScriptName;
halcanary32875882016-08-16 09:36:23 -0700595
vandebo0f9bad02014-06-19 11:05:39 -0700596 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700597 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700598 }
599 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700600 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700601 }
602 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700603 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700604 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000605
Hal Canary5bdc4d52018-04-10 11:13:24 -0400606 info->fType = get_font_type(face);
halcanary32875882016-08-16 09:36:23 -0700607 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700608 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000609 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700610 }
611 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000612 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700613 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000614
bungemanf1491692016-07-22 11:19:24 -0700615 PS_FontInfoRec psFontInfo;
616 TT_Postscript* postTable;
617 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
618 info->fItalicAngle = psFontInfo.italic_angle;
619 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
Ben Wagner4f6fc832017-09-15 16:00:40 -0400620 info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000621 } else {
622 info->fItalicAngle = 0;
623 }
624
625 info->fAscent = face->ascender;
626 info->fDescent = face->descender;
627
bungemanf1491692016-07-22 11:19:24 -0700628 TT_PCLT* pcltTable;
629 TT_OS2* os2Table;
630 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
631 info->fCapHeight = pcltTable->CapHeight;
632 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
633 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000634 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700635 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000636 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700637 }
638 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000639 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700640 os2Table->version != 0xFFFF &&
641 os2Table->version >= 2)
642 {
643 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000644 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000645 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
646 face->bbox.xMax, face->bbox.yMin);
Greg Daniel97c11082018-05-09 15:35:54 +0000647 return info;
Hal Canary1c2bcd82018-04-10 11:27:48 -0400648}
649
Hal Canary46cc3da2018-05-09 11:50:34 -0400650void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
651 SkASSERT(dstArray);
652 AutoFTAccess fta(this);
653 FT_Face face = fta.face();
654 FT_Long numGlyphs = face->num_glyphs;
655 sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
656
657 FT_UInt glyphIndex;
658 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
659 while (glyphIndex) {
660 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
661 // Use the first character that maps to this glyphID. https://crbug.com/359065
662 if (0 == dstArray[glyphIndex]) {
663 dstArray[glyphIndex] = charCode;
664 }
665 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
666 }
667}
668
Hal Canary5bdc4d52018-04-10 11:13:24 -0400669void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
670 SkASSERT(dstArray);
671 AutoFTAccess fta(this);
672 FT_Face face = fta.face();
673 if (face && FT_HAS_GLYPH_NAMES(face)) {
674 for (int gID = 0; gID < face->num_glyphs; gID++) {
675 char glyphName[128]; // PS limit for names is 127 bytes.
676 FT_Get_Glyph_Name(face, gID, glyphName, 128);
677 dstArray[gID] = glyphName;
678 }
679 }
680}
681
reed@google.com618ef5e2011-01-26 22:10:41 +0000682///////////////////////////////////////////////////////////////////////////
683
reed@google.com8ed436c2011-07-21 14:12:36 +0000684static bool bothZero(SkScalar a, SkScalar b) {
685 return 0 == a && 0 == b;
686}
687
688// returns false if there is any non-90-rotation or skew
Ben Wagner3e45a2f2017-11-01 11:47:39 -0400689static bool isAxisAligned(const SkScalerContextRec& rec) {
reed@google.com8ed436c2011-07-21 14:12:36 +0000690 return 0 == rec.fPreSkewX &&
691 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
692 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
693}
694
reeda9322c22016-04-12 06:47:05 -0700695SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
696 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400697 auto c = skstd::make_unique<SkScalerContext_FreeType>(
698 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000699 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400700 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000701 }
bungeman7cfd46a2016-10-20 16:06:52 -0400702 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000703}
704
Bruce Wangebf0cf52018-06-18 14:04:19 -0400705std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(
706 const SkFontArguments& args) const {
707 SkString name;
708 AutoFTAccess fta(this);
709 FT_Face face = fta.face();
710 Scanner::AxisDefinitions axisDefinitions;
711
712 if (!Scanner::GetAxes(face, &axisDefinitions)) {
713 return nullptr;
714 }
715 SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count());
716 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(),
717 axisValues, name);
718 int ttcIndex;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500719 std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
Bruce Wangebf0cf52018-06-18 14:04:19 -0400720 return skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, axisValues.get(),
721 axisDefinitions.count());
722}
723
reed@google.com0da48612013-03-19 16:06:52 +0000724void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000725 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
726 //Cap the requested size as larger sizes give bogus values.
727 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800728 //Note that this also currently only protects against large text size requests,
729 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000730 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000731 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000732 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000733
bungemanec7e12f2015-01-21 11:55:16 -0800734 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800735 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
736 SkAutoMutexAcquire ama(gFTMutex);
737 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800738 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800739 // If the runtime Freetype library doesn't support LCD, disable it here.
740 rec->fMaskFormat = SkMask::kA8_Format;
741 }
742 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000743 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000744
Mike Reed04346d52018-11-05 12:45:32 -0500745 SkFontHinting h = rec->getHinting();
Ben Wagner5785e4a2019-05-07 16:50:29 -0400746 if (SkFontHinting::kFull == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000747 // collapse full->normal hinting if we're not doing LCD
Ben Wagner5785e4a2019-05-07 16:50:29 -0400748 h = SkFontHinting::kNormal;
reed@google.com618ef5e2011-01-26 22:10:41 +0000749 }
reed@google.com1ac83502012-02-28 17:06:02 +0000750
reed@google.com8ed436c2011-07-21 14:12:36 +0000751 // rotated text looks bad with hinting, so we disable it as needed
752 if (!isAxisAligned(*rec)) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400753 h = SkFontHinting::kNone;
reed@google.com8ed436c2011-07-21 14:12:36 +0000754 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000755 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000756
bungeman@google.com97efada2012-07-30 20:40:50 +0000757#ifndef SK_GAMMA_APPLY_TO_A8
758 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700759 // SRGBTODO: Is this correct? Do we want contrast boost?
760 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000761 }
reed@google.com1ac83502012-02-28 17:06:02 +0000762#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000763}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000764
Ben Wagner26a005a2018-08-31 17:41:45 -0400765int SkTypeface_FreeType::GetUnitsPerEm(FT_Face face) {
766 if (!face) {
767 return 0;
768 }
769
770 SkScalar upem = SkIntToScalar(face->units_per_EM);
771 // At least some versions of FreeType set face->units_per_EM to 0 for bitmap only fonts.
772 if (upem == 0) {
773 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
774 if (ttHeader) {
775 upem = SkIntToScalar(ttHeader->Units_Per_EM);
776 }
777 }
778 return upem;
779}
780
reed@google.com38c37dd2013-03-21 15:36:26 +0000781int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000782 AutoFTAccess fta(this);
783 FT_Face face = fta.face();
Ben Wagner26a005a2018-08-31 17:41:45 -0400784 return GetUnitsPerEm(face);
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000785}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000786
reed@google.com35fe7372013-10-30 15:07:03 +0000787bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
788 int count, int32_t adjustments[]) const {
789 AutoFTAccess fta(this);
790 FT_Face face = fta.face();
791 if (!face || !FT_HAS_KERNING(face)) {
792 return false;
793 }
794
795 for (int i = 0; i < count - 1; ++i) {
796 FT_Vector delta;
797 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
798 FT_KERNING_UNSCALED, &delta);
799 if (err) {
800 return false;
801 }
802 adjustments[i] = delta.x;
803 }
804 return true;
805}
806
bungeman401ae2d2016-07-18 15:46:27 -0700807/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800808static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700809 if (face == nullptr) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500810 LOG_INFO("chooseBitmapStrike aborted due to nullptr face.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000811 return -1;
812 }
bungeman401ae2d2016-07-18 15:46:27 -0700813
814 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000815 FT_Int chosenStrikeIndex = -1;
816 FT_Pos chosenPPEM = 0;
817 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700818 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
819 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000820 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700821 return strikeIndex;
822 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000823 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700824 if (chosenPPEM < strikePPEM) {
825 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000826 chosenStrikeIndex = strikeIndex;
827 }
828 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700829 // attempt to decrease chosenPPEM, but not below requestedPPEM
830 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
831 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000832 chosenStrikeIndex = strikeIndex;
833 }
834 }
835 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000836 return chosenStrikeIndex;
837}
838
bungeman7cfd46a2016-10-20 16:06:52 -0400839SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700840 const SkScalerContextEffects& effects,
841 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400842 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800843 , fFace(nullptr)
844 , fFTSize(nullptr)
845 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700846{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847 SkAutoMutexAcquire ac(gFTMutex);
Ben Wagner7ca9a742017-08-17 14:05:04 -0400848 SkASSERT_RELEASE(ref_ft_library());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000849
Ben Wagnerfc497342017-02-24 11:15:26 -0500850 fFaceRec.reset(ref_ft_face(this->getTypeface()));
851
reed@android.com8a1c16f2008-12-17 15:59:43 +0000852 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500853 if (nullptr == fFaceRec) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500854 LOG_INFO("Could not create FT_Face.\n");
reed@android.com62900b42009-02-11 15:07:19 +0000855 return;
856 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000857
reed@google.coma1bfa212012-03-08 21:57:12 +0000858 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
859
reed@android.com8a1c16f2008-12-17 15:59:43 +0000860 // compute the flags we send to Load_Glyph
Ben Wagnerf460eee2019-04-18 16:37:45 -0400861 bool linearMetrics = this->isLinearMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000862 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000863 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000864
agl@chromium.org70a303f2010-05-10 14:15:50 +0000865 if (SkMask::kBW_Format == fRec.fMaskFormat) {
866 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
867 loadFlags = FT_LOAD_TARGET_MONO;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400868 if (fRec.getHinting() == SkFontHinting::kNone) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000869 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000870 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000871 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000872 } else {
873 switch (fRec.getHinting()) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400874 case SkFontHinting::kNone:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000875 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000876 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000877 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400878 case SkFontHinting::kSlight:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000879 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
Ben Wagnerc7520542019-04-29 15:31:09 -0400880 if (gFTLibrary->lightHintingIsYOnly()) {
881 linearMetrics = true;
882 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000883 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400884 case SkFontHinting::kNormal:
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400885 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000886 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400887 case SkFontHinting::kFull:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000888 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000889 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000890 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000891 loadFlags = FT_LOAD_TARGET_LCD_V;
892 } else {
893 loadFlags = FT_LOAD_TARGET_LCD;
894 }
reed@google.comea2333d2011-03-14 16:44:56 +0000895 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000896 break;
897 default:
Mike Klein3e0141a2019-03-26 10:41:18 -0500898 LOG_INFO("---------- UNKNOWN hinting %d\n", fRec.getHinting());
agl@chromium.org70a303f2010-05-10 14:15:50 +0000899 break;
900 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000901 }
902
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400903 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
904 loadFlags |= FT_LOAD_FORCE_AUTOHINT;
905#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
906 } else {
907 loadFlags |= FT_LOAD_NO_AUTOHINT;
908#endif
909 }
910
reed@google.comeffc5012011-06-27 16:44:46 +0000911 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000912 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000913 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000914
reed@google.com96a9f7912011-05-06 11:49:30 +0000915 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
916 // advances, as fontconfig and cairo do.
917 // See http://code.google.com/p/skia/issues/detail?id=222.
918 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
919
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000920 // Use vertical layout if requested.
Ben Wagneraa166bd2018-08-14 14:58:18 -0400921 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000922 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
923 }
924
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000925 loadFlags |= FT_LOAD_COLOR;
926
reed@android.come4d0bc02009-07-24 19:53:20 +0000927 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000928 }
929
bungemanaabd71c2016-03-01 15:15:09 -0800930 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500931 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800932 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500933 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800934 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500935 SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800936 return nullptr;
937 }
938 return size;
939 }());
940 if (nullptr == ftSize) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500941 LOG_INFO("Could not create FT_Size.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000942 return;
943 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944
bungemanaabd71c2016-03-01 15:15:09 -0800945 FT_Error err = FT_Activate_Size(ftSize.get());
946 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500947 SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800948 return;
949 }
950
Ben Wagner082a7a72018-06-08 14:15:47 -0400951 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
952 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
953 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
954
Ben Wagnerfc497342017-02-24 11:15:26 -0500955 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
956 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000957 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500958 SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400959 fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960 return;
961 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400962
Ben Wagner082a7a72018-06-08 14:15:47 -0400963 // Adjust the matrix to reflect the actually chosen scale.
964 // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
965 // Don't do this at all sizes as that will interfere with hinting.
966 if (fScale.fX < 1 || fScale.fY < 1) {
967 SkScalar upem = fFaceRec->fFace->units_per_EM;
968 FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
969 SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
970 SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
971 fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
972 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400973
Ben Wagnerfc497342017-02-24 11:15:26 -0500974 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
975 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000976 if (fStrikeIndex == -1) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500977 LOG_INFO("No glyphs for font \"%s\" size %f.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400978 fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700979 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000980 }
bungeman401ae2d2016-07-18 15:46:27 -0700981
Ben Wagnerfc497342017-02-24 11:15:26 -0500982 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700983 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500984 SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400985 fFaceRec->fFace->family_name, fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700986 fStrikeIndex = -1;
987 return;
988 }
989
Ben Wagner082a7a72018-06-08 14:15:47 -0400990 // Adjust the matrix to reflect the actually chosen scale.
991 // It is likely that the ppem chosen was not the one requested, this allows for scaling.
Ben Wagnerfc497342017-02-24 11:15:26 -0500992 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
993 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700994
995 // FreeType does not provide linear metrics for bitmap fonts.
996 linearMetrics = false;
997
998 // FreeType documentation says:
999 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
1000 // Bitmap-only fonts ignore this flag.
1001 //
1002 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
1003 // Force this flag off for bitmap only fonts.
1004 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001005 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -05001006 LOG_INFO("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -07001007 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001008 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001009
Ben Wagner082a7a72018-06-08 14:15:47 -04001010 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
1011 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
1012 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
1013 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
1014
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001015#ifdef FT_COLOR_H
1016 FT_Palette_Select(fFaceRec->fFace.get(), 0, nullptr);
1017#endif
1018
bungemanaabd71c2016-03-01 15:15:09 -08001019 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -05001020 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001021 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001022}
1023
1024SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +00001025 SkAutoMutexAcquire ac(gFTMutex);
1026
halcanary96fcdcc2015-08-27 07:41:13 -07001027 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001028 FT_Done_Size(fFTSize);
1029 }
1030
Ben Wagnerfc497342017-02-24 11:15:26 -05001031 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -08001032
1033 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001034}
1035
1036/* We call this before each use of the fFace, since we may be sharing
1037 this face with other context (at different sizes).
1038*/
1039FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -08001040 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001041 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001042 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001043 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001044 }
halcanary96fcdcc2015-08-27 07:41:13 -07001045 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001046 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001047}
1048
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001049unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001050 return fFace->num_glyphs;
1051}
1052
Ben Wagnere5416452018-08-09 14:03:42 -04001053bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001054 /* unhinted and light hinted text have linearly scaled advances
1055 * which are very cheap to compute with some font formats...
1056 */
Ben Wagnere5416452018-08-09 14:03:42 -04001057 if (!fDoLinearMetrics) {
1058 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001059 }
bungeman5ec443c2014-11-21 13:18:34 -08001060
Ben Wagnere5416452018-08-09 14:03:42 -04001061 SkAutoMutexAcquire ac(gFTMutex);
1062
1063 if (this->setupSize()) {
1064 glyph->zeroMetrics();
1065 return true;
1066 }
1067
1068 FT_Error error;
1069 FT_Fixed advance;
1070
1071 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
1072 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1073 &advance );
1074
1075 if (error != 0) {
1076 return false;
1077 }
1078
1079 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1080 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1081 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1082 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001083}
1084
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001085void SkScalerContext_FreeType::getBBoxForCurrentGlyph(const SkGlyph* glyph,
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001086 FT_BBox* bbox,
1087 bool snapToPixelBoundary) {
1088
1089 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1090
Ben Wagneraa166bd2018-08-14 14:58:18 -04001091 if (this->isSubpixel()) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001092 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1093 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001094 // negate dy since freetype-y-goes-up and skia-y-goes-down
1095 bbox->xMin += dx;
1096 bbox->yMin -= dy;
1097 bbox->xMax += dx;
1098 bbox->yMax -= dy;
1099 }
1100
1101 // outset the box to integral boundaries
1102 if (snapToPixelBoundary) {
1103 bbox->xMin &= ~63;
1104 bbox->yMin &= ~63;
1105 bbox->xMax = (bbox->xMax + 63) & ~63;
1106 bbox->yMax = (bbox->yMax + 63) & ~63;
1107 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001108
1109 // Must come after snapToPixelBoundary so that the width and height are
1110 // consistent. Otherwise asserts will fire later on when generating the
1111 // glyph image.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001112 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001113 FT_Vector vector;
1114 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1115 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1116 FT_Vector_Transform(&vector, &fMatrix22);
1117 bbox->xMin += vector.x;
1118 bbox->xMax += vector.x;
1119 bbox->yMin += vector.y;
1120 bbox->yMax += vector.y;
1121 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001122}
1123
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001124bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1125 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001126 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001127 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001128 }
1129 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001130 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001131 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001132 emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001133 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1134 return true;
1135}
1136
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001137void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
Ben Wagnere5416452018-08-09 14:03:42 -04001138 if (glyph->fMaskFormat == SkMask::kLCD16_Format) {
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001139 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001140 glyph->fHeight += gFTLibrary->lcdExtra();
1141 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001142 } else {
bungeman9dc24682014-12-01 14:01:32 -08001143 glyph->fWidth += gFTLibrary->lcdExtra();
1144 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001145 }
1146 }
1147}
1148
bungeman401ae2d2016-07-18 15:46:27 -07001149bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1150 // If subpixel rendering of a bitmap *can* be done.
1151 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
Ben Wagneraa166bd2018-08-14 14:58:18 -04001152 this->isSubpixel() &&
bungeman401ae2d2016-07-18 15:46:27 -07001153 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001154
bungeman401ae2d2016-07-18 15:46:27 -07001155 // If subpixel rendering of a bitmap *should* be done.
1156 // 1. If the face is not scalable then always allow subpixel rendering.
1157 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1158 // 2. If the matrix is already not identity the bitmap will already be resampled,
1159 // so resampling slightly differently shouldn't make much difference.
1160 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1161
1162 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001163}
1164
reed@android.com8a1c16f2008-12-17 15:59:43 +00001165void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1166 SkAutoMutexAcquire ac(gFTMutex);
1167
Ben Wagnere5416452018-08-09 14:03:42 -04001168 glyph->fMaskFormat = fRec.fMaskFormat;
1169
reed@android.com8a1c16f2008-12-17 15:59:43 +00001170 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001171 glyph->zeroMetrics();
1172 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001173 }
1174
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001175 FT_Error err;
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001176 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1177 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001178 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001179 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001180 return;
1181 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001182 emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001183
Ben Wagner094b3ea2018-09-06 18:09:29 -04001184 if (fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
1185 using FT_PosLimits = std::numeric_limits<FT_Pos>;
1186 FT_BBox bounds = { FT_PosLimits::max(), FT_PosLimits::max(),
1187 FT_PosLimits::min(), FT_PosLimits::min() };
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001188#ifdef FT_COLOR_H
Ben Wagner094b3ea2018-09-06 18:09:29 -04001189 FT_Bool haveLayers = false;
1190 FT_LayerIterator layerIterator = { 0, 0, nullptr };
1191 FT_UInt layerGlyphIndex;
1192 FT_UInt layerColorIndex;
1193 while (FT_Get_Color_Glyph_Layer(fFace, glyph->getGlyphID(),
1194 &layerGlyphIndex, &layerColorIndex, &layerIterator))
1195 {
1196 haveLayers = true;
1197 err = FT_Load_Glyph(fFace, layerGlyphIndex,
1198 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
1199 if (err != 0) {
1200 glyph->zeroMetrics();
1201 return;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001202 }
Ben Wagner094b3ea2018-09-06 18:09:29 -04001203 emboldenIfNeeded(fFace, fFace->glyph, layerGlyphIndex);
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001204
Ben Wagner094b3ea2018-09-06 18:09:29 -04001205 if (0 < fFace->glyph->outline.n_contours) {
1206 FT_BBox bbox;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001207 getBBoxForCurrentGlyph(glyph, &bbox, true);
1208
Ben Wagner094b3ea2018-09-06 18:09:29 -04001209 // Union
1210 bounds.xMin = std::min(bbox.xMin, bounds.xMin);
1211 bounds.yMin = std::min(bbox.yMin, bounds.yMin);
1212 bounds.xMax = std::max(bbox.xMax, bounds.xMax);
1213 bounds.yMax = std::max(bbox.yMax, bounds.yMax);
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001214 }
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001215 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001216
Ben Wagner094b3ea2018-09-06 18:09:29 -04001217 if (haveLayers) {
1218 glyph->fMaskFormat = SkMask::kARGB32_Format;
1219 if (!(bounds.xMin < bounds.xMax && bounds.yMin < bounds.yMax)) {
1220 bounds = { 0, 0, 0, 0 };
1221 }
1222 } else {
1223#endif
1224 if (0 < fFace->glyph->outline.n_contours) {
1225 getBBoxForCurrentGlyph(glyph, &bounds, true);
1226 } else {
1227 bounds = { 0, 0, 0, 0 };
1228 }
1229#ifdef FT_COLOR_H
1230 }
1231#endif
1232 // Round out, no longer dot6.
1233 bounds.xMin = SkFDot6Floor(bounds.xMin);
1234 bounds.yMin = SkFDot6Floor(bounds.yMin);
1235 bounds.xMax = SkFDot6Ceil (bounds.xMax);
1236 bounds.yMax = SkFDot6Ceil (bounds.yMax);
1237
1238 FT_Pos width = bounds.xMax - bounds.xMin;
1239 FT_Pos height = bounds.yMax - bounds.yMin;
1240 FT_Pos top = -bounds.yMax; // Freetype y-up, Skia y-down.
1241 FT_Pos left = bounds.xMin;
1242 if (!SkTFitsIn<decltype(glyph->fWidth )>(width ) ||
1243 !SkTFitsIn<decltype(glyph->fHeight)>(height) ||
1244 !SkTFitsIn<decltype(glyph->fTop )>(top ) ||
1245 !SkTFitsIn<decltype(glyph->fLeft )>(left ) )
1246 {
1247 width = height = top = left = 0;
1248 }
1249
1250 glyph->fWidth = SkToU16(width );
1251 glyph->fHeight = SkToU16(height);
1252 glyph->fTop = SkToS16(top );
1253 glyph->fLeft = SkToS16(left );
1254 updateGlyphIfLCD(glyph);
1255
1256 } else if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
Ben Wagneraa166bd2018-08-14 14:58:18 -04001257 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001258 FT_Vector vector;
1259 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1260 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1261 FT_Vector_Transform(&vector, &fMatrix22);
1262 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1263 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1264 }
1265
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001266 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1267 glyph->fMaskFormat = SkMask::kARGB32_Format;
1268 }
1269
bungeman401ae2d2016-07-18 15:46:27 -07001270 {
1271 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1272 -SkIntToScalar(fFace->glyph->bitmap_top),
1273 SkIntToScalar(fFace->glyph->bitmap.width),
1274 SkIntToScalar(fFace->glyph->bitmap.rows));
1275 fMatrix22Scalar.mapRect(&rect);
1276 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1277 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1278 SkFixedToScalar(glyph->getSubYFixed()));
1279 }
1280 SkIRect irect = rect.roundOut();
1281 glyph->fWidth = SkToU16(irect.width());
1282 glyph->fHeight = SkToU16(irect.height());
1283 glyph->fTop = SkToS16(irect.top());
1284 glyph->fLeft = SkToS16(irect.left());
1285 }
Ben Wagner094b3ea2018-09-06 18:09:29 -04001286 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001287 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001288 glyph->zeroMetrics();
1289 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001290 }
1291
Ben Wagneraa166bd2018-08-14 14:58:18 -04001292 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001293 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001294 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001295 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001296 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001297 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001298 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1299 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001300 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001301 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001302 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001303 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1304 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001305 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001306 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001307 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1308 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001309 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001310 }
1311
reed@android.com8a1c16f2008-12-17 15:59:43 +00001312#ifdef ENABLE_GLYPH_SPEW
Mike Klein3e0141a2019-03-26 10:41:18 -05001313 LOG_INFO("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314#endif
1315}
1316
bungeman5ec443c2014-11-21 13:18:34 -08001317static void clear_glyph_image(const SkGlyph& glyph) {
1318 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1319}
reed@google.comea2333d2011-03-14 16:44:56 +00001320
bungeman@google.coma76de722012-10-26 19:35:54 +00001321void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001322 SkAutoMutexAcquire ac(gFTMutex);
1323
reed@android.com8a1c16f2008-12-17 15:59:43 +00001324 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001325 clear_glyph_image(glyph);
1326 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001327 }
1328
bungeman5ec443c2014-11-21 13:18:34 -08001329 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -05001331 SK_TRACEFTR(err, "SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d "
1332 "width:%d height:%d rb:%d flags:%d) failed.",
1333 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(),
1334 fLoadGlyphFlags);
bungeman5ec443c2014-11-21 13:18:34 -08001335 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001336 return;
1337 }
1338
Ben Wagnerc3aef182017-06-26 12:47:33 -04001339 emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
bungeman401ae2d2016-07-18 15:46:27 -07001340 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1341 SkMatrix subpixelBitmapMatrix;
1342 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1343 subpixelBitmapMatrix = fMatrix22Scalar;
1344 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1345 SkFixedToScalar(glyph.getSubYFixed()));
1346 bitmapMatrix = &subpixelBitmapMatrix;
1347 }
1348 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001349}
1350
reed@android.com8a1c16f2008-12-17 15:59:43 +00001351
Ben Wagner5ddb3082018-03-29 11:18:06 -04001352bool SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
caryclarka10742c2014-09-18 11:00:40 -07001353 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001354
Ben Wagner5ddb3082018-03-29 11:18:06 -04001355 SkAutoMutexAcquire ac(gFTMutex);
1356
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001357 // FT_IS_SCALABLE is documented to mean the face contains outline glyphs.
1358 if (!FT_IS_SCALABLE(fFace) || this->setupSize()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001359 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001360 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001361 }
1362
1363 uint32_t flags = fLoadGlyphFlags;
1364 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1365 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1366
Ben Wagner6e9ac122016-11-11 14:31:06 -05001367 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001368 if (err != 0 || fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001369 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001370 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001371 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001372 emboldenIfNeeded(fFace, fFace->glyph, glyphID);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001373
Ben Wagner5ddb3082018-03-29 11:18:06 -04001374 if (!generateGlyphPath(fFace, path)) {
1375 path->reset();
1376 return false;
1377 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001378
1379 // The path's origin from FreeType is always the horizontal layout origin.
1380 // Offset the path so that it is relative to the vertical origin if needed.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001381 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001382 FT_Vector vector;
1383 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1384 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1385 FT_Vector_Transform(&vector, &fMatrix22);
1386 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1387 }
Ben Wagner5ddb3082018-03-29 11:18:06 -04001388 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001389}
1390
Mike Reedb5784ac2018-11-12 09:35:15 -05001391void SkScalerContext_FreeType::generateFontMetrics(SkFontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001392 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001393 return;
1394 }
1395
bungeman41078062014-07-07 08:16:37 -07001396 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001397
1398 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001399 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001400 return;
1401 }
1402
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001403 FT_Face face = fFace;
Ben Wagner219f3622017-07-17 15:32:25 -04001404 metrics->fFlags = 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001405
Ben Wagner26a005a2018-08-31 17:41:45 -04001406 SkScalar upem = SkIntToScalar(SkTypeface_FreeType::GetUnitsPerEm(face));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001407
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001408 // use the os/2 table as a source of reasonable defaults.
1409 SkScalar x_height = 0.0f;
1410 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001411 SkScalar cap_height = 0.0f;
Kevin Lubick42846132018-01-05 10:11:11 -05001412 SkScalar strikeoutThickness = 0.0f, strikeoutPosition = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001413 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1414 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001415 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001416 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
Ben Wagner219f3622017-07-17 15:32:25 -04001417 strikeoutThickness = SkIntToScalar(os2->yStrikeoutSize) / upem;
1418 strikeoutPosition = -SkIntToScalar(os2->yStrikeoutPosition) / upem;
Mike Reedb5784ac2018-11-12 09:35:15 -05001419 metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
1420 metrics->fFlags |= SkFontMetrics::kStrikeoutPositionIsValid_Flag;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001421 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001422 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001423 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001424 }
1425
1426 // pull from format-specific metrics as needed
1427 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001428 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001429 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001430 // FreeType will always use HHEA metrics if they're not zero.
1431 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1432 // It also ignores the VDMX tables, which are also of interest here
1433 // (and override everything else when they apply).
1434 static const int kUseTypoMetricsMask = (1 << 7);
1435 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1436 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1437 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1438 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1439 } else {
1440 ascent = -SkIntToScalar(face->ascender) / upem;
1441 descent = -SkIntToScalar(face->descender) / upem;
1442 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1443 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001444 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1445 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1446 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1447 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001448 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001449 underlinePosition = -SkIntToScalar(face->underline_position +
1450 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001451
Mike Reedb5784ac2018-11-12 09:35:15 -05001452 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1453 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001454
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001455 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001456 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001457 FT_BBox bbox;
1458 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001459 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1460 }
1461 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001462 if (!cap_height) {
1463 FT_BBox bbox;
1464 if (getCBoxForLetter('H', &bbox)) {
1465 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1466 }
1467 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001468 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1469 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1470 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1471 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1472 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001473 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001474 xmin = 0.0f;
1475 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001476 ymin = descent;
1477 ymax = ascent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001478 underlineThickness = 0;
1479 underlinePosition = 0;
Mike Reedb5784ac2018-11-12 09:35:15 -05001480 metrics->fFlags &= ~SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1481 metrics->fFlags &= ~SkFontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001482
1483 TT_Postscript* post = (TT_Postscript*) FT_Get_Sfnt_Table(face, ft_sfnt_post);
1484 if (post) {
1485 underlineThickness = SkIntToScalar(post->underlineThickness) / upem;
1486 underlinePosition = -SkIntToScalar(post->underlinePosition) / upem;
Mike Reedb5784ac2018-11-12 09:35:15 -05001487 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1488 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001489 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001490 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001491 sk_bzero(metrics, sizeof(*metrics));
1492 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001493 }
1494
1495 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1496 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001497 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001498 }
1499 if (!avgCharWidth) {
1500 avgCharWidth = xmax - xmin;
1501 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001502 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001503 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001504 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001505
1506 // disallow negative linespacing
1507 if (leading < 0.0f) {
1508 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001509 }
1510
bungeman53790512016-07-21 13:32:09 -07001511 metrics->fTop = ymax * fScale.y();
1512 metrics->fAscent = ascent * fScale.y();
1513 metrics->fDescent = descent * fScale.y();
1514 metrics->fBottom = ymin * fScale.y();
1515 metrics->fLeading = leading * fScale.y();
1516 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1517 metrics->fXMin = xmin * fScale.y();
1518 metrics->fXMax = xmax * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001519 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
bungeman7316b102014-10-29 12:46:52 -07001520 metrics->fXHeight = x_height;
1521 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001522 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1523 metrics->fUnderlinePosition = underlinePosition * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001524 metrics->fStrikeoutThickness = strikeoutThickness * fScale.y();
1525 metrics->fStrikeoutPosition = strikeoutPosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001526}
1527
djsollenfcfea992015-01-09 08:18:13 -08001528///////////////////////////////////////////////////////////////////////////////
1529
1530// hand-tuned value to reduce outline embolden strength
1531#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1532 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1533 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1534 #else
1535 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1536 #endif
1537#endif
1538
1539///////////////////////////////////////////////////////////////////////////////
1540
Ben Wagnerc3aef182017-06-26 12:47:33 -04001541void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid) {
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001542 // check to see if the embolden bit is set
1543 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1544 return;
1545 }
1546
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001547 switch (glyph->format) {
1548 case FT_GLYPH_FORMAT_OUTLINE:
1549 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001550 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1551 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001552 FT_Outline_Embolden(&glyph->outline, strength);
1553 break;
1554 case FT_GLYPH_FORMAT_BITMAP:
Ben Wagnerc3aef182017-06-26 12:47:33 -04001555 if (!fFace->glyph->bitmap.buffer) {
1556 FT_Load_Glyph(fFace, gid, fLoadGlyphFlags);
1557 }
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001558 FT_GlyphSlot_Own_Bitmap(glyph);
1559 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1560 break;
1561 default:
1562 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001563 }
1564}
1565
reed@google.comb4162b12013-07-02 16:32:29 +00001566///////////////////////////////////////////////////////////////////////////////
1567
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001568#include "src/core/SkUtils.h"
reed@google.comb4162b12013-07-02 16:32:29 +00001569
Mike Reedb07e9a82019-04-19 10:02:10 -04001570// Just made up, so we don't end up storing 1000s of entries
1571constexpr int kMaxC2GCacheCount = 512;
1572
Mike Reed64670cb2019-04-16 11:37:38 -07001573void SkTypeface_FreeType::onCharsToGlyphs(const SkUnichar uni[], int count,
1574 SkGlyphID glyphs[]) const {
Mike Reedb07e9a82019-04-19 10:02:10 -04001575 // Try the cache first, *before* accessing freetype lib/face, as that
1576 // can be very slow. If we do need to compute a new glyphID, then
1577 // access those freetype objects and continue the loop.
1578
1579 SkAutoMutexAcquire ama(fC2GCacheMutex);
1580
1581 int i;
1582 for (i = 0; i < count; ++i) {
1583 int index = fC2GCache.findGlyphIndex(uni[i]);
1584 if (index < 0) {
1585 break;
1586 }
1587 glyphs[i] = SkToU16(index);
1588 }
1589 if (i == count) {
1590 // we're done, no need to access the freetype objects
1591 return;
1592 }
1593
reed@google.comb4162b12013-07-02 16:32:29 +00001594 AutoFTAccess fta(this);
1595 FT_Face face = fta.face();
1596 if (!face) {
Mike Reed64670cb2019-04-16 11:37:38 -07001597 sk_bzero(glyphs, count * sizeof(glyphs[0]));
1598 return;
reed@google.comb4162b12013-07-02 16:32:29 +00001599 }
1600
Mike Reedb07e9a82019-04-19 10:02:10 -04001601 for (; i < count; ++i) {
1602 SkUnichar c = uni[i];
1603 int index = fC2GCache.findGlyphIndex(c);
1604 if (index >= 0) {
1605 glyphs[i] = SkToU16(index);
1606 } else {
1607 glyphs[i] = SkToU16(FT_Get_Char_Index(face, c));
1608 fC2GCache.insertCharAndGlyph(~index, c, glyphs[i]);
1609 }
1610 }
1611
1612 if (fC2GCache.count() > kMaxC2GCacheCount) {
1613 fC2GCache.reset();
reed@google.comb4162b12013-07-02 16:32:29 +00001614 }
1615}
1616
1617int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001618 AutoFTAccess fta(this);
1619 FT_Face face = fta.face();
1620 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001621}
1622
bungeman@google.com839702b2013-08-07 17:09:22 +00001623SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
Ben Wagnerad031f52018-08-20 13:45:57 -04001624 sk_sp<SkTypeface::LocalizedStrings> nameIter =
1625 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
1626 if (!nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001627 SkString familyName;
1628 this->getFamilyName(&familyName);
1629 SkString language("und"); //undetermined
Ben Wagnerad031f52018-08-20 13:45:57 -04001630 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
bungeman@google.coma9802692013-08-07 02:45:25 +00001631 }
Ben Wagnerad031f52018-08-20 13:45:57 -04001632 return nameIter.release();
bungeman@google.coma9802692013-08-07 02:45:25 +00001633}
1634
Ben Wagnerfc497342017-02-24 11:15:26 -05001635int SkTypeface_FreeType::onGetVariationDesignPosition(
Ben Wagnere346b1e2018-06-26 11:22:37 -04001636 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
Ben Wagnerfc497342017-02-24 11:15:26 -05001637{
1638 AutoFTAccess fta(this);
1639 FT_Face face = fta.face();
Ben Wagnere346b1e2018-06-26 11:22:37 -04001640 if (!face) {
1641 return -1;
1642 }
Ben Wagnerfc497342017-02-24 11:15:26 -05001643
Ben Wagnere346b1e2018-06-26 11:22:37 -04001644 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001645 return 0;
1646 }
1647
1648 FT_MM_Var* variations = nullptr;
1649 if (FT_Get_MM_Var(face, &variations)) {
Ben Wagnere346b1e2018-06-26 11:22:37 -04001650 return -1;
Ben Wagnerfc497342017-02-24 11:15:26 -05001651 }
1652 SkAutoFree autoFreeVariations(variations);
1653
1654 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1655 return variations->num_axis;
1656 }
1657
1658 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1659 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1660 if (gFTLibrary->fGetVarDesignCoordinates &&
1661 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1662 {
1663 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1664 coordinates[i].axis = variations->axis[i].tag;
1665 coordinates[i].value = SkFixedToScalar(coords[i]);
1666 }
1667 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1668 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1669 coordinates[i].axis = variations->axis[i].tag;
1670 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1671 }
1672 } else if (fta.isNamedVariationSpecified()) {
1673 // The font has axes, they cannot be retrieved, and some named axis was specified.
1674 return -1;
1675 } else {
1676 // The font has axes, they cannot be retrieved, but no named instance was specified.
1677 return 0;
1678 }
1679
1680 return variations->num_axis;
1681}
1682
Ben Wagnere346b1e2018-06-26 11:22:37 -04001683int SkTypeface_FreeType::onGetVariationDesignParameters(
1684 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
1685{
1686 AutoFTAccess fta(this);
1687 FT_Face face = fta.face();
1688 if (!face) {
1689 return -1;
1690 }
1691
1692 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1693 return 0;
1694 }
1695
1696 FT_MM_Var* variations = nullptr;
1697 if (FT_Get_MM_Var(face, &variations)) {
1698 return -1;
1699 }
1700 SkAutoFree autoFreeVariations(variations);
1701
1702 if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
1703 return variations->num_axis;
1704 }
1705
1706 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1707 parameters[i].tag = variations->axis[i].tag;
1708 parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
1709 parameters[i].def = SkFixedToScalar(variations->axis[i].def);
1710 parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
1711 FT_UInt flags = 0;
1712 bool hidden = gFTLibrary->fGetVarAxisFlags &&
1713 !gFTLibrary->fGetVarAxisFlags(variations, i, &flags) &&
1714 (flags & FT_VAR_AXIS_FLAG_HIDDEN);
1715 parameters[i].setHidden(hidden);
1716 }
1717
1718 return variations->num_axis;
1719}
1720
bungeman@google.comddc218e2013-08-01 22:29:43 +00001721int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1722 AutoFTAccess fta(this);
1723 FT_Face face = fta.face();
1724
1725 FT_ULong tableCount = 0;
1726 FT_Error error;
1727
halcanary96fcdcc2015-08-27 07:41:13 -07001728 // When 'tag' is nullptr, returns number of tables in 'length'.
1729 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001730 if (error) {
1731 return 0;
1732 }
1733
1734 if (tags) {
1735 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1736 FT_ULong tableTag;
1737 FT_ULong tablelength;
1738 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1739 if (error) {
1740 return 0;
1741 }
1742 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1743 }
1744 }
1745 return tableCount;
1746}
1747
1748size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1749 size_t length, void* data) const
1750{
1751 AutoFTAccess fta(this);
1752 FT_Face face = fta.face();
1753
1754 FT_ULong tableLength = 0;
1755 FT_Error error;
1756
1757 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001758 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001759 if (error) {
1760 return 0;
1761 }
1762
1763 if (offset > tableLength) {
1764 return 0;
1765 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001766 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001767 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001768 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1769 if (error) {
1770 return 0;
1771 }
1772 }
1773
1774 return size;
1775}
1776
reed@google.comb4162b12013-07-02 16:32:29 +00001777///////////////////////////////////////////////////////////////////////////////
1778///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001779
halcanary96fcdcc2015-08-27 07:41:13 -07001780SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001781 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1782 return;
bungeman14df8332014-10-28 15:07:23 -07001783 }
bungeman9dc24682014-12-01 14:01:32 -08001784 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001785}
1786SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001787 if (fLibrary) {
1788 FT_Done_Library(fLibrary);
1789 }
bungeman14df8332014-10-28 15:07:23 -07001790}
1791
bungemanf93d7112016-09-16 06:24:20 -07001792FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001793 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001794{
halcanary96fcdcc2015-08-27 07:41:13 -07001795 if (fLibrary == nullptr) {
1796 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001797 }
1798
bungeman14df8332014-10-28 15:07:23 -07001799 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001800 memset(&args, 0, sizeof(args));
1801
1802 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001803
bsalomon49f085d2014-09-05 13:34:00 -07001804 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001805 args.flags = FT_OPEN_MEMORY;
1806 args.memory_base = (const FT_Byte*)memoryBase;
1807 args.memory_size = stream->getLength();
1808 } else {
bungeman14df8332014-10-28 15:07:23 -07001809 memset(ftStream, 0, sizeof(*ftStream));
1810 ftStream->size = stream->getLength();
1811 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001812 ftStream->read = sk_ft_stream_io;
1813 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001814
1815 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001816 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001817 }
1818
1819 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001820 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001821 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001822 }
1823 return face;
1824}
1825
bungemanf93d7112016-09-16 06:24:20 -07001826bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001827 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1828
1829 FT_StreamRec streamRec;
1830 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001831 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001832 return false;
1833 }
1834
1835 *numFaces = face->num_faces;
1836
1837 FT_Done_Face(face);
1838 return true;
1839}
1840
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001841#include "include/private/SkTSearch.h"
bungeman14df8332014-10-28 15:07:23 -07001842bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001843 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001844 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001845{
1846 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1847
1848 FT_StreamRec streamRec;
1849 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001850 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001851 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001852 }
1853
bungemana4c4a2d2014-10-20 13:33:19 -07001854 int weight = SkFontStyle::kNormal_Weight;
1855 int width = SkFontStyle::kNormal_Width;
1856 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001857 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001858 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001859 }
1860 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001861 slant = SkFontStyle::kItalic_Slant;
1862 }
1863
1864 PS_FontInfoRec psFontInfo;
1865 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1866 if (os2 && os2->version != 0xffff) {
1867 weight = os2->usWeightClass;
1868 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001869
1870 // OS/2::fsSelection bit 9 indicates oblique.
1871 if (SkToBool(os2->fsSelection & (1u << 9))) {
1872 slant = SkFontStyle::kOblique_Slant;
1873 }
bungemana4c4a2d2014-10-20 13:33:19 -07001874 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1875 static const struct {
1876 char const * const name;
1877 int const weight;
1878 } commonWeights [] = {
1879 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001880 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001881 { "black", SkFontStyle::kBlack_Weight },
1882 { "bold", SkFontStyle::kBold_Weight },
1883 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1884 { "demi", SkFontStyle::kSemiBold_Weight },
1885 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001886 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001887 { "extrabold", SkFontStyle::kExtraBold_Weight },
1888 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001889 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001890 { "heavy", SkFontStyle::kBlack_Weight },
1891 { "light", SkFontStyle::kLight_Weight },
1892 { "medium", SkFontStyle::kMedium_Weight },
1893 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001894 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001895 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001896 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001897 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001898 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001899 { "thin", SkFontStyle::kThin_Weight },
1900 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001901 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001902 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001903 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001904 { "ultralight", SkFontStyle::kExtraLight_Weight },
1905 };
1906 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001907 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001908 if (index >= 0) {
1909 weight = commonWeights[index].weight;
1910 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -05001911 LOG_INFO("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
bungemana4c4a2d2014-10-20 13:33:19 -07001912 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001913 }
1914
1915 if (name) {
1916 name->set(face->family_name);
1917 }
1918 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001919 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001920 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001921 if (isFixedPitch) {
1922 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001923 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001924
Bruce Wangebf0cf52018-06-18 14:04:19 -04001925 bool success = GetAxes(face, axes);
1926 FT_Done_Face(face);
1927 return success;
1928}
1929
1930bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
bungeman41868fe2015-05-20 09:21:04 -07001931 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001932 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001933 FT_Error err = FT_Get_MM_Var(face, &variations);
1934 if (err) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001935 LOG_INFO("INFO: font %s claims to have variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001936 face->family_name);
bungeman41868fe2015-05-20 09:21:04 -07001937 return false;
1938 }
1939 SkAutoFree autoFreeVariations(variations);
1940
1941 axes->reset(variations->num_axis);
1942 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1943 const FT_Var_Axis& ftAxis = variations->axis[i];
1944 (*axes)[i].fTag = ftAxis.tag;
1945 (*axes)[i].fMinimum = ftAxis.minimum;
1946 (*axes)[i].fDefault = ftAxis.def;
1947 (*axes)[i].fMaximum = ftAxis.maximum;
1948 }
1949 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001950 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001951}
bungemanf6c71072016-01-21 14:17:47 -08001952
1953/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1954 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001955 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001956 SkFixed* axisValues,
1957 const SkString& name)
1958{
1959 for (int i = 0; i < axisDefinitions.count(); ++i) {
1960 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001961 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1962 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001963 axisValues[i] = axisDefinition.fDefault;
bungeman9aec8942017-03-29 13:38:53 -04001964 // The position may be over specified. If there are multiple values for a given axis,
1965 // use the last one since that's what css-fonts-4 requires.
1966 for (int j = position.coordinateCount; j --> 0;) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001967 const auto& coordinate = position.coordinates[j];
1968 if (axisDefinition.fTag == coordinate.axis) {
1969 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1970 if (coordinate.value != axisValue) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001971 LOG_INFO("Requested font axis value out of range: "
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001972 "%s '%c%c%c%c' %f; pinned to %f.\n",
1973 name.c_str(),
1974 (axisDefinition.fTag >> 24) & 0xFF,
1975 (axisDefinition.fTag >> 16) & 0xFF,
1976 (axisDefinition.fTag >> 8) & 0xFF,
1977 (axisDefinition.fTag ) & 0xFF,
1978 SkScalarToDouble(coordinate.value),
1979 SkScalarToDouble(axisValue));
bungemanf6c71072016-01-21 14:17:47 -08001980 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001981 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001982 break;
1983 }
1984 }
1985 // TODO: warn on defaulted axis?
1986 }
1987
1988 SkDEBUGCODE(
1989 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001990 for (int i = 0; i < position.coordinateCount; ++i) {
1991 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001992 bool found = false;
1993 for (int j = 0; j < axisDefinitions.count(); ++j) {
1994 if (skTag == axisDefinitions[j].fTag) {
1995 found = true;
1996 break;
1997 }
1998 }
1999 if (!found) {
Mike Klein3e0141a2019-03-26 10:41:18 -05002000 LOG_INFO("Requested font axis not found: %s '%c%c%c%c'\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04002001 name.c_str(),
2002 (skTag >> 24) & 0xFF,
2003 (skTag >> 16) & 0xFF,
2004 (skTag >> 8) & 0xFF,
2005 (skTag) & 0xFF);
bungemanf6c71072016-01-21 14:17:47 -08002006 }
2007 }
2008 )
2009}