blob: 1c228eaf48a6ed8447228d7959b4f890d69d84e4 [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"
mtklein1b249332015-07-07 12:21:21 -070021#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000022#include "SkOTUtils.h"
bungemand3ebb482015-08-05 13:57:49 -070023#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000024#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000025#include "SkStream.h"
26#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027#include "SkTemplates.h"
mtklein5f939ab2016-03-16 10:28:35 -070028#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000029
30#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080031#include FT_ADVANCES_H
32#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000033#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080034#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080035#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070036#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000037#include FT_OUTLINE_H
38#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080039#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000040#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000041#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000042#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000043
Ben Wagnerfc497342017-02-24 11:15:26 -050044// SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
45// Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
46#define SK_FREETYPE_DLOPEN (0x1)
47#ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
48# if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (GOOGLE3)
49# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
50# else
51# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
52# endif
53#endif
54#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
55# include <dlfcn.h>
56#endif
57
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000058// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
59// were introduced in FreeType 2.5.0.
60// The following may be removed once FreeType 2.5.0 is required to build.
61#ifndef FT_LOAD_COLOR
62# define FT_LOAD_COLOR ( 1L << 20 )
63# define FT_PIXEL_MODE_BGRA 7
64#endif
65
Seigo Nonaka52ab2f52016-12-05 02:41:53 +090066// FT_LOAD_BITMAP_METRICS_ONLY was introduced in FreeType 2.7.1
67// The following may be removed once FreeType 2.7.1 is required to build.
68#ifndef FT_LOAD_BITMAP_METRICS_ONLY
69# define FT_LOAD_BITMAP_METRICS_ONLY ( 1L << 22 )
70#endif
71
reed@android.com8a1c16f2008-12-17 15:59:43 +000072//#define ENABLE_GLYPH_SPEW // for tracing calls
73//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080074//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000075//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000076
reed@google.comeffc5012011-06-27 16:44:46 +000077static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080078 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000079}
80
reed@android.com8a1c16f2008-12-17 15:59:43 +000081//////////////////////////////////////////////////////////////////////////
82
bungeman9dc24682014-12-01 14:01:32 -080083extern "C" {
84 static void* sk_ft_alloc(FT_Memory, long size) {
85 return sk_malloc_throw(size);
86 }
87 static void sk_ft_free(FT_Memory, void* block) {
88 sk_free(block);
89 }
90 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
91 return sk_realloc_throw(block, new_size);
92 }
93};
halcanary96fcdcc2015-08-27 07:41:13 -070094FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -080095
96class FreeTypeLibrary : SkNoncopyable {
97public:
Ben Wagnerfc497342017-02-24 11:15:26 -050098 FreeTypeLibrary()
99 : fGetVarDesignCoordinates(nullptr)
100 , fLibrary(nullptr)
101 , fIsLCDSupported(false)
102 , fLCDExtra(0)
103 {
bungeman9dc24682014-12-01 14:01:32 -0800104 if (FT_New_Library(&gFTMemory, &fLibrary)) {
105 return;
106 }
107 FT_Add_Default_Modules(fLibrary);
108
Ben Wagner2a098d02017-03-01 13:00:53 -0500109 // When using dlsym
110 // *(void**)(&procPtr) = dlsym(self, "proc");
111 // is non-standard, but safe for POSIX. Cannot write
112 // *reinterpret_cast<void**>(&procPtr) = dlsym(self, "proc");
113 // because clang has not implemented DR573. See http://clang.llvm.org/cxx_dr_status.html .
114
115 FT_Int major, minor, patch;
116 FT_Library_Version(fLibrary, &major, &minor, &patch);
117
Ben Wagnerfc497342017-02-24 11:15:26 -0500118#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070100
119 fGetVarDesignCoordinates = FT_Get_Var_Design_Coordinates;
120#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
Ben Wagner2a098d02017-03-01 13:00:53 -0500121 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 0))) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500122 //The FreeType library is already loaded, so symbols are available in process.
123 void* self = dlopen(nullptr, RTLD_LAZY);
124 if (self) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500125 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
126 dlclose(self);
127 }
128 }
129#endif
130
Ben Wagner2a098d02017-03-01 13:00:53 -0500131#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION >= 0x02070200
132 FT_Set_Default_Properties(fLibrary);
133#elif SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
134 if (major > 2 || ((major == 2 && minor > 7) || (major == 2 && minor == 7 && patch >= 1))) {
bungeman9dc24682014-12-01 14:01:32 -0800135 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700136 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800137 if (self) {
Ben Wagner2a098d02017-03-01 13:00:53 -0500138 FT_Set_Default_PropertiesProc setDefaultProperties;
139 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
bungeman9dc24682014-12-01 14:01:32 -0800140 dlclose(self);
141
Ben Wagner2a098d02017-03-01 13:00:53 -0500142 if (setDefaultProperties) {
143 setDefaultProperties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800144 }
145 }
Ben Wagner2a098d02017-03-01 13:00:53 -0500146 }
bungeman9dc24682014-12-01 14:01:32 -0800147#endif
Ben Wagner2a098d02017-03-01 13:00:53 -0500148
149 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
150 // The default has changed over time, so this doesn't mean the same thing to all users.
151 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
152 fIsLCDSupported = true;
153 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
bungeman9dc24682014-12-01 14:01:32 -0800154 }
155 }
156 ~FreeTypeLibrary() {
157 if (fLibrary) {
158 FT_Done_Library(fLibrary);
159 }
160 }
161
162 FT_Library library() { return fLibrary; }
163 bool isLCDSupported() { return fIsLCDSupported; }
164 int lcdExtra() { return fLCDExtra; }
165
Ben Wagnerfc497342017-02-24 11:15:26 -0500166 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
167 // Prior to this there was no way to get the coordinates out of the FT_Face.
168 // This wasn't too bad because you needed to specify them anyway, and the clamp was provided.
169 // However, this doesn't work when face_index specifies named variations as introduced in 2.6.1.
170 using FT_Get_Var_Blend_CoordinatesProc = FT_Error (*)(FT_Face, FT_UInt, FT_Fixed*);
171 FT_Get_Var_Blend_CoordinatesProc fGetVarDesignCoordinates;
172
bungeman9dc24682014-12-01 14:01:32 -0800173private:
174 FT_Library fLibrary;
175 bool fIsLCDSupported;
176 int fLCDExtra;
177
178 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
179 // The following platforms provide FreeType of at least 2.4.0.
180 // Ubuntu >= 11.04 (previous deprecated April 2013)
181 // Debian >= 6.0 (good)
182 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
183 // Fedora >= 14 (good)
184 // Android >= Gingerbread (good)
Ben Wagnerfc497342017-02-24 11:15:26 -0500185 // RHEL >= 7 (6 has 2.3.11, EOL Nov 2020, Phase 3 May 2017)
186 using FT_Library_SetLcdFilterWeightsProc = FT_Error (*)(FT_Library, unsigned char*);
Ben Wagner2a098d02017-03-01 13:00:53 -0500187
188 // FreeType added the ability to read global properties in 2.7.0. After 2.7.1 a means for users
189 // of FT_New_Library to request these global properties to be read was added.
190 using FT_Set_Default_PropertiesProc = void (*)(FT_Library);
bungeman9dc24682014-12-01 14:01:32 -0800191};
192
reed@android.com8a1c16f2008-12-17 15:59:43 +0000193struct SkFaceRec;
194
reed086eea92016-05-04 17:12:46 -0700195SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800196static FreeTypeLibrary* gFTLibrary;
197static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000198
bungemanaabd71c2016-03-01 15:15:09 -0800199// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800200static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000201
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000202// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800203static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800204 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800205 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800206
bungeman9dc24682014-12-01 14:01:32 -0800207 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700208 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700209 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000210 }
bungeman9dc24682014-12-01 14:01:32 -0800211 ++gFTCount;
212 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000213}
214
bungeman9dc24682014-12-01 14:01:32 -0800215// Caller must lock gFTMutex before calling this function.
216static void unref_ft_library() {
217 gFTMutex.assertHeld();
218 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000219
bungeman9dc24682014-12-01 14:01:32 -0800220 --gFTCount;
221 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800222 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700223 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700224 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700225 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800226 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000227}
228
Ben Wagnerfc497342017-02-24 11:15:26 -0500229///////////////////////////////////////////////////////////////////////////
230
231struct SkFaceRec {
232 SkFaceRec* fNext;
233 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<FT_Error, FT_FaceRec, FT_Done_Face>> fFace;
234 FT_StreamRec fFTStream;
235 std::unique_ptr<SkStreamAsset> fSkStream;
236 uint32_t fRefCnt;
237 uint32_t fFontID;
238
239 // FreeType prior to 2.7.1 does not implement retreiving variation design metrics.
240 // Cache the variation design metrics used to create the font if the user specifies them.
241 SkAutoSTMalloc<4, SkFixed> fAxes;
242 int fAxesCount;
243
244 // FreeType from 2.6.1 (14d6b5d7) until 2.7.0 (ee3f36f6b38) uses font_index for both font index
245 // and named variation index on input, but masks the named variation index part on output.
246 // Manually keep track of when a named variation is requested for 2.6.1 until 2.7.1.
247 bool fNamedVariationSpecified;
248
249 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
250};
251
252extern "C" {
253 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
254 unsigned long offset,
255 unsigned char* buffer,
256 unsigned long count)
257 {
258 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
259
260 if (count) {
261 if (!stream->seek(offset)) {
262 return 0;
263 }
264 count = stream->read(buffer, count);
265 }
266 return count;
267 }
268
269 static void sk_ft_stream_close(FT_Stream) {}
270}
271
272SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
273 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
274 , fAxesCount(0), fNamedVariationSpecified(false)
275{
276 sk_bzero(&fFTStream, sizeof(fFTStream));
277 fFTStream.size = fSkStream->getLength();
278 fFTStream.descriptor.pointer = fSkStream.get();
279 fFTStream.read = sk_ft_stream_io;
280 fFTStream.close = sk_ft_stream_close;
281}
282
283static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
284 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
285 return;
286 }
287
288 // If a named variation is requested, don't overwrite the named variation's position.
289 if (data.getIndex() > 0xFFFF) {
290 rec->fNamedVariationSpecified = true;
291 return;
292 }
293
294 SkDEBUGCODE(
295 FT_MM_Var* variations = nullptr;
296 if (FT_Get_MM_Var(rec->fFace.get(), &variations)) {
297 SkDEBUGF(("INFO: font %s claims variations, but none found.\n",
298 rec->fFace->family_name));
299 return;
300 }
301 SkAutoFree autoFreeVariations(variations);
302
303 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
304 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
305 rec->fFace->family_name, variations->num_axis, data.getAxisCount()));
306 return;
307 }
308 )
309
310 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
311 for (int i = 0; i < data.getAxisCount(); ++i) {
312 coords[i] = data.getAxis()[i];
313 }
314 if (FT_Set_Var_Design_Coordinates(rec->fFace.get(), data.getAxisCount(), coords.get())) {
315 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
316 rec->fFace->family_name));
317 return;
318 }
319
320 rec->fAxesCount = data.getAxisCount();
321 rec->fAxes.reset(rec->fAxesCount);
322 for (int i = 0; i < rec->fAxesCount; ++i) {
323 rec->fAxes[i] = data.getAxis()[i];
324 }
325}
326
327// Will return nullptr on failure
328// Caller must lock gFTMutex before calling this function.
329static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
330 gFTMutex.assertHeld();
331
332 const SkFontID fontID = typeface->uniqueID();
333 SkFaceRec* cachedRec = gFaceRecHead;
334 while (cachedRec) {
335 if (cachedRec->fFontID == fontID) {
336 SkASSERT(cachedRec->fFace);
337 cachedRec->fRefCnt += 1;
338 return cachedRec;
339 }
340 cachedRec = cachedRec->fNext;
341 }
342
343 std::unique_ptr<SkFontData> data = typeface->makeFontData();
344 if (nullptr == data || !data->hasStream()) {
345 return nullptr;
346 }
347
348 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
349
350 FT_Open_Args args;
351 memset(&args, 0, sizeof(args));
352 const void* memoryBase = rec->fSkStream->getMemoryBase();
353 if (memoryBase) {
354 args.flags = FT_OPEN_MEMORY;
355 args.memory_base = (const FT_Byte*)memoryBase;
356 args.memory_size = rec->fSkStream->getLength();
357 } else {
358 args.flags = FT_OPEN_STREAM;
359 args.stream = &rec->fFTStream;
360 }
361
362 {
363 FT_Face rawFace;
364 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
365 if (err) {
366 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
367 return nullptr;
368 }
369 rec->fFace.reset(rawFace);
370 }
371 SkASSERT(rec->fFace);
372
373 ft_face_setup_axes(rec.get(), *data);
374
375 // FreeType will set the charmap to the "most unicode" cmap if it exists.
376 // If there are no unicode cmaps, the charmap is set to nullptr.
377 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
378 // because they are effectively private use area only (even if they aren't).
379 // This is the last on the fallback list at
380 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
381 if (!rec->fFace->charmap) {
382 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
383 }
384
385 rec->fNext = gFaceRecHead;
386 gFaceRecHead = rec.get();
387 return rec.release();
388}
389
390// Caller must lock gFTMutex before calling this function.
391static void unref_ft_face(SkFaceRec* faceRec) {
392 gFTMutex.assertHeld();
393
394 SkFaceRec* rec = gFaceRecHead;
395 SkFaceRec* prev = nullptr;
396 while (rec) {
397 SkFaceRec* next = rec->fNext;
398 if (rec->fFace == faceRec->fFace) {
399 if (--rec->fRefCnt == 0) {
400 if (prev) {
401 prev->fNext = next;
402 } else {
403 gFaceRecHead = next;
404 }
405 delete rec;
406 }
407 return;
408 }
409 prev = rec;
410 rec = next;
411 }
412 SkDEBUGFAIL("shouldn't get here, face not in list");
413}
414
415class AutoFTAccess {
416public:
417 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
418 gFTMutex.acquire();
419 if (!ref_ft_library()) {
420 sk_throw();
421 }
422 fFaceRec = ref_ft_face(tf);
423 }
424
425 ~AutoFTAccess() {
426 if (fFaceRec) {
427 unref_ft_face(fFaceRec);
428 }
429 unref_ft_library();
430 gFTMutex.release();
431 }
432
433 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
434 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
435 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
436 bool isNamedVariationSpecified() {
437 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
438 }
439
440private:
441 SkFaceRec* fFaceRec;
442};
443
444///////////////////////////////////////////////////////////////////////////
445
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000446class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000447public:
bungeman7cfd46a2016-10-20 16:06:52 -0400448 SkScalerContext_FreeType(sk_sp<SkTypeface>,
449 const SkScalerContextEffects&,
450 const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000451 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000452
reed@android.com62900b42009-02-11 15:07:19 +0000453 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700454 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000455 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000456
457protected:
mtklein36352bf2015-03-25 18:17:31 -0700458 unsigned generateGlyphCount() override;
459 uint16_t generateCharToGlyph(SkUnichar uni) override;
460 void generateAdvance(SkGlyph* glyph) override;
461 void generateMetrics(SkGlyph* glyph) override;
462 void generateImage(const SkGlyph& glyph) override;
Ben Wagner6e9ac122016-11-11 14:31:06 -0500463 void generatePath(SkGlyphID glyphID, SkPath* path) override;
mtklein36352bf2015-03-25 18:17:31 -0700464 void generateFontMetrics(SkPaint::FontMetrics*) override;
465 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000466
467private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500468 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
469 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
470
471 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700472 FT_Size fFTSize; // The size on the fFace for this scaler.
473 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000474
bungeman401ae2d2016-07-18 15:46:27 -0700475 /** The rest of the matrix after FreeType handles the size.
476 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
477 * With bitmap only fonts this matrix must be applied to scale the bitmap.
478 */
479 SkMatrix fMatrix22Scalar;
480 /** Same as fMatrix22Scalar, but in FreeType units and space. */
481 FT_Matrix fMatrix22;
482 /** The actual size requested. */
483 SkVector fScale;
484
485 uint32_t fLoadGlyphFlags;
486 bool fDoLinearMetrics;
487 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000488
reed@android.com8a1c16f2008-12-17 15:59:43 +0000489 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000490 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
491 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000492 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000493 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000494 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000495 // Caller must lock gFTMutex before calling this function.
496 // update FreeType2 glyph slot with glyph emboldened
497 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
bungeman401ae2d2016-07-18 15:46:27 -0700498 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000499};
500
501///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000502
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000503static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000504 FT_UShort fsType = FT_Get_FSType_Flags(face);
505 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
506 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000507}
508
vandebo0f9bad02014-06-19 11:05:39 -0700509static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700510 FT_UShort fsType = FT_Get_FSType_Flags(face);
511 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700512}
513
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000514static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
515 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
516 if (!glyph_id)
517 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000518 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
519 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000520 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
521 return true;
522}
523
bungeman5ec443c2014-11-21 13:18:34 -0800524static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
halcanaryf8c74a12016-04-20 08:37:43 -0700525 FT_Long numGlyphs = face->num_glyphs;
526 glyphToUnicode->setCount(SkToInt(numGlyphs));
527 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000528
bungeman726cf902015-06-05 13:38:12 -0700529 FT_UInt glyphIndex;
530 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
531 while (glyphIndex) {
halcanaryf8c74a12016-04-20 08:37:43 -0700532 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
halcanary5f1d0f62016-09-13 08:08:38 -0700533 // Use the first character that maps to this glyphID. https://crbug.com/359065
534 if (0 == (*glyphToUnicode)[glyphIndex]) {
535 (*glyphToUnicode)[glyphIndex] = charCode;
536 }
bungeman726cf902015-06-05 13:38:12 -0700537 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000538 }
539}
540
reed@google.com2689f612013-03-20 20:01:47 +0000541SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700542 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000543 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000544 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000545 AutoFTAccess fta(this);
546 FT_Face face = fta.face();
547 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700548 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000549 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000550
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000551 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
552 info->fFontName.set(FT_Get_Postscript_Name(face));
halcanary32875882016-08-16 09:36:23 -0700553
vandebo0f9bad02014-06-19 11:05:39 -0700554 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700555 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700556 }
557 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700558 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700559 }
560 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700561 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700562 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000563 info->fLastGlyphID = face->num_glyphs - 1;
564 info->fEmSize = 1000;
565
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;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000575 TT_Header* ttHeader;
bungemanf1491692016-07-22 11:19:24 -0700576 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000577 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000578 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000579 } else {
580 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000581 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000582
halcanary32875882016-08-16 09:36:23 -0700583 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700584 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000585 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700586 }
587 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000588 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700589 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000590
bungemanf1491692016-07-22 11:19:24 -0700591 PS_FontInfoRec psFontInfo;
592 TT_Postscript* postTable;
593 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
594 info->fItalicAngle = psFontInfo.italic_angle;
595 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
596 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000597 } else {
598 info->fItalicAngle = 0;
599 }
600
601 info->fAscent = face->ascender;
602 info->fDescent = face->descender;
603
604 // Figure out a good guess for StemV - Min width of i, I, !, 1.
605 // This probably isn't very good with an italic font.
606 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000607 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000608 char stem_chars[] = {'i', 'I', '!', '1'};
609 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
610 FT_BBox bbox;
611 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
612 int16_t width = bbox.xMax - bbox.xMin;
613 if (width > 0 && width < min_width) {
614 min_width = width;
615 info->fStemV = min_width;
616 }
617 }
618 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000619
bungemanf1491692016-07-22 11:19:24 -0700620 TT_PCLT* pcltTable;
621 TT_OS2* os2Table;
622 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
623 info->fCapHeight = pcltTable->CapHeight;
624 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
625 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000626 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700627 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000628 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700629 }
630 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000631 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700632 os2Table->version != 0xFFFF &&
633 os2Table->version >= 2)
634 {
635 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000636 } else {
637 // Figure out a good guess for CapHeight: average the height of M and X.
638 FT_BBox m_bbox, x_bbox;
639 bool got_m, got_x;
640 got_m = GetLetterCBox(face, 'M', &m_bbox);
641 got_x = GetLetterCBox(face, 'X', &x_bbox);
642 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700643 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000644 } else if (got_m && !got_x) {
645 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
646 } else if (!got_m && got_x) {
647 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000648 } else {
649 // Last resort, use the ascent.
650 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000651 }
652 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000653
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000654 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
655 face->bbox.xMax, face->bbox.yMin);
656
vandebo0f9bad02014-06-19 11:05:39 -0700657 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700658 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000659 }
660
reed39a9a502015-05-12 09:50:04 -0700661 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700662 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
663 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000664 // Postscript fonts may contain more than 255 glyphs, so we end up
665 // using multiple font descriptions with a glyph ordering. Record
666 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700667 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000668 for (int gID = 0; gID < face->num_glyphs; gID++) {
669 char glyphName[128]; // PS limit for names is 127 bytes.
670 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700671 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000672 }
673 }
674
reed39a9a502015-05-12 09:50:04 -0700675 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700676 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
677 face->num_charmaps)
678 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000679 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
680 }
681
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000682 return info;
683}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000684
reed@google.com618ef5e2011-01-26 22:10:41 +0000685///////////////////////////////////////////////////////////////////////////
686
reed@google.com8ed436c2011-07-21 14:12:36 +0000687static bool bothZero(SkScalar a, SkScalar b) {
688 return 0 == a && 0 == b;
689}
690
691// returns false if there is any non-90-rotation or skew
692static bool isAxisAligned(const SkScalerContext::Rec& rec) {
693 return 0 == rec.fPreSkewX &&
694 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
695 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
696}
697
reeda9322c22016-04-12 06:47:05 -0700698SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
699 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400700 auto c = skstd::make_unique<SkScalerContext_FreeType>(
701 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000702 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400703 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000704 }
bungeman7cfd46a2016-10-20 16:06:52 -0400705 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000706}
707
708void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000709 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
710 //Cap the requested size as larger sizes give bogus values.
711 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800712 //Note that this also currently only protects against large text size requests,
713 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000714 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000715 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000716 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000717
bungemanec7e12f2015-01-21 11:55:16 -0800718 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800719 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
720 SkAutoMutexAcquire ama(gFTMutex);
721 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800722 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800723 // If the runtime Freetype library doesn't support LCD, disable it here.
724 rec->fMaskFormat = SkMask::kA8_Format;
725 }
726 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000727 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000728
reed@google.com618ef5e2011-01-26 22:10:41 +0000729 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000730 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000731 // collapse full->normal hinting if we're not doing LCD
732 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000733 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000734 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000735 if (SkPaint::kNo_Hinting != h) {
736 h = SkPaint::kSlight_Hinting;
737 }
738 }
739
reed@google.com8ed436c2011-07-21 14:12:36 +0000740 // rotated text looks bad with hinting, so we disable it as needed
741 if (!isAxisAligned(*rec)) {
742 h = SkPaint::kNo_Hinting;
743 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000744 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000745
bungeman@google.com97efada2012-07-30 20:40:50 +0000746#ifndef SK_GAMMA_APPLY_TO_A8
747 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700748 // SRGBTODO: Is this correct? Do we want contrast boost?
749 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000750 }
reed@google.com1ac83502012-02-28 17:06:02 +0000751#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000752}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000753
reed@google.com38c37dd2013-03-21 15:36:26 +0000754int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000755 AutoFTAccess fta(this);
756 FT_Face face = fta.face();
757 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000758}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000759
reed@google.com35fe7372013-10-30 15:07:03 +0000760bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
761 int count, int32_t adjustments[]) const {
762 AutoFTAccess fta(this);
763 FT_Face face = fta.face();
764 if (!face || !FT_HAS_KERNING(face)) {
765 return false;
766 }
767
768 for (int i = 0; i < count - 1; ++i) {
769 FT_Vector delta;
770 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
771 FT_KERNING_UNSCALED, &delta);
772 if (err) {
773 return false;
774 }
775 adjustments[i] = delta.x;
776 }
777 return true;
778}
779
bungeman401ae2d2016-07-18 15:46:27 -0700780/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800781static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700782 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700783 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000784 return -1;
785 }
bungeman401ae2d2016-07-18 15:46:27 -0700786
787 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000788 FT_Int chosenStrikeIndex = -1;
789 FT_Pos chosenPPEM = 0;
790 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700791 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
792 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000793 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700794 return strikeIndex;
795 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000796 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700797 if (chosenPPEM < strikePPEM) {
798 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000799 chosenStrikeIndex = strikeIndex;
800 }
801 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700802 // attempt to decrease chosenPPEM, but not below requestedPPEM
803 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
804 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000805 chosenStrikeIndex = strikeIndex;
806 }
807 }
808 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000809 return chosenStrikeIndex;
810}
811
bungeman7cfd46a2016-10-20 16:06:52 -0400812SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700813 const SkScalerContextEffects& effects,
814 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400815 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800816 , fFace(nullptr)
817 , fFTSize(nullptr)
818 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700819{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820 SkAutoMutexAcquire ac(gFTMutex);
821
bungeman9dc24682014-12-01 14:01:32 -0800822 if (!ref_ft_library()) {
823 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000824 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000825
Ben Wagnerfc497342017-02-24 11:15:26 -0500826 fFaceRec.reset(ref_ft_face(this->getTypeface()));
827
reed@android.com8a1c16f2008-12-17 15:59:43 +0000828 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500829 if (nullptr == fFaceRec) {
bungemanaabd71c2016-03-01 15:15:09 -0800830 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000831 return;
832 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000833
bungeman5f14c5e2014-12-05 12:26:44 -0800834 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000835
bungeman401ae2d2016-07-18 15:46:27 -0700836 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
837 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000838 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700839 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
840 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000841 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000842
reed@google.coma1bfa212012-03-08 21:57:12 +0000843 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
844
reed@android.com8a1c16f2008-12-17 15:59:43 +0000845 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000846 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000848 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000849
agl@chromium.org70a303f2010-05-10 14:15:50 +0000850 if (SkMask::kBW_Format == fRec.fMaskFormat) {
851 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
852 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000853 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000854 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000855 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000856 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000857 } else {
858 switch (fRec.getHinting()) {
859 case SkPaint::kNo_Hinting:
860 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000861 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000862 break;
863 case SkPaint::kSlight_Hinting:
864 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
865 break;
866 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000867 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000868 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700869#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
870 } else {
871 loadFlags = FT_LOAD_NO_AUTOHINT;
872#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000873 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000874 break;
875 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000876 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000877 loadFlags = FT_LOAD_FORCE_AUTOHINT;
878 break;
879 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000880 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000881 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000882 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000883 loadFlags = FT_LOAD_TARGET_LCD_V;
884 } else {
885 loadFlags = FT_LOAD_TARGET_LCD;
886 }
reed@google.comea2333d2011-03-14 16:44:56 +0000887 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000888 break;
889 default:
890 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
891 break;
892 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000893 }
894
reed@google.comeffc5012011-06-27 16:44:46 +0000895 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000896 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000897 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000898
reed@google.com96a9f7912011-05-06 11:49:30 +0000899 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
900 // advances, as fontconfig and cairo do.
901 // See http://code.google.com/p/skia/issues/detail?id=222.
902 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
903
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000904 // Use vertical layout if requested.
905 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
906 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
907 }
908
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000909 loadFlags |= FT_LOAD_COLOR;
910
reed@android.come4d0bc02009-07-24 19:53:20 +0000911 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000912 }
913
bungemanaabd71c2016-03-01 15:15:09 -0800914 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500915 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800916 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500917 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800918 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500919 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800920 return nullptr;
921 }
922 return size;
923 }());
924 if (nullptr == ftSize) {
925 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000926 return;
927 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000928
bungemanaabd71c2016-03-01 15:15:09 -0800929 FT_Error err = FT_Activate_Size(ftSize.get());
930 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500931 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800932 return;
933 }
934
Ben Wagnerfc497342017-02-24 11:15:26 -0500935 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
936 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000937 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700938 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500939 fFaceRec->fFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000940 return;
941 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500942 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
943 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000944 if (fStrikeIndex == -1) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500945 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n",
946 fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700947 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000948 }
bungeman401ae2d2016-07-18 15:46:27 -0700949
Ben Wagnerfc497342017-02-24 11:15:26 -0500950 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700951 if (err != 0) {
952 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500953 fFaceRec->fFace->family_name, fStrikeIndex, err));
bungeman401ae2d2016-07-18 15:46:27 -0700954 fStrikeIndex = -1;
955 return;
956 }
957
958 // A non-ideal size was picked, so recompute the matrix.
959 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
Ben Wagnerfc497342017-02-24 11:15:26 -0500960 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
961 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700962 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
963 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
964 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
965 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
966
967 // FreeType does not provide linear metrics for bitmap fonts.
968 linearMetrics = false;
969
970 // FreeType documentation says:
971 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
972 // Bitmap-only fonts ignore this flag.
973 //
974 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
975 // Force this flag off for bitmap only fonts.
976 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000977 } else {
Ben Wagnerfc497342017-02-24 11:15:26 -0500978 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700979 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000980 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000981
bungemanaabd71c2016-03-01 15:15:09 -0800982 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500983 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000984 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000985}
986
987SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000988 SkAutoMutexAcquire ac(gFTMutex);
989
halcanary96fcdcc2015-08-27 07:41:13 -0700990 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000991 FT_Done_Size(fFTSize);
992 }
993
Ben Wagnerfc497342017-02-24 11:15:26 -0500994 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -0800995
996 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000997}
998
999/* We call this before each use of the fFace, since we may be sharing
1000 this face with other context (at different sizes).
1001*/
1002FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -08001003 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001004 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001005 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001006 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001007 }
halcanary96fcdcc2015-08-27 07:41:13 -07001008 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001009 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001010}
1011
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001012unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 return fFace->num_glyphs;
1014}
1015
1016uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -08001017 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001018 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1019}
1020
reed@android.com9d3a9852010-01-08 14:07:42 +00001021SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -08001022 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +00001023 // iterate through each cmap entry, looking for matching glyph indices
1024 FT_UInt glyphIndex;
1025 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1026
1027 while (glyphIndex != 0) {
1028 if (glyphIndex == glyph) {
1029 return charCode;
1030 }
1031 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1032 }
1033
1034 return 0;
1035}
1036
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001037static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
1038 return SkFixedToScalar(x);
1039}
1040
reed@android.com8a1c16f2008-12-17 15:59:43 +00001041void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001042 /* unhinted and light hinted text have linearly scaled advances
1043 * which are very cheap to compute with some font formats...
1044 */
reed@google.combdc99882011-11-21 14:36:57 +00001045 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001046 SkAutoMutexAcquire ac(gFTMutex);
1047
1048 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001049 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001050 return;
1051 }
1052
1053 FT_Error error;
1054 FT_Fixed advance;
1055
djsollen1b277042014-08-06 06:58:06 -07001056 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001057 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1058 &advance );
1059 if (0 == error) {
1060 glyph->fRsbDelta = 0;
1061 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001062 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1063 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001064 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001065 return;
1066 }
1067 }
bungeman5ec443c2014-11-21 13:18:34 -08001068
reed@android.com8a1c16f2008-12-17 15:59:43 +00001069 /* otherwise, we need to load/hint the glyph, which is slower */
1070 this->generateMetrics(glyph);
1071 return;
1072}
1073
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001074void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1075 FT_BBox* bbox,
1076 bool snapToPixelBoundary) {
1077
1078 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1079
1080 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001081 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1082 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001083 // negate dy since freetype-y-goes-up and skia-y-goes-down
1084 bbox->xMin += dx;
1085 bbox->yMin -= dy;
1086 bbox->xMax += dx;
1087 bbox->yMax -= dy;
1088 }
1089
1090 // outset the box to integral boundaries
1091 if (snapToPixelBoundary) {
1092 bbox->xMin &= ~63;
1093 bbox->yMin &= ~63;
1094 bbox->xMax = (bbox->xMax + 63) & ~63;
1095 bbox->yMax = (bbox->yMax + 63) & ~63;
1096 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001097
1098 // Must come after snapToPixelBoundary so that the width and height are
1099 // consistent. Otherwise asserts will fire later on when generating the
1100 // glyph image.
1101 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1102 FT_Vector vector;
1103 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1104 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1105 FT_Vector_Transform(&vector, &fMatrix22);
1106 bbox->xMin += vector.x;
1107 bbox->xMax += vector.x;
1108 bbox->yMin += vector.y;
1109 bbox->yMax += vector.y;
1110 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001111}
1112
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001113bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1114 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001115 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001116 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001117 }
1118 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001119 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001120 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001121 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001122 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1123 return true;
1124}
1125
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001126void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1127 if (isLCD(fRec)) {
1128 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001129 glyph->fHeight += gFTLibrary->lcdExtra();
1130 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001131 } else {
bungeman9dc24682014-12-01 14:01:32 -08001132 glyph->fWidth += gFTLibrary->lcdExtra();
1133 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001134 }
1135 }
1136}
1137
bungeman401ae2d2016-07-18 15:46:27 -07001138bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1139 // If subpixel rendering of a bitmap *can* be done.
1140 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1141 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1142 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001143
bungeman401ae2d2016-07-18 15:46:27 -07001144 // If subpixel rendering of a bitmap *should* be done.
1145 // 1. If the face is not scalable then always allow subpixel rendering.
1146 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1147 // 2. If the matrix is already not identity the bitmap will already be resampled,
1148 // so resampling slightly differently shouldn't make much difference.
1149 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1150
1151 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001152}
1153
reed@android.com8a1c16f2008-12-17 15:59:43 +00001154void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1155 SkAutoMutexAcquire ac(gFTMutex);
1156
1157 glyph->fRsbDelta = 0;
1158 glyph->fLsbDelta = 0;
1159
1160 FT_Error err;
1161
1162 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001163 glyph->zeroMetrics();
1164 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001165 }
1166
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001167 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1168 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001169 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001170 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001171 return;
1172 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001173 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001174
1175 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001176 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001177 if (0 == fFace->glyph->outline.n_contours) {
1178 glyph->fWidth = 0;
1179 glyph->fHeight = 0;
1180 glyph->fTop = 0;
1181 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001182 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001183 FT_BBox bbox;
1184 getBBoxForCurrentGlyph(glyph, &bbox, true);
1185
1186 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1187 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1188 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1189 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1190
1191 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001192 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193 break;
1194
1195 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001196 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1197 FT_Vector vector;
1198 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1199 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1200 FT_Vector_Transform(&vector, &fMatrix22);
1201 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1202 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1203 }
1204
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001205 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1206 glyph->fMaskFormat = SkMask::kARGB32_Format;
1207 }
1208
bungeman401ae2d2016-07-18 15:46:27 -07001209 {
1210 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1211 -SkIntToScalar(fFace->glyph->bitmap_top),
1212 SkIntToScalar(fFace->glyph->bitmap.width),
1213 SkIntToScalar(fFace->glyph->bitmap.rows));
1214 fMatrix22Scalar.mapRect(&rect);
1215 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1216 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1217 SkFixedToScalar(glyph->getSubYFixed()));
1218 }
1219 SkIRect irect = rect.roundOut();
1220 glyph->fWidth = SkToU16(irect.width());
1221 glyph->fHeight = SkToU16(irect.height());
1222 glyph->fTop = SkToS16(irect.top());
1223 glyph->fLeft = SkToS16(irect.left());
1224 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001225 break;
1226
1227 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001228 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001229 glyph->zeroMetrics();
1230 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001231 }
1232
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001233 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1234 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001235 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001236 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001237 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001238 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001239 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1240 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001241 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001242 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001243 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001244 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1245 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001246 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001247 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001248 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1249 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001250
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001251 if (fRec.fFlags & kDevKernText_Flag) {
1252 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1253 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001254 }
1255 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001256 }
1257
reed@android.com8a1c16f2008-12-17 15:59:43 +00001258#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001259 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001260#endif
1261}
1262
bungeman5ec443c2014-11-21 13:18:34 -08001263static void clear_glyph_image(const SkGlyph& glyph) {
1264 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1265}
reed@google.comea2333d2011-03-14 16:44:56 +00001266
bungeman@google.coma76de722012-10-26 19:35:54 +00001267void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001268 SkAutoMutexAcquire ac(gFTMutex);
1269
reed@android.com8a1c16f2008-12-17 15:59:43 +00001270 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001271 clear_glyph_image(glyph);
1272 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001273 }
1274
bungeman5ec443c2014-11-21 13:18:34 -08001275 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001276 if (err != 0) {
1277 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 -08001278 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1279 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001280 return;
1281 }
1282
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001283 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001284 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1285 SkMatrix subpixelBitmapMatrix;
1286 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1287 subpixelBitmapMatrix = fMatrix22Scalar;
1288 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1289 SkFixedToScalar(glyph.getSubYFixed()));
1290 bitmapMatrix = &subpixelBitmapMatrix;
1291 }
1292 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001293}
1294
reed@android.com8a1c16f2008-12-17 15:59:43 +00001295
Ben Wagner6e9ac122016-11-11 14:31:06 -05001296void SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001297 SkAutoMutexAcquire ac(gFTMutex);
1298
caryclarka10742c2014-09-18 11:00:40 -07001299 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001300
1301 if (this->setupSize()) {
1302 path->reset();
1303 return;
1304 }
1305
1306 uint32_t flags = fLoadGlyphFlags;
1307 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1308 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1309
Ben Wagner6e9ac122016-11-11 14:31:06 -05001310 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001311
1312 if (err != 0) {
1313 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
Ben Wagner6e9ac122016-11-11 14:31:06 -05001314 glyphID, flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001315 path->reset();
1316 return;
1317 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001318 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001319
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001320 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001321
1322 // The path's origin from FreeType is always the horizontal layout origin.
1323 // Offset the path so that it is relative to the vertical origin if needed.
1324 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1325 FT_Vector vector;
1326 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1327 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1328 FT_Vector_Transform(&vector, &fMatrix22);
1329 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1330 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001331}
1332
bungeman41078062014-07-07 08:16:37 -07001333void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001334 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001335 return;
1336 }
1337
bungeman41078062014-07-07 08:16:37 -07001338 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001339
1340 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001341 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001342 return;
1343 }
1344
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001345 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001346
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001347 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1348 SkScalar upem = SkIntToScalar(face->units_per_EM);
1349 if (!upem) {
1350 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1351 if (ttHeader) {
1352 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001353 }
1354 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001355
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001356 // use the os/2 table as a source of reasonable defaults.
1357 SkScalar x_height = 0.0f;
1358 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001359 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001360 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1361 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001362 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001363 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001364 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001365 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001366 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001367 }
1368
1369 // pull from format-specific metrics as needed
1370 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001371 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001372 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001373 // FreeType will always use HHEA metrics if they're not zero.
1374 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1375 // It also ignores the VDMX tables, which are also of interest here
1376 // (and override everything else when they apply).
1377 static const int kUseTypoMetricsMask = (1 << 7);
1378 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1379 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1380 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1381 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1382 } else {
1383 ascent = -SkIntToScalar(face->ascender) / upem;
1384 descent = -SkIntToScalar(face->descender) / upem;
1385 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1386 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001387 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1388 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1389 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1390 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001391 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001392 underlinePosition = -SkIntToScalar(face->underline_position +
1393 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001394
bungeman41078062014-07-07 08:16:37 -07001395 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1396 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1397
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001398 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001399 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001400 FT_BBox bbox;
1401 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001402 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1403 }
1404 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001405 if (!cap_height) {
1406 FT_BBox bbox;
1407 if (getCBoxForLetter('H', &bbox)) {
1408 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1409 }
1410 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001411 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1412 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1413 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1414 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1415 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001416 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001417 xmin = 0.0f;
1418 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1419 ymin = descent + leading;
1420 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001421 underlineThickness = 0;
1422 underlinePosition = 0;
1423
bungeman41078062014-07-07 08:16:37 -07001424 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1425 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001426 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001427 sk_bzero(metrics, sizeof(*metrics));
1428 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001429 }
1430
1431 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1432 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001433 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001434 }
1435 if (!avgCharWidth) {
1436 avgCharWidth = xmax - xmin;
1437 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001438 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001439 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001440 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001441
1442 // disallow negative linespacing
1443 if (leading < 0.0f) {
1444 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001445 }
1446
bungeman53790512016-07-21 13:32:09 -07001447 metrics->fTop = ymax * fScale.y();
1448 metrics->fAscent = ascent * fScale.y();
1449 metrics->fDescent = descent * fScale.y();
1450 metrics->fBottom = ymin * fScale.y();
1451 metrics->fLeading = leading * fScale.y();
1452 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1453 metrics->fXMin = xmin * fScale.y();
1454 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001455 metrics->fXHeight = x_height;
1456 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001457 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1458 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001459}
1460
djsollenfcfea992015-01-09 08:18:13 -08001461///////////////////////////////////////////////////////////////////////////////
1462
1463// hand-tuned value to reduce outline embolden strength
1464#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1465 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1466 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1467 #else
1468 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1469 #endif
1470#endif
1471
1472///////////////////////////////////////////////////////////////////////////////
1473
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001474void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1475{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001476 // check to see if the embolden bit is set
1477 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1478 return;
1479 }
1480
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001481 switch (glyph->format) {
1482 case FT_GLYPH_FORMAT_OUTLINE:
1483 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001484 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1485 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001486 FT_Outline_Embolden(&glyph->outline, strength);
1487 break;
1488 case FT_GLYPH_FORMAT_BITMAP:
1489 FT_GlyphSlot_Own_Bitmap(glyph);
1490 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1491 break;
1492 default:
1493 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001494 }
1495}
1496
reed@google.comb4162b12013-07-02 16:32:29 +00001497///////////////////////////////////////////////////////////////////////////////
1498
1499#include "SkUtils.h"
1500
1501static SkUnichar next_utf8(const void** chars) {
1502 return SkUTF8_NextUnichar((const char**)chars);
1503}
1504
1505static SkUnichar next_utf16(const void** chars) {
1506 return SkUTF16_NextUnichar((const uint16_t**)chars);
1507}
1508
1509static SkUnichar next_utf32(const void** chars) {
1510 const SkUnichar** uniChars = (const SkUnichar**)chars;
1511 SkUnichar uni = **uniChars;
1512 *uniChars += 1;
1513 return uni;
1514}
1515
1516typedef SkUnichar (*EncodingProc)(const void**);
1517
1518static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1519 static const EncodingProc gProcs[] = {
1520 next_utf8, next_utf16, next_utf32
1521 };
1522 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1523 return gProcs[enc];
1524}
1525
1526int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001527 uint16_t glyphs[], int glyphCount) const
1528{
reed@google.comb4162b12013-07-02 16:32:29 +00001529 AutoFTAccess fta(this);
1530 FT_Face face = fta.face();
1531 if (!face) {
1532 if (glyphs) {
1533 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1534 }
1535 return 0;
1536 }
1537
1538 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1539
halcanary96fcdcc2015-08-27 07:41:13 -07001540 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001541 for (int i = 0; i < glyphCount; ++i) {
1542 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1543 return i;
1544 }
1545 }
1546 return glyphCount;
1547 } else {
1548 int first = glyphCount;
1549 for (int i = 0; i < glyphCount; ++i) {
1550 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1551 glyphs[i] = SkToU16(id);
1552 if (0 == id && i < first) {
1553 first = i;
1554 }
1555 }
1556 return first;
1557 }
1558}
1559
1560int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001561 AutoFTAccess fta(this);
1562 FT_Face face = fta.face();
1563 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001564}
1565
bungeman@google.com839702b2013-08-07 17:09:22 +00001566SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001567 SkTypeface::LocalizedStrings* nameIter =
1568 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001569 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001570 SkString familyName;
1571 this->getFamilyName(&familyName);
1572 SkString language("und"); //undetermined
1573 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1574 }
1575 return nameIter;
1576}
1577
Ben Wagnerfc497342017-02-24 11:15:26 -05001578int SkTypeface_FreeType::onGetVariationDesignPosition(
1579 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1580{
1581 AutoFTAccess fta(this);
1582 FT_Face face = fta.face();
1583
Ben Wagnere7e54992017-03-02 11:48:38 -05001584 if (!face || !(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001585 return 0;
1586 }
1587
1588 FT_MM_Var* variations = nullptr;
1589 if (FT_Get_MM_Var(face, &variations)) {
1590 return 0;
1591 }
1592 SkAutoFree autoFreeVariations(variations);
1593
1594 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1595 return variations->num_axis;
1596 }
1597
1598 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1599 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1600 if (gFTLibrary->fGetVarDesignCoordinates &&
1601 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1602 {
1603 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1604 coordinates[i].axis = variations->axis[i].tag;
1605 coordinates[i].value = SkFixedToScalar(coords[i]);
1606 }
1607 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1608 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1609 coordinates[i].axis = variations->axis[i].tag;
1610 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1611 }
1612 } else if (fta.isNamedVariationSpecified()) {
1613 // The font has axes, they cannot be retrieved, and some named axis was specified.
1614 return -1;
1615 } else {
1616 // The font has axes, they cannot be retrieved, but no named instance was specified.
1617 return 0;
1618 }
1619
1620 return variations->num_axis;
1621}
1622
bungeman@google.comddc218e2013-08-01 22:29:43 +00001623int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1624 AutoFTAccess fta(this);
1625 FT_Face face = fta.face();
1626
1627 FT_ULong tableCount = 0;
1628 FT_Error error;
1629
halcanary96fcdcc2015-08-27 07:41:13 -07001630 // When 'tag' is nullptr, returns number of tables in 'length'.
1631 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001632 if (error) {
1633 return 0;
1634 }
1635
1636 if (tags) {
1637 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1638 FT_ULong tableTag;
1639 FT_ULong tablelength;
1640 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1641 if (error) {
1642 return 0;
1643 }
1644 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1645 }
1646 }
1647 return tableCount;
1648}
1649
1650size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1651 size_t length, void* data) const
1652{
1653 AutoFTAccess fta(this);
1654 FT_Face face = fta.face();
1655
1656 FT_ULong tableLength = 0;
1657 FT_Error error;
1658
1659 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001660 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001661 if (error) {
1662 return 0;
1663 }
1664
1665 if (offset > tableLength) {
1666 return 0;
1667 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001668 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001669 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001670 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1671 if (error) {
1672 return 0;
1673 }
1674 }
1675
1676 return size;
1677}
1678
reed@google.comb4162b12013-07-02 16:32:29 +00001679///////////////////////////////////////////////////////////////////////////////
1680///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001681
halcanary96fcdcc2015-08-27 07:41:13 -07001682SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001683 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1684 return;
bungeman14df8332014-10-28 15:07:23 -07001685 }
bungeman9dc24682014-12-01 14:01:32 -08001686 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001687}
1688SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001689 if (fLibrary) {
1690 FT_Done_Library(fLibrary);
1691 }
bungeman14df8332014-10-28 15:07:23 -07001692}
1693
bungemanf93d7112016-09-16 06:24:20 -07001694FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001695 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001696{
halcanary96fcdcc2015-08-27 07:41:13 -07001697 if (fLibrary == nullptr) {
1698 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001699 }
1700
bungeman14df8332014-10-28 15:07:23 -07001701 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001702 memset(&args, 0, sizeof(args));
1703
1704 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001705
bsalomon49f085d2014-09-05 13:34:00 -07001706 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001707 args.flags = FT_OPEN_MEMORY;
1708 args.memory_base = (const FT_Byte*)memoryBase;
1709 args.memory_size = stream->getLength();
1710 } else {
bungeman14df8332014-10-28 15:07:23 -07001711 memset(ftStream, 0, sizeof(*ftStream));
1712 ftStream->size = stream->getLength();
1713 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001714 ftStream->read = sk_ft_stream_io;
1715 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001716
1717 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001718 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001719 }
1720
1721 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001722 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001723 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001724 }
1725 return face;
1726}
1727
bungemanf93d7112016-09-16 06:24:20 -07001728bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001729 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1730
1731 FT_StreamRec streamRec;
1732 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001733 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001734 return false;
1735 }
1736
1737 *numFaces = face->num_faces;
1738
1739 FT_Done_Face(face);
1740 return true;
1741}
1742
1743#include "SkTSearch.h"
1744bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001745 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001746 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001747{
1748 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1749
1750 FT_StreamRec streamRec;
1751 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001752 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001753 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001754 }
1755
bungemana4c4a2d2014-10-20 13:33:19 -07001756 int weight = SkFontStyle::kNormal_Weight;
1757 int width = SkFontStyle::kNormal_Width;
1758 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001759 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001760 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001761 }
1762 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001763 slant = SkFontStyle::kItalic_Slant;
1764 }
1765
1766 PS_FontInfoRec psFontInfo;
1767 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1768 if (os2 && os2->version != 0xffff) {
1769 weight = os2->usWeightClass;
1770 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001771
1772 // OS/2::fsSelection bit 9 indicates oblique.
1773 if (SkToBool(os2->fsSelection & (1u << 9))) {
1774 slant = SkFontStyle::kOblique_Slant;
1775 }
bungemana4c4a2d2014-10-20 13:33:19 -07001776 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1777 static const struct {
1778 char const * const name;
1779 int const weight;
1780 } commonWeights [] = {
1781 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001782 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001783 { "black", SkFontStyle::kBlack_Weight },
1784 { "bold", SkFontStyle::kBold_Weight },
1785 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1786 { "demi", SkFontStyle::kSemiBold_Weight },
1787 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001788 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001789 { "extrabold", SkFontStyle::kExtraBold_Weight },
1790 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001791 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001792 { "heavy", SkFontStyle::kBlack_Weight },
1793 { "light", SkFontStyle::kLight_Weight },
1794 { "medium", SkFontStyle::kMedium_Weight },
1795 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001796 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001797 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001798 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001799 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001800 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001801 { "thin", SkFontStyle::kThin_Weight },
1802 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001803 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001804 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001805 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001806 { "ultralight", SkFontStyle::kExtraLight_Weight },
1807 };
1808 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001809 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001810 if (index >= 0) {
1811 weight = commonWeights[index].weight;
1812 } else {
bungeman14df8332014-10-28 15:07:23 -07001813 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001814 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001815 }
1816
1817 if (name) {
1818 name->set(face->family_name);
1819 }
1820 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001821 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001822 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001823 if (isFixedPitch) {
1824 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001825 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001826
bungeman41868fe2015-05-20 09:21:04 -07001827 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001828 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001829 FT_Error err = FT_Get_MM_Var(face, &variations);
1830 if (err) {
1831 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1832 face->family_name));
1833 return false;
1834 }
1835 SkAutoFree autoFreeVariations(variations);
1836
1837 axes->reset(variations->num_axis);
1838 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1839 const FT_Var_Axis& ftAxis = variations->axis[i];
1840 (*axes)[i].fTag = ftAxis.tag;
1841 (*axes)[i].fMinimum = ftAxis.minimum;
1842 (*axes)[i].fDefault = ftAxis.def;
1843 (*axes)[i].fMaximum = ftAxis.maximum;
1844 }
1845 }
bungeman41868fe2015-05-20 09:21:04 -07001846
reed@android.com8a1c16f2008-12-17 15:59:43 +00001847 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001848 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001849}
bungemanf6c71072016-01-21 14:17:47 -08001850
1851/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1852 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001853 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001854 SkFixed* axisValues,
1855 const SkString& name)
1856{
1857 for (int i = 0; i < axisDefinitions.count(); ++i) {
1858 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001859 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1860 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001861 axisValues[i] = axisDefinition.fDefault;
Ben Wagnerfc497342017-02-24 11:15:26 -05001862 for (int j = 0; j < position.coordinateCount; ++j) {
1863 const auto& coordinate = position.coordinates[j];
1864 if (axisDefinition.fTag == coordinate.axis) {
1865 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1866 if (coordinate.value != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001867 SkDEBUGF(("Requested font axis value out of range: "
1868 "%s '%c%c%c%c' %f; pinned to %f.\n",
1869 name.c_str(),
1870 (axisDefinition.fTag >> 24) & 0xFF,
1871 (axisDefinition.fTag >> 16) & 0xFF,
1872 (axisDefinition.fTag >> 8) & 0xFF,
1873 (axisDefinition.fTag ) & 0xFF,
Ben Wagnerfc497342017-02-24 11:15:26 -05001874 SkScalarToDouble(coordinate.value),
benjaminwagner64a3c952016-02-25 12:20:40 -08001875 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001876 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001877 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001878 break;
1879 }
1880 }
1881 // TODO: warn on defaulted axis?
1882 }
1883
1884 SkDEBUGCODE(
1885 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001886 for (int i = 0; i < position.coordinateCount; ++i) {
1887 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001888 bool found = false;
1889 for (int j = 0; j < axisDefinitions.count(); ++j) {
1890 if (skTag == axisDefinitions[j].fTag) {
1891 found = true;
1892 break;
1893 }
1894 }
1895 if (!found) {
1896 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1897 name.c_str(),
1898 (skTag >> 24) & 0xFF,
1899 (skTag >> 16) & 0xFF,
1900 (skTag >> 8) & 0xFF,
1901 (skTag) & 0xFF));
1902 }
1903 }
1904 )
1905}