blob: 91801cdbd0be925d41b068c2d857422138c1026c [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +00008#include "SkAdvancedTypefaceMetrics.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +00009#include "SkBitmap.h"
10#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000011#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000012#include "SkDescriptor.h"
13#include "SkFDot6.h"
bungeman41868fe2015-05-20 09:21:04 -070014#include "SkFontDescriptor.h"
george@mozilla.comc59b5da2012-08-23 00:39:08 +000015#include "SkFontHost_FreeType_common.h"
bungeman@google.combbe50132012-07-24 20:33:21 +000016#include "SkGlyph.h"
bungeman7cfd46a2016-10-20 16:06:52 -040017#include "SkMakeUnique.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000018#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000019#include "SkMaskGamma.h"
bungeman@google.comd3fbd342014-04-15 15:52:07 +000020#include "SkMatrix22.h"
Herb Derbyb549cc32017-03-27 13:35:15 -040021#include "SkMalloc.h"
mtklein1b249332015-07-07 12:21:21 -070022#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000023#include "SkOTUtils.h"
bungemand3ebb482015-08-05 13:57:49 -070024#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000025#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000026#include "SkStream.h"
27#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000028#include "SkTemplates.h"
mtklein5f939ab2016-03-16 10:28:35 -070029#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000030
31#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080032#include FT_ADVANCES_H
33#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000034#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080035#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080036#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070037#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000038#include FT_OUTLINE_H
39#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080040#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000041#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000042#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000043#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000044
Ben Wagnerfc497342017-02-24 11:15:26 -050045// SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
46// Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
47#define SK_FREETYPE_DLOPEN (0x1)
48#ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
49# if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (GOOGLE3)
50# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
51# else
52# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
53# endif
54#endif
55#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
56# include <dlfcn.h>
57#endif
58
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000059// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
60// were introduced in FreeType 2.5.0.
61// The following may be removed once FreeType 2.5.0 is required to build.
62#ifndef FT_LOAD_COLOR
63# define FT_LOAD_COLOR ( 1L << 20 )
64# define FT_PIXEL_MODE_BGRA 7
65#endif
66
Seigo Nonaka52ab2f52016-12-05 02:41:53 +090067// FT_LOAD_BITMAP_METRICS_ONLY was introduced in FreeType 2.7.1
68// The following may be removed once FreeType 2.7.1 is required to build.
69#ifndef FT_LOAD_BITMAP_METRICS_ONLY
70# define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
71#endif
72
reed@android.com8a1c16f2008-12-17 15:59:43 +000073//#define ENABLE_GLYPH_SPEW // for tracing calls
74//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080075//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000076//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000077
reed@google.comeffc5012011-06-27 16:44:46 +000078static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080079 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000080}
81
reed@android.com8a1c16f2008-12-17 15:59:43 +000082//////////////////////////////////////////////////////////////////////////
83
bungeman9dc24682014-12-01 14:01:32 -080084extern "C" {
85 static void* sk_ft_alloc(FT_Memory, long size) {
86 return sk_malloc_throw(size);
87 }
88 static void sk_ft_free(FT_Memory, void* block) {
89 sk_free(block);
90 }
91 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
92 return sk_realloc_throw(block, new_size);
93 }
94};
halcanary96fcdcc2015-08-27 07:41:13 -070095FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -080096
97class FreeTypeLibrary : SkNoncopyable {
98public:
Ben Wagnerfc497342017-02-24 11:15:26 -050099 FreeTypeLibrary()
100 : fGetVarDesignCoordinates(nullptr)
101 , fLibrary(nullptr)
102 , fIsLCDSupported(false)
103 , fLCDExtra(0)
104 {
bungeman9dc24682014-12-01 14:01:32 -0800105 if (FT_New_Library(&gFTMemory, &fLibrary)) {
106 return;
107 }
108 FT_Add_Default_Modules(fLibrary);
109
Ben Wagner2a098d02017-03-01 13:00:53 -0500110 // When using dlsym
111 // *(void**)(&procPtr) = dlsym(self, "proc");
112 // is non-standard, but safe for POSIX. Cannot write
113 // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
114 // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
115
116 FT_Int major, minor, patch;
117 FT_Library_Version(fLibrary, &major, &minor, &patch);
118
Ben Wagnerfc497342017-02-24 11:15:26 -0500119#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
120 fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
121#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
Ben Wagner2a098d02017-03-01 13:00:53 -0500122 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500123 //The FreeType library is already loaded, so symbols are available in process.
124 void* self = dlopen(nullptr, RTLD_LAZY);
125 if (self) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500126 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
127 dlclose(self);
128 }
129 }
130#endif
131
Ben Wagner2a098d02017-03-01 13:00:53 -0500132#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
133 FT_Set_Default_Properties(fLibrary);
134#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
135 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
bungeman9dc24682014-12-01 14:01:32 -0800136 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700137 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800138 if (self) {
Ben Wagner2a098d02017-03-01 13:00:53 -0500139 FT_Set_Default_PropertiesProc setDefaultProperties;
140 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
bungeman9dc24682014-12-01 14:01:32 -0800141 dlclose(self);
142
Ben Wagner2a098d02017-03-01 13:00:53 -0500143 if (setDefaultProperties) {
144 setDefaultProperties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800145 }
146 }
Ben Wagner2a098d02017-03-01 13:00:53 -0500147 }
bungeman9dc24682014-12-01 14:01:32 -0800148#endif
Ben Wagner2a098d02017-03-01 13:00:53 -0500149
150 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
151 // The default has changed over time, so this doesn't mean the same thing to all users.
152 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
153 fIsLCDSupported = true;
154 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
bungeman9dc24682014-12-01 14:01:32 -0800155 }
156 }
157 ~FreeTypeLibrary() {
158 if (fLibrary) {
159 FT_Done_Library(fLibrary);
160 }
161 }
162
163 FT_Library library() { return fLibrary; }
164 bool isLCDSupported() { return fIsLCDSupported; }
165 int lcdExtra() { return fLCDExtra; }
166
Ben Wagnerfc497342017-02-24 11:15:26 -0500167 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
168 // Prior to this there was no way to get the coordinates out of the FT_Face.
169 // This wasn't too bad because you needed to specify them anyway, and the clamp was provided.
170 // However, this doesn't work when face_index specifies named variations as introduced in 2.6.1.
171 using FT_Get_Var_Blend_CoordinatesProc = FT_Error (*)(FT_Face, FT_UInt, FT_Fixed*);
172 FT_Get_Var_Blend_CoordinatesProc fGetVarDesignCoordinates;
173
bungeman9dc24682014-12-01 14:01:32 -0800174private:
175 FT_Library fLibrary;
176 bool fIsLCDSupported;
177 int fLCDExtra;
178
179 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
180 // The following platforms provide FreeType of at least 2.4.0.
181 // Ubuntu >= 11.04 (previous deprecated April 2013)
182 // Debian >= 6.0 (good)
183 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
184 // Fedora >= 14 (good)
185 // Android >= Gingerbread (good)
Ben Wagnerfc497342017-02-24 11:15:26 -0500186 // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
187 using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
Ben Wagner2a098d02017-03-01 13:00:53 -0500188
189 // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
190 // of FT_New_Library to request these global properties to be read was added.
191 using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
bungeman9dc24682014-12-01 14:01:32 -0800192};
193
reed@android.com8a1c16f2008-12-17 15:59:43 +0000194struct SkFaceRec;
195
reed086eea92016-05-04 17:12:46 -0700196SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800197static FreeTypeLibrary* gFTLibrary;
198static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000199
bungemanaabd71c2016-03-01 15:15:09 -0800200// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800201static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000202
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000203// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800204static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800205 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800206 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800207
bungeman9dc24682014-12-01 14:01:32 -0800208 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700209 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700210 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000211 }
bungeman9dc24682014-12-01 14:01:32 -0800212 ++gFTCount;
213 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000214}
215
bungeman9dc24682014-12-01 14:01:32 -0800216// Caller must lock gFTMutex before calling this function.
217static void unref_ft_library() {
218 gFTMutex.assertHeld();
219 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000220
bungeman9dc24682014-12-01 14:01:32 -0800221 --gFTCount;
222 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800223 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700224 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700225 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700226 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800227 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000228}
229
Ben Wagnerfc497342017-02-24 11:15:26 -0500230///////////////////////////////////////////////////////////////////////////
231
232struct SkFaceRec {
233 SkFaceRec* fNext;
234 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
235 FT_StreamRec fFTStream;
236 std::unique_ptr<SkStreamAsset> fSkStream;
237 uint32_t fRefCnt;
238 uint32_t fFontID;
239
240 // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
241 // Cache the variation design metrics used to create the font if the user specifies them.
242 SkAutoSTMalloc<4, SkFixed> fAxes;
243 int fAxesCount;
244
245 // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
246 // and named variation index on input, but masks the named variation index part on output.
247 // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
248 bool fNamedVariationSpecified;
249
250 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
251};
252
253extern "C" {
254 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
255 unsigned long offset,
256 unsigned char* buffer,
257 unsigned long count)
258 {
259 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
260
261 if (count) {
262 if (!stream->seek(offset)) {
263 return 0;
264 }
265 count = stream->read(buffer, count);
266 }
267 return count;
268 }
269
270 static void sk_ft_stream_close(FT_Stream) {}
271}
272
273SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
274 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
275 , fAxesCount(0), fNamedVariationSpecified(false)
276{
277 sk_bzero(&fFTStream, sizeof(fFTStream));
278 fFTStream.size = fSkStream->getLength();
279 fFTStream.descriptor.pointer = fSkStream.get();
280 fFTStream.read = sk_ft_stream_io;
281 fFTStream.close = sk_ft_stream_close;
282}
283
284static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
285 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
286 return;
287 }
288
289 // If a named variation is requested, don't overwrite the named variation's position.
290 if (data.getIndex() > 0xFFFF) {
291 rec->fNamedVariationSpecified = true;
292 return;
293 }
294
295 SkDEBUGCODE(
296 FT_MM_Var* variations = nullptr;
297 if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
298 SkDEBUGF(("INFO: font %s claims variations, but none found.\n",
299 rec->fFace->family_name));
300 return;
301 }
302 SkAutoFree autoFreeVariations(variations);
303
304 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
305 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
306 rec->fFace->family_name, variations->num_axis, data.getAxisCount()));
307 return;
308 }
309 )
310
311 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
312 for (int i = 0; i < data.getAxisCount(); ++i) {
313 coords[i] = data.getAxis()[i];
314 }
315 if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
316 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
317 rec->fFace->family_name));
318 return;
319 }
320
321 rec->fAxesCount = data.getAxisCount();
322 rec->fAxes.reset(rec->fAxesCount);
323 for (int i = 0; i < rec->fAxesCount; ++i) {
324 rec->fAxes[i] = data.getAxis()[i];
325 }
326}
327
328// Will return nullptr on failure
329// Caller must lock gFTMutex before calling this function.
330static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
331 gFTMutex.assertHeld();
332
333 const SkFontID fontID = typeface->uniqueID();
334 SkFaceRec* cachedRec = gFaceRecHead;
335 while (cachedRec) {
336 if (cachedRec->fFontID == fontID) {
337 SkASSERT(cachedRec->fFace);
338 cachedRec->fRefCnt += 1;
339 return cachedRec;
340 }
341 cachedRec = cachedRec->fNext;
342 }
343
344 std::unique_ptr<SkFontData> data = typeface->makeFontData();
345 if (nullptr == data || !data->hasStream()) {
346 return nullptr;
347 }
348
349 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
350
351 FT_Open_Args args;
352 memset(&args, 0, sizeof(args));
353 const void* memoryBase = rec->fSkStream->getMemoryBase();
354 if (memoryBase) {
355 args.flags = FT_OPEN_MEMORY;
356 args.memory_base = (const FT_Byte*)memoryBase;
357 args.memory_size = rec->fSkStream->getLength();
358 } else {
359 args.flags = FT_OPEN_STREAM;
360 args.stream = &rec->fFTStream;
361 }
362
363 {
364 FT_Face rawFace;
365 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
366 if (err) {
367 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
368 return nullptr;
369 }
370 rec->fFace.reset(rawFace);
371 }
372 SkASSERT(rec->fFace);
373
374 ft_face_setup_axes(rec.get(), *data);
375
376 // FreeType will set the charmap to the "most unicode" cmap if it exists.
377 // If there are no unicode cmaps, the charmap is set to nullptr.
378 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
379 // because they are effectively private use area only (even if they aren't).
380 // This is the last on the fallback list at
381 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
382 if (!rec->fFace->charmap) {
383 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
384 }
385
386 rec->fNext = gFaceRecHead;
387 gFaceRecHead = rec.get();
388 return rec.release();
389}
390
391// Caller must lock gFTMutex before calling this function.
Ben Wagnerf1b61af2017-03-09 15:12:09 -0500392// Marked extern because vc++ does not support internal linkage template parameters.
393extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500394 gFTMutex.assertHeld();
395
396 SkFaceRec* rec = gFaceRecHead;
397 SkFaceRec* prev = nullptr;
398 while (rec) {
399 SkFaceRec* next = rec->fNext;
400 if (rec->fFace == faceRec->fFace) {
401 if (--rec->fRefCnt == 0) {
402 if (prev) {
403 prev->fNext = next;
404 } else {
405 gFaceRecHead = next;
406 }
407 delete rec;
408 }
409 return;
410 }
411 prev = rec;
412 rec = next;
413 }
414 SkDEBUGFAIL("shouldn't get here, face not in list");
415}
416
417class AutoFTAccess {
418public:
419 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
420 gFTMutex.acquire();
421 if (!ref_ft_library()) {
422 sk_throw();
423 }
424 fFaceRec = ref_ft_face(tf);
425 }
426
427 ~AutoFTAccess() {
428 if (fFaceRec) {
429 unref_ft_face(fFaceRec);
430 }
431 unref_ft_library();
432 gFTMutex.release();
433 }
434
435 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
436 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
437 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
438 bool isNamedVariationSpecified() {
439 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
440 }
441
442private:
443 SkFaceRec* fFaceRec;
444};
445
446///////////////////////////////////////////////////////////////////////////
447
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000448class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000449public:
bungeman7cfd46a2016-10-20 16:06:52 -0400450 SkScalerContext_FreeType(sk_sp<SkTypeface>,
451 const SkScalerContextEffects&,
452 const SkDescriptor* desc);
Brian Salomond3b65972017-03-22 12:05:03 -0400453 ~SkScalerContext_FreeType() override;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000454
reed@android.com62900b42009-02-11 15:07:19 +0000455 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700456 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000457 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000458
459protected:
mtklein36352bf2015-03-25 18:17:31 -0700460 unsigned generateGlyphCount() override;
461 uint16_t generateCharToGlyph(SkUnichar uni) override;
462 void generateAdvance(SkGlyph* glyph) override;
463 void generateMetrics(SkGlyph* glyph) override;
464 void generateImage(const SkGlyph& glyph) override;
Ben Wagner6e9ac122016-11-11 14:31:06 -0500465 void generatePath(SkGlyphID glyphID, SkPath* path) override;
mtklein36352bf2015-03-25 18:17:31 -0700466 void generateFontMetrics(SkPaint::FontMetrics*) override;
467 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000468
469private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500470 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
471 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
472
473 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700474 FT_Size fFTSize; // The size on the fFace for this scaler.
475 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000476
bungeman401ae2d2016-07-18 15:46:27 -0700477 /** The rest of the matrix after FreeType handles the size.
478 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
479 * With bitmap only fonts this matrix must be applied to scale the bitmap.
480 */
481 SkMatrix fMatrix22Scalar;
482 /** Same as fMatrix22Scalar, but in FreeType units and space. */
483 FT_Matrix fMatrix22;
484 /** The actual size requested. */
485 SkVector fScale;
486
487 uint32_t fLoadGlyphFlags;
488 bool fDoLinearMetrics;
489 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000490
reed@android.com8a1c16f2008-12-17 15:59:43 +0000491 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000492 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
493 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000494 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000495 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000496 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000497 // Caller must lock gFTMutex before calling this function.
498 // update FreeType2 glyph slot with glyph emboldened
499 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
bungeman401ae2d2016-07-18 15:46:27 -0700500 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000501};
502
503///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000504
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000505static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000506 FT_UShort fsType = FT_Get_FSType_Flags(face);
507 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
508 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000509}
510
vandebo0f9bad02014-06-19 11:05:39 -0700511static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700512 FT_UShort fsType = FT_Get_FSType_Flags(face);
513 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700514}
515
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000516static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
517 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
518 if (!glyph_id)
519 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000520 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
521 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000522 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
523 return true;
524}
525
bungeman5ec443c2014-11-21 13:18:34 -0800526static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
halcanaryf8c74a12016-04-20 08:37:43 -0700527 FT_Long numGlyphs = face->num_glyphs;
528 glyphToUnicode->setCount(SkToInt(numGlyphs));
529 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000530
bungeman726cf902015-06-05 13:38:12 -0700531 FT_UInt glyphIndex;
532 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
533 while (glyphIndex) {
halcanaryf8c74a12016-04-20 08:37:43 -0700534 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
halcanary5f1d0f62016-09-13 08:08:38 -0700535 // Use the first character that maps to this glyphID. https://crbug.com/359065
536 if (0 == (*glyphToUnicode)[glyphIndex]) {
537 (*glyphToUnicode)[glyphIndex] = charCode;
538 }
bungeman726cf902015-06-05 13:38:12 -0700539 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000540 }
541}
542
reed@google.com2689f612013-03-20 20:01:47 +0000543SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700544 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000545 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000546 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000547 AutoFTAccess fta(this);
548 FT_Face face = fta.face();
549 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700550 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000551 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000552
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000553 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
554 info->fFontName.set(FT_Get_Postscript_Name(face));
halcanary32875882016-08-16 09:36:23 -0700555
vandebo0f9bad02014-06-19 11:05:39 -0700556 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700557 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700558 }
559 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700560 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700561 }
562 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700563 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700564 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000565
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000566 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000567 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000568 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000569 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000570 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000571 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000572 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000573 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000574 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
bungeman@google.com4d71db82013-12-02 19:10:02 +0000575 } else {
576 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000577 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000578
halcanary32875882016-08-16 09:36:23 -0700579 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700580 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000581 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700582 }
583 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000584 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700585 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000586
bungemanf1491692016-07-22 11:19:24 -0700587 PS_FontInfoRec psFontInfo;
588 TT_Postscript* postTable;
589 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
590 info->fItalicAngle = psFontInfo.italic_angle;
591 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
592 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000593 } else {
594 info->fItalicAngle = 0;
595 }
596
597 info->fAscent = face->ascender;
598 info->fDescent = face->descender;
599
600 // Figure out a good guess for StemV - Min width of i, I, !, 1.
601 // This probably isn't very good with an italic font.
602 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000603 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000604 char stem_chars[] = {'i', 'I', '!', '1'};
605 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
606 FT_BBox bbox;
607 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
608 int16_t width = bbox.xMax - bbox.xMin;
609 if (width > 0 && width < min_width) {
610 min_width = width;
611 info->fStemV = min_width;
612 }
613 }
614 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000615
bungemanf1491692016-07-22 11:19:24 -0700616 TT_PCLT* pcltTable;
617 TT_OS2* os2Table;
618 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
619 info->fCapHeight = pcltTable->CapHeight;
620 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
621 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000622 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700623 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000624 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700625 }
626 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000627 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700628 os2Table->version != 0xFFFF &&
629 os2Table->version >= 2)
630 {
631 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000632 } else {
633 // Figure out a good guess for CapHeight: average the height of M and X.
634 FT_BBox m_bbox, x_bbox;
635 bool got_m, got_x;
636 got_m = GetLetterCBox(face, 'M', &m_bbox);
637 got_x = GetLetterCBox(face, 'X', &x_bbox);
638 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700639 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000640 } else if (got_m && !got_x) {
641 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
642 } else if (!got_m && got_x) {
643 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000644 } else {
645 // Last resort, use the ascent.
646 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000647 }
648 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000649
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000650 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
651 face->bbox.xMax, face->bbox.yMin);
652
vandebo0f9bad02014-06-19 11:05:39 -0700653 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700654 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000655 }
656
reed39a9a502015-05-12 09:50:04 -0700657 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700658 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
659 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000660 // Postscript fonts may contain more than 255 glyphs, so we end up
661 // using multiple font descriptions with a glyph ordering. Record
662 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700663 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000664 for (int gID = 0; gID < face->num_glyphs; gID++) {
665 char glyphName[128]; // PS limit for names is 127 bytes.
666 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700667 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000668 }
669 }
670
reed39a9a502015-05-12 09:50:04 -0700671 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700672 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
673 face->num_charmaps)
674 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000675 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
676 }
677
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000678 return info;
679}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000680
reed@google.com618ef5e2011-01-26 22:10:41 +0000681///////////////////////////////////////////////////////////////////////////
682
reed@google.com8ed436c2011-07-21 14:12:36 +0000683static bool bothZero(SkScalar a, SkScalar b) {
684 return 0 == a && 0 == b;
685}
686
687// returns false if there is any non-90-rotation or skew
688static bool isAxisAligned(const SkScalerContext::Rec& rec) {
689 return 0 == rec.fPreSkewX &&
690 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
691 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
692}
693
reeda9322c22016-04-12 06:47:05 -0700694SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
695 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400696 auto c = skstd::make_unique<SkScalerContext_FreeType>(
697 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000698 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400699 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000700 }
bungeman7cfd46a2016-10-20 16:06:52 -0400701 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000702}
703
704void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000705 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
706 //Cap the requested size as larger sizes give bogus values.
707 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800708 //Note that this also currently only protects against large text size requests,
709 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000710 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000711 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000712 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000713
bungemanec7e12f2015-01-21 11:55:16 -0800714 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800715 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
716 SkAutoMutexAcquire ama(gFTMutex);
717 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800718 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800719 // If the runtime Freetype library doesn't support LCD, disable it here.
720 rec->fMaskFormat = SkMask::kA8_Format;
721 }
722 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000723 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000724
reed@google.com618ef5e2011-01-26 22:10:41 +0000725 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000726 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000727 // collapse full->normal hinting if we're not doing LCD
728 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000729 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000730 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000731 if (SkPaint::kNo_Hinting != h) {
732 h = SkPaint::kSlight_Hinting;
733 }
734 }
735
reed@google.com8ed436c2011-07-21 14:12:36 +0000736 // rotated text looks bad with hinting, so we disable it as needed
737 if (!isAxisAligned(*rec)) {
738 h = SkPaint::kNo_Hinting;
739 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000740 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000741
bungeman@google.com97efada2012-07-30 20:40:50 +0000742#ifndef SK_GAMMA_APPLY_TO_A8
743 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700744 // SRGBTODO: Is this correct? Do we want contrast boost?
745 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000746 }
reed@google.com1ac83502012-02-28 17:06:02 +0000747#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000748}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000749
reed@google.com38c37dd2013-03-21 15:36:26 +0000750int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000751 AutoFTAccess fta(this);
752 FT_Face face = fta.face();
753 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000754}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000755
reed@google.com35fe7372013-10-30 15:07:03 +0000756bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
757 int count, int32_t adjustments[]) const {
758 AutoFTAccess fta(this);
759 FT_Face face = fta.face();
760 if (!face || !FT_HAS_KERNING(face)) {
761 return false;
762 }
763
764 for (int i = 0; i < count - 1; ++i) {
765 FT_Vector delta;
766 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
767 FT_KERNING_UNSCALED, &delta);
768 if (err) {
769 return false;
770 }
771 adjustments[i] = delta.x;
772 }
773 return true;
774}
775
bungeman401ae2d2016-07-18 15:46:27 -0700776/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800777static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700778 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700779 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000780 return -1;
781 }
bungeman401ae2d2016-07-18 15:46:27 -0700782
783 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000784 FT_Int chosenStrikeIndex = -1;
785 FT_Pos chosenPPEM = 0;
786 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700787 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
788 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000789 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700790 return strikeIndex;
791 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000792 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700793 if (chosenPPEM < strikePPEM) {
794 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000795 chosenStrikeIndex = strikeIndex;
796 }
797 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700798 // attempt to decrease chosenPPEM, but not below requestedPPEM
799 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
800 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000801 chosenStrikeIndex = strikeIndex;
802 }
803 }
804 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000805 return chosenStrikeIndex;
806}
807
bungeman7cfd46a2016-10-20 16:06:52 -0400808SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700809 const SkScalerContextEffects& effects,
810 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400811 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800812 , fFace(nullptr)
813 , fFTSize(nullptr)
814 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700815{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000816 SkAutoMutexAcquire ac(gFTMutex);
817
bungeman9dc24682014-12-01 14:01:32 -0800818 if (!ref_ft_library()) {
819 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000821
Ben Wagnerfc497342017-02-24 11:15:26 -0500822 fFaceRec.reset(ref_ft_face(this->getTypeface()));
823
reed@android.com8a1c16f2008-12-17 15:59:43 +0000824 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500825 if (nullptr == fFaceRec) {
bungemanaabd71c2016-03-01 15:15:09 -0800826 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000827 return;
828 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000829
bungeman5f14c5e2014-12-05 12:26:44 -0800830 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000831
bungeman401ae2d2016-07-18 15:46:27 -0700832 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
833 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000834 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700835 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
836 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000837 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000838
reed@google.coma1bfa212012-03-08 21:57:12 +0000839 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
840
reed@android.com8a1c16f2008-12-17 15:59:43 +0000841 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000842 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000843 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000844 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000845
agl@chromium.org70a303f2010-05-10 14:15:50 +0000846 if (SkMask::kBW_Format == fRec.fMaskFormat) {
847 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
848 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000849 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000850 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000851 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000852 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000853 } else {
854 switch (fRec.getHinting()) {
855 case SkPaint::kNo_Hinting:
856 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000857 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000858 break;
859 case SkPaint::kSlight_Hinting:
860 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
861 break;
862 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000863 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000864 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700865#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
866 } else {
867 loadFlags = FT_LOAD_NO_AUTOHINT;
868#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000869 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000870 break;
871 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000872 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000873 loadFlags = FT_LOAD_FORCE_AUTOHINT;
874 break;
875 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000876 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000877 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000878 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000879 loadFlags = FT_LOAD_TARGET_LCD_V;
880 } else {
881 loadFlags = FT_LOAD_TARGET_LCD;
882 }
reed@google.comea2333d2011-03-14 16:44:56 +0000883 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000884 break;
885 default:
886 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
887 break;
888 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000889 }
890
reed@google.comeffc5012011-06-27 16:44:46 +0000891 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000892 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000893 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000894
reed@google.com96a9f7912011-05-06 11:49:30 +0000895 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
896 // advances, as fontconfig and cairo do.
897 // See http://code.google.com/p/skia/issues/detail?id=222.
898 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
899
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000900 // Use vertical layout if requested.
901 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
902 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
903 }
904
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000905 loadFlags |= FT_LOAD_COLOR;
906
reed@android.come4d0bc02009-07-24 19:53:20 +0000907 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000908 }
909
bungemanaabd71c2016-03-01 15:15:09 -0800910 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500911 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800912 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500913 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800914 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500915 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800916 return nullptr;
917 }
918 return size;
919 }());
920 if (nullptr == ftSize) {
921 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000922 return;
923 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000924
bungemanaabd71c2016-03-01 15:15:09 -0800925 FT_Error err = FT_Activate_Size(ftSize.get());
926 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500927 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800928 return;
929 }
930
Ben Wagnerfc497342017-02-24 11:15:26 -0500931 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
932 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000933 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700934 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500935 fFaceRec->fFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000936 return;
937 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500938 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
939 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000940 if (fStrikeIndex == -1) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500941 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n",
942 fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700943 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944 }
bungeman401ae2d2016-07-18 15:46:27 -0700945
Ben Wagnerfc497342017-02-24 11:15:26 -0500946 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700947 if (err != 0) {
948 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500949 fFaceRec->fFace->family_name, fStrikeIndex, err));
bungeman401ae2d2016-07-18 15:46:27 -0700950 fStrikeIndex = -1;
951 return;
952 }
953
954 // A non-ideal size was picked, so recompute the matrix.
955 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
Ben Wagnerfc497342017-02-24 11:15:26 -0500956 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
957 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700958 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
959 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
960 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
961 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
962
963 // FreeType does not provide linear metrics for bitmap fonts.
964 linearMetrics = false;
965
966 // FreeType documentation says:
967 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
968 // Bitmap-only fonts ignore this flag.
969 //
970 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
971 // Force this flag off for bitmap only fonts.
972 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000973 } else {
Ben Wagnerfc497342017-02-24 11:15:26 -0500974 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700975 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000976 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000977
bungemanaabd71c2016-03-01 15:15:09 -0800978 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500979 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000980 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000981}
982
983SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000984 SkAutoMutexAcquire ac(gFTMutex);
985
halcanary96fcdcc2015-08-27 07:41:13 -0700986 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000987 FT_Done_Size(fFTSize);
988 }
989
Ben Wagnerfc497342017-02-24 11:15:26 -0500990 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -0800991
992 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000993}
994
995/* We call this before each use of the fFace, since we may be sharing
996 this face with other context (at different sizes).
997*/
998FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800999 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001000 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001001 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001002 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001003 }
halcanary96fcdcc2015-08-27 07:41:13 -07001004 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001005 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006}
1007
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001008unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001009 return fFace->num_glyphs;
1010}
1011
1012uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -08001013 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001014 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1015}
1016
reed@android.com9d3a9852010-01-08 14:07:42 +00001017SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -08001018 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +00001019 // iterate through each cmap entry, looking for matching glyph indices
1020 FT_UInt glyphIndex;
1021 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1022
1023 while (glyphIndex != 0) {
1024 if (glyphIndex == glyph) {
1025 return charCode;
1026 }
1027 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1028 }
1029
1030 return 0;
1031}
1032
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001033static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
1034 return SkFixedToScalar(x);
1035}
1036
reed@android.com8a1c16f2008-12-17 15:59:43 +00001037void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001038 /* unhinted and light hinted text have linearly scaled advances
1039 * which are very cheap to compute with some font formats...
1040 */
reed@google.combdc99882011-11-21 14:36:57 +00001041 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001042 SkAutoMutexAcquire ac(gFTMutex);
1043
1044 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001045 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001046 return;
1047 }
1048
1049 FT_Error error;
1050 FT_Fixed advance;
1051
djsollen1b277042014-08-06 06:58:06 -07001052 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001053 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1054 &advance );
1055 if (0 == error) {
1056 glyph->fRsbDelta = 0;
1057 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001058 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1059 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001060 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001061 return;
1062 }
1063 }
bungeman5ec443c2014-11-21 13:18:34 -08001064
reed@android.com8a1c16f2008-12-17 15:59:43 +00001065 /* otherwise, we need to load/hint the glyph, which is slower */
1066 this->generateMetrics(glyph);
1067 return;
1068}
1069
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001070void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1071 FT_BBox* bbox,
1072 bool snapToPixelBoundary) {
1073
1074 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1075
1076 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001077 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1078 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001079 // negate dy since freetype-y-goes-up and skia-y-goes-down
1080 bbox->xMin += dx;
1081 bbox->yMin -= dy;
1082 bbox->xMax += dx;
1083 bbox->yMax -= dy;
1084 }
1085
1086 // outset the box to integral boundaries
1087 if (snapToPixelBoundary) {
1088 bbox->xMin &= ~63;
1089 bbox->yMin &= ~63;
1090 bbox->xMax = (bbox->xMax + 63) & ~63;
1091 bbox->yMax = (bbox->yMax + 63) & ~63;
1092 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001093
1094 // Must come after snapToPixelBoundary so that the width and height are
1095 // consistent. Otherwise asserts will fire later on when generating the
1096 // glyph image.
1097 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1098 FT_Vector vector;
1099 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1100 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1101 FT_Vector_Transform(&vector, &fMatrix22);
1102 bbox->xMin += vector.x;
1103 bbox->xMax += vector.x;
1104 bbox->yMin += vector.y;
1105 bbox->yMax += vector.y;
1106 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001107}
1108
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001109bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1110 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001111 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001112 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001113 }
1114 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001115 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001116 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001117 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001118 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1119 return true;
1120}
1121
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001122void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1123 if (isLCD(fRec)) {
1124 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001125 glyph->fHeight += gFTLibrary->lcdExtra();
1126 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001127 } else {
bungeman9dc24682014-12-01 14:01:32 -08001128 glyph->fWidth += gFTLibrary->lcdExtra();
1129 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001130 }
1131 }
1132}
1133
bungeman401ae2d2016-07-18 15:46:27 -07001134bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1135 // If subpixel rendering of a bitmap *can* be done.
1136 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1137 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1138 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001139
bungeman401ae2d2016-07-18 15:46:27 -07001140 // If subpixel rendering of a bitmap *should* be done.
1141 // 1. If the face is not scalable then always allow subpixel rendering.
1142 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1143 // 2. If the matrix is already not identity the bitmap will already be resampled,
1144 // so resampling slightly differently shouldn't make much difference.
1145 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1146
1147 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001148}
1149
reed@android.com8a1c16f2008-12-17 15:59:43 +00001150void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1151 SkAutoMutexAcquire ac(gFTMutex);
1152
1153 glyph->fRsbDelta = 0;
1154 glyph->fLsbDelta = 0;
1155
1156 FT_Error err;
1157
1158 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001159 glyph->zeroMetrics();
1160 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001161 }
1162
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001163 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1164 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001165 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001166 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001167 return;
1168 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001169 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001170
1171 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001172 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001173 if (0 == fFace->glyph->outline.n_contours) {
1174 glyph->fWidth = 0;
1175 glyph->fHeight = 0;
1176 glyph->fTop = 0;
1177 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001178 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001179 FT_BBox bbox;
1180 getBBoxForCurrentGlyph(glyph, &bbox, true);
1181
1182 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1183 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1184 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1185 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1186
1187 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001188 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001189 break;
1190
1191 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001192 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1193 FT_Vector vector;
1194 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1195 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1196 FT_Vector_Transform(&vector, &fMatrix22);
1197 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1198 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1199 }
1200
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001201 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1202 glyph->fMaskFormat = SkMask::kARGB32_Format;
1203 }
1204
bungeman401ae2d2016-07-18 15:46:27 -07001205 {
1206 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1207 -SkIntToScalar(fFace->glyph->bitmap_top),
1208 SkIntToScalar(fFace->glyph->bitmap.width),
1209 SkIntToScalar(fFace->glyph->bitmap.rows));
1210 fMatrix22Scalar.mapRect(&rect);
1211 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1212 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1213 SkFixedToScalar(glyph->getSubYFixed()));
1214 }
1215 SkIRect irect = rect.roundOut();
1216 glyph->fWidth = SkToU16(irect.width());
1217 glyph->fHeight = SkToU16(irect.height());
1218 glyph->fTop = SkToS16(irect.top());
1219 glyph->fLeft = SkToS16(irect.left());
1220 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001221 break;
1222
1223 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001224 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001225 glyph->zeroMetrics();
1226 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001227 }
1228
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001229 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1230 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001231 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001232 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001233 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001234 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001235 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1236 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001237 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001238 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001239 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001240 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1241 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001242 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001243 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001244 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1245 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001246
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001247 if (fRec.fFlags & kDevKernText_Flag) {
1248 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1249 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001250 }
1251 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001252 }
1253
reed@android.com8a1c16f2008-12-17 15:59:43 +00001254#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001255 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001256#endif
1257}
1258
bungeman5ec443c2014-11-21 13:18:34 -08001259static void clear_glyph_image(const SkGlyph& glyph) {
1260 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1261}
reed@google.comea2333d2011-03-14 16:44:56 +00001262
bungeman@google.coma76de722012-10-26 19:35:54 +00001263void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001264 SkAutoMutexAcquire ac(gFTMutex);
1265
reed@android.com8a1c16f2008-12-17 15:59:43 +00001266 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001267 clear_glyph_image(glyph);
1268 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001269 }
1270
bungeman5ec443c2014-11-21 13:18:34 -08001271 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001272 if (err != 0) {
1273 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
bungeman5ec443c2014-11-21 13:18:34 -08001274 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1275 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001276 return;
1277 }
1278
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001279 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001280 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1281 SkMatrix subpixelBitmapMatrix;
1282 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1283 subpixelBitmapMatrix = fMatrix22Scalar;
1284 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1285 SkFixedToScalar(glyph.getSubYFixed()));
1286 bitmapMatrix = &subpixelBitmapMatrix;
1287 }
1288 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001289}
1290
reed@android.com8a1c16f2008-12-17 15:59:43 +00001291
Ben Wagner6e9ac122016-11-11 14:31:06 -05001292void SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001293 SkAutoMutexAcquire ac(gFTMutex);
1294
caryclarka10742c2014-09-18 11:00:40 -07001295 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001296
1297 if (this->setupSize()) {
1298 path->reset();
1299 return;
1300 }
1301
1302 uint32_t flags = fLoadGlyphFlags;
1303 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1304 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1305
Ben Wagner6e9ac122016-11-11 14:31:06 -05001306 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001307
1308 if (err != 0) {
1309 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
Ben Wagner6e9ac122016-11-11 14:31:06 -05001310 glyphID, flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001311 path->reset();
1312 return;
1313 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001314 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001315
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001316 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001317
1318 // The path's origin from FreeType is always the horizontal layout origin.
1319 // Offset the path so that it is relative to the vertical origin if needed.
1320 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1321 FT_Vector vector;
1322 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1323 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1324 FT_Vector_Transform(&vector, &fMatrix22);
1325 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1326 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001327}
1328
bungeman41078062014-07-07 08:16:37 -07001329void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001330 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001331 return;
1332 }
1333
bungeman41078062014-07-07 08:16:37 -07001334 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001335
1336 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001337 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001338 return;
1339 }
1340
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001341 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001342
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001343 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1344 SkScalar upem = SkIntToScalar(face->units_per_EM);
1345 if (!upem) {
1346 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1347 if (ttHeader) {
1348 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001349 }
1350 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001351
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001352 // use the os/2 table as a source of reasonable defaults.
1353 SkScalar x_height = 0.0f;
1354 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001355 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001356 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1357 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001358 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001359 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001360 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001361 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001362 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001363 }
1364
1365 // pull from format-specific metrics as needed
1366 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001367 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001368 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001369 // FreeType will always use HHEA metrics if they're not zero.
1370 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1371 // It also ignores the VDMX tables, which are also of interest here
1372 // (and override everything else when they apply).
1373 static const int kUseTypoMetricsMask = (1 << 7);
1374 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1375 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1376 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1377 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1378 } else {
1379 ascent = -SkIntToScalar(face->ascender) / upem;
1380 descent = -SkIntToScalar(face->descender) / upem;
1381 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1382 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001383 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1384 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1385 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1386 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001387 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001388 underlinePosition = -SkIntToScalar(face->underline_position +
1389 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001390
Ben Wagner3318da52017-03-23 14:01:22 -04001391 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThicknessIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001392 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1393
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001394 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001395 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001396 FT_BBox bbox;
1397 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001398 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1399 }
1400 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001401 if (!cap_height) {
1402 FT_BBox bbox;
1403 if (getCBoxForLetter('H', &bbox)) {
1404 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1405 }
1406 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001407 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1408 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1409 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1410 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1411 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001412 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001413 xmin = 0.0f;
1414 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1415 ymin = descent + leading;
1416 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001417 underlineThickness = 0;
1418 underlinePosition = 0;
1419
Ben Wagner3318da52017-03-23 14:01:22 -04001420 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThicknessIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001421 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001422 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001423 sk_bzero(metrics, sizeof(*metrics));
1424 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001425 }
1426
1427 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1428 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001429 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001430 }
1431 if (!avgCharWidth) {
1432 avgCharWidth = xmax - xmin;
1433 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001434 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001435 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001436 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001437
1438 // disallow negative linespacing
1439 if (leading < 0.0f) {
1440 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001441 }
1442
bungeman53790512016-07-21 13:32:09 -07001443 metrics->fTop = ymax * fScale.y();
1444 metrics->fAscent = ascent * fScale.y();
1445 metrics->fDescent = descent * fScale.y();
1446 metrics->fBottom = ymin * fScale.y();
1447 metrics->fLeading = leading * fScale.y();
1448 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1449 metrics->fXMin = xmin * fScale.y();
1450 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001451 metrics->fXHeight = x_height;
1452 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001453 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1454 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001455}
1456
djsollenfcfea992015-01-09 08:18:13 -08001457///////////////////////////////////////////////////////////////////////////////
1458
1459// hand-tuned value to reduce outline embolden strength
1460#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1461 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1462 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1463 #else
1464 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1465 #endif
1466#endif
1467
1468///////////////////////////////////////////////////////////////////////////////
1469
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001470void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1471{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001472 // check to see if the embolden bit is set
1473 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1474 return;
1475 }
1476
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001477 switch (glyph->format) {
1478 case FT_GLYPH_FORMAT_OUTLINE:
1479 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001480 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1481 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001482 FT_Outline_Embolden(&glyph->outline, strength);
1483 break;
1484 case FT_GLYPH_FORMAT_BITMAP:
1485 FT_GlyphSlot_Own_Bitmap(glyph);
1486 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1487 break;
1488 default:
1489 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001490 }
1491}
1492
reed@google.comb4162b12013-07-02 16:32:29 +00001493///////////////////////////////////////////////////////////////////////////////
1494
1495#include "SkUtils.h"
1496
1497static SkUnichar next_utf8(const void** chars) {
1498 return SkUTF8_NextUnichar((const char**)chars);
1499}
1500
1501static SkUnichar next_utf16(const void** chars) {
1502 return SkUTF16_NextUnichar((const uint16_t**)chars);
1503}
1504
1505static SkUnichar next_utf32(const void** chars) {
1506 const SkUnichar** uniChars = (const SkUnichar**)chars;
1507 SkUnichar uni = **uniChars;
1508 *uniChars += 1;
1509 return uni;
1510}
1511
1512typedef SkUnichar (*EncodingProc)(const void**);
1513
1514static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1515 static const EncodingProc gProcs[] = {
1516 next_utf8, next_utf16, next_utf32
1517 };
1518 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1519 return gProcs[enc];
1520}
1521
1522int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001523 uint16_t glyphs[], int glyphCount) const
1524{
reed@google.comb4162b12013-07-02 16:32:29 +00001525 AutoFTAccess fta(this);
1526 FT_Face face = fta.face();
1527 if (!face) {
1528 if (glyphs) {
1529 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1530 }
1531 return 0;
1532 }
1533
1534 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1535
halcanary96fcdcc2015-08-27 07:41:13 -07001536 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001537 for (int i = 0; i < glyphCount; ++i) {
1538 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1539 return i;
1540 }
1541 }
1542 return glyphCount;
1543 } else {
1544 int first = glyphCount;
1545 for (int i = 0; i < glyphCount; ++i) {
1546 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1547 glyphs[i] = SkToU16(id);
1548 if (0 == id && i < first) {
1549 first = i;
1550 }
1551 }
1552 return first;
1553 }
1554}
1555
1556int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001557 AutoFTAccess fta(this);
1558 FT_Face face = fta.face();
1559 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001560}
1561
bungeman@google.com839702b2013-08-07 17:09:22 +00001562SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001563 SkTypeface::LocalizedStrings* nameIter =
1564 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001565 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001566 SkString familyName;
1567 this->getFamilyName(&familyName);
1568 SkString language("und"); //undetermined
1569 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1570 }
1571 return nameIter;
1572}
1573
Ben Wagnerfc497342017-02-24 11:15:26 -05001574int SkTypeface_FreeType::onGetVariationDesignPosition(
1575 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1576{
1577 AutoFTAccess fta(this);
1578 FT_Face face = fta.face();
1579
Ben Wagnere7e54992017-03-02 11:48:38 -05001580 if (!face || !(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001581 return 0;
1582 }
1583
1584 FT_MM_Var* variations = nullptr;
1585 if (FT_Get_MM_Var(face, &variations)) {
1586 return 0;
1587 }
1588 SkAutoFree autoFreeVariations(variations);
1589
1590 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1591 return variations->num_axis;
1592 }
1593
1594 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1595 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1596 if (gFTLibrary->fGetVarDesignCoordinates &&
1597 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1598 {
1599 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1600 coordinates[i].axis = variations->axis[i].tag;
1601 coordinates[i].value = SkFixedToScalar(coords[i]);
1602 }
1603 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1604 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1605 coordinates[i].axis = variations->axis[i].tag;
1606 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1607 }
1608 } else if (fta.isNamedVariationSpecified()) {
1609 // The font has axes, they cannot be retrieved, and some named axis was specified.
1610 return -1;
1611 } else {
1612 // The font has axes, they cannot be retrieved, but no named instance was specified.
1613 return 0;
1614 }
1615
1616 return variations->num_axis;
1617}
1618
bungeman@google.comddc218e2013-08-01 22:29:43 +00001619int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1620 AutoFTAccess fta(this);
1621 FT_Face face = fta.face();
1622
1623 FT_ULong tableCount = 0;
1624 FT_Error error;
1625
halcanary96fcdcc2015-08-27 07:41:13 -07001626 // When 'tag' is nullptr, returns number of tables in 'length'.
1627 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001628 if (error) {
1629 return 0;
1630 }
1631
1632 if (tags) {
1633 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1634 FT_ULong tableTag;
1635 FT_ULong tablelength;
1636 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1637 if (error) {
1638 return 0;
1639 }
1640 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1641 }
1642 }
1643 return tableCount;
1644}
1645
1646size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1647 size_t length, void* data) const
1648{
1649 AutoFTAccess fta(this);
1650 FT_Face face = fta.face();
1651
1652 FT_ULong tableLength = 0;
1653 FT_Error error;
1654
1655 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001656 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001657 if (error) {
1658 return 0;
1659 }
1660
1661 if (offset > tableLength) {
1662 return 0;
1663 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001664 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001665 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001666 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1667 if (error) {
1668 return 0;
1669 }
1670 }
1671
1672 return size;
1673}
1674
reed@google.comb4162b12013-07-02 16:32:29 +00001675///////////////////////////////////////////////////////////////////////////////
1676///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001677
halcanary96fcdcc2015-08-27 07:41:13 -07001678SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001679 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1680 return;
bungeman14df8332014-10-28 15:07:23 -07001681 }
bungeman9dc24682014-12-01 14:01:32 -08001682 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001683}
1684SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001685 if (fLibrary) {
1686 FT_Done_Library(fLibrary);
1687 }
bungeman14df8332014-10-28 15:07:23 -07001688}
1689
bungemanf93d7112016-09-16 06:24:20 -07001690FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001691 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001692{
halcanary96fcdcc2015-08-27 07:41:13 -07001693 if (fLibrary == nullptr) {
1694 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001695 }
1696
bungeman14df8332014-10-28 15:07:23 -07001697 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001698 memset(&args, 0, sizeof(args));
1699
1700 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001701
bsalomon49f085d2014-09-05 13:34:00 -07001702 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001703 args.flags = FT_OPEN_MEMORY;
1704 args.memory_base = (const FT_Byte*)memoryBase;
1705 args.memory_size = stream->getLength();
1706 } else {
bungeman14df8332014-10-28 15:07:23 -07001707 memset(ftStream, 0, sizeof(*ftStream));
1708 ftStream->size = stream->getLength();
1709 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001710 ftStream->read = sk_ft_stream_io;
1711 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001712
1713 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001714 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001715 }
1716
1717 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001718 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001719 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001720 }
1721 return face;
1722}
1723
bungemanf93d7112016-09-16 06:24:20 -07001724bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001725 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1726
1727 FT_StreamRec streamRec;
1728 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001729 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001730 return false;
1731 }
1732
1733 *numFaces = face->num_faces;
1734
1735 FT_Done_Face(face);
1736 return true;
1737}
1738
1739#include "SkTSearch.h"
1740bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001741 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001742 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001743{
1744 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1745
1746 FT_StreamRec streamRec;
1747 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001748 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001749 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001750 }
1751
bungemana4c4a2d2014-10-20 13:33:19 -07001752 int weight = SkFontStyle::kNormal_Weight;
1753 int width = SkFontStyle::kNormal_Width;
1754 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001755 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001756 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001757 }
1758 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001759 slant = SkFontStyle::kItalic_Slant;
1760 }
1761
1762 PS_FontInfoRec psFontInfo;
1763 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1764 if (os2 && os2->version != 0xffff) {
1765 weight = os2->usWeightClass;
1766 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001767
1768 // OS/2::fsSelection bit 9 indicates oblique.
1769 if (SkToBool(os2->fsSelection & (1u << 9))) {
1770 slant = SkFontStyle::kOblique_Slant;
1771 }
bungemana4c4a2d2014-10-20 13:33:19 -07001772 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1773 static const struct {
1774 char const * const name;
1775 int const weight;
1776 } commonWeights [] = {
1777 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001778 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001779 { "black", SkFontStyle::kBlack_Weight },
1780 { "bold", SkFontStyle::kBold_Weight },
1781 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1782 { "demi", SkFontStyle::kSemiBold_Weight },
1783 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001784 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001785 { "extrabold", SkFontStyle::kExtraBold_Weight },
1786 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001787 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001788 { "heavy", SkFontStyle::kBlack_Weight },
1789 { "light", SkFontStyle::kLight_Weight },
1790 { "medium", SkFontStyle::kMedium_Weight },
1791 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001792 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001793 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001794 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001795 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001796 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001797 { "thin", SkFontStyle::kThin_Weight },
1798 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001799 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001800 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001801 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001802 { "ultralight", SkFontStyle::kExtraLight_Weight },
1803 };
1804 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001805 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001806 if (index >= 0) {
1807 weight = commonWeights[index].weight;
1808 } else {
bungeman14df8332014-10-28 15:07:23 -07001809 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001810 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001811 }
1812
1813 if (name) {
1814 name->set(face->family_name);
1815 }
1816 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001817 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001818 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001819 if (isFixedPitch) {
1820 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001821 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001822
bungeman41868fe2015-05-20 09:21:04 -07001823 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001824 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001825 FT_Error err = FT_Get_MM_Var(face, &variations);
1826 if (err) {
1827 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1828 face->family_name));
1829 return false;
1830 }
1831 SkAutoFree autoFreeVariations(variations);
1832
1833 axes->reset(variations->num_axis);
1834 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1835 const FT_Var_Axis& ftAxis = variations->axis[i];
1836 (*axes)[i].fTag = ftAxis.tag;
1837 (*axes)[i].fMinimum = ftAxis.minimum;
1838 (*axes)[i].fDefault = ftAxis.def;
1839 (*axes)[i].fMaximum = ftAxis.maximum;
1840 }
1841 }
bungeman41868fe2015-05-20 09:21:04 -07001842
reed@android.com8a1c16f2008-12-17 15:59:43 +00001843 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001844 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001845}
bungemanf6c71072016-01-21 14:17:47 -08001846
1847/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1848 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001849 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001850 SkFixed* axisValues,
1851 const SkString& name)
1852{
1853 for (int i = 0; i < axisDefinitions.count(); ++i) {
1854 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001855 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1856 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001857 axisValues[i] = axisDefinition.fDefault;
bungeman9aec8942017-03-29 13:38:53 -04001858 // The position may be over specified. If there are multiple values for a given axis,
1859 // use the last one since that's what css-fonts-4 requires.
1860 for (int j = position.coordinateCount; j --> 0;) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001861 const auto& coordinate = position.coordinates[j];
1862 if (axisDefinition.fTag == coordinate.axis) {
1863 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1864 if (coordinate.value != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001865 SkDEBUGF(("Requested font axis value out of range: "
1866 "%s '%c%c%c%c' %f; pinned to %f.\n",
1867 name.c_str(),
1868 (axisDefinition.fTag >> 24) & 0xFF,
1869 (axisDefinition.fTag >> 16) & 0xFF,
1870 (axisDefinition.fTag >> 8) & 0xFF,
1871 (axisDefinition.fTag ) & 0xFF,
Ben Wagnerfc497342017-02-24 11:15:26 -05001872 SkScalarToDouble(coordinate.value),
benjaminwagner64a3c952016-02-25 12:20:40 -08001873 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001874 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001875 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001876 break;
1877 }
1878 }
1879 // TODO: warn on defaulted axis?
1880 }
1881
1882 SkDEBUGCODE(
1883 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001884 for (int i = 0; i < position.coordinateCount; ++i) {
1885 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001886 bool found = false;
1887 for (int j = 0; j < axisDefinitions.count(); ++j) {
1888 if (skTag == axisDefinitions[j].fTag) {
1889 found = true;
1890 break;
1891 }
1892 }
1893 if (!found) {
1894 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1895 name.c_str(),
1896 (skTag >> 24) & 0xFF,
1897 (skTag >> 16) & 0xFF,
1898 (skTag >> 8) & 0xFF,
1899 (skTag) & 0xFF));
1900 }
1901 }
1902 )
1903}