blob: eee76d5730839f189ee361efb3e79169753df352 [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
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000564 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000565 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000566 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000567 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000568 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000569 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000570 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000571 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000572 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
bungeman@google.com4d71db82013-12-02 19:10:02 +0000573 } else {
574 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000575 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000576
halcanary32875882016-08-16 09:36:23 -0700577 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700578 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000579 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700580 }
581 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000582 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700583 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000584
bungemanf1491692016-07-22 11:19:24 -0700585 PS_FontInfoRec psFontInfo;
586 TT_Postscript* postTable;
587 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
588 info->fItalicAngle = psFontInfo.italic_angle;
589 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
590 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000591 } else {
592 info->fItalicAngle = 0;
593 }
594
595 info->fAscent = face->ascender;
596 info->fDescent = face->descender;
597
598 // Figure out a good guess for StemV - Min width of i, I, !, 1.
599 // This probably isn't very good with an italic font.
600 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000601 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000602 char stem_chars[] = {'i', 'I', '!', '1'};
603 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
604 FT_BBox bbox;
605 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
606 int16_t width = bbox.xMax - bbox.xMin;
607 if (width > 0 && width < min_width) {
608 min_width = width;
609 info->fStemV = min_width;
610 }
611 }
612 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000613
bungemanf1491692016-07-22 11:19:24 -0700614 TT_PCLT* pcltTable;
615 TT_OS2* os2Table;
616 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
617 info->fCapHeight = pcltTable->CapHeight;
618 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
619 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000620 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700621 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000622 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700623 }
624 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000625 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700626 os2Table->version != 0xFFFF &&
627 os2Table->version >= 2)
628 {
629 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000630 } else {
631 // Figure out a good guess for CapHeight: average the height of M and X.
632 FT_BBox m_bbox, x_bbox;
633 bool got_m, got_x;
634 got_m = GetLetterCBox(face, 'M', &m_bbox);
635 got_x = GetLetterCBox(face, 'X', &x_bbox);
636 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700637 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000638 } else if (got_m && !got_x) {
639 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
640 } else if (!got_m && got_x) {
641 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000642 } else {
643 // Last resort, use the ascent.
644 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000645 }
646 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000647
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000648 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
649 face->bbox.xMax, face->bbox.yMin);
650
vandebo0f9bad02014-06-19 11:05:39 -0700651 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700652 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000653 }
654
reed39a9a502015-05-12 09:50:04 -0700655 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700656 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
657 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000658 // Postscript fonts may contain more than 255 glyphs, so we end up
659 // using multiple font descriptions with a glyph ordering. Record
660 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700661 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000662 for (int gID = 0; gID < face->num_glyphs; gID++) {
663 char glyphName[128]; // PS limit for names is 127 bytes.
664 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700665 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000666 }
667 }
668
reed39a9a502015-05-12 09:50:04 -0700669 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700670 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
671 face->num_charmaps)
672 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000673 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
674 }
675
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000676 return info;
677}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000678
reed@google.com618ef5e2011-01-26 22:10:41 +0000679///////////////////////////////////////////////////////////////////////////
680
reed@google.com8ed436c2011-07-21 14:12:36 +0000681static bool bothZero(SkScalar a, SkScalar b) {
682 return 0 == a && 0 == b;
683}
684
685// returns false if there is any non-90-rotation or skew
686static bool isAxisAligned(const SkScalerContext::Rec& rec) {
687 return 0 == rec.fPreSkewX &&
688 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
689 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
690}
691
reeda9322c22016-04-12 06:47:05 -0700692SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
693 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400694 auto c = skstd::make_unique<SkScalerContext_FreeType>(
695 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000696 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400697 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000698 }
bungeman7cfd46a2016-10-20 16:06:52 -0400699 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000700}
701
702void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000703 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
704 //Cap the requested size as larger sizes give bogus values.
705 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800706 //Note that this also currently only protects against large text size requests,
707 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000708 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000709 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000710 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000711
bungemanec7e12f2015-01-21 11:55:16 -0800712 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800713 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
714 SkAutoMutexAcquire ama(gFTMutex);
715 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800716 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800717 // If the runtime Freetype library doesn't support LCD, disable it here.
718 rec->fMaskFormat = SkMask::kA8_Format;
719 }
720 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000721 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000722
reed@google.com618ef5e2011-01-26 22:10:41 +0000723 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000724 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000725 // collapse full->normal hinting if we're not doing LCD
726 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000727 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000728 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000729 if (SkPaint::kNo_Hinting != h) {
730 h = SkPaint::kSlight_Hinting;
731 }
732 }
733
reed@google.com8ed436c2011-07-21 14:12:36 +0000734 // rotated text looks bad with hinting, so we disable it as needed
735 if (!isAxisAligned(*rec)) {
736 h = SkPaint::kNo_Hinting;
737 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000738 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000739
bungeman@google.com97efada2012-07-30 20:40:50 +0000740#ifndef SK_GAMMA_APPLY_TO_A8
741 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700742 // SRGBTODO: Is this correct? Do we want contrast boost?
743 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000744 }
reed@google.com1ac83502012-02-28 17:06:02 +0000745#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000746}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000747
reed@google.com38c37dd2013-03-21 15:36:26 +0000748int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000749 AutoFTAccess fta(this);
750 FT_Face face = fta.face();
751 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000752}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000753
reed@google.com35fe7372013-10-30 15:07:03 +0000754bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
755 int count, int32_t adjustments[]) const {
756 AutoFTAccess fta(this);
757 FT_Face face = fta.face();
758 if (!face || !FT_HAS_KERNING(face)) {
759 return false;
760 }
761
762 for (int i = 0; i < count - 1; ++i) {
763 FT_Vector delta;
764 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
765 FT_KERNING_UNSCALED, &delta);
766 if (err) {
767 return false;
768 }
769 adjustments[i] = delta.x;
770 }
771 return true;
772}
773
bungeman401ae2d2016-07-18 15:46:27 -0700774/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800775static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700776 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700777 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000778 return -1;
779 }
bungeman401ae2d2016-07-18 15:46:27 -0700780
781 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000782 FT_Int chosenStrikeIndex = -1;
783 FT_Pos chosenPPEM = 0;
784 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700785 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
786 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000787 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700788 return strikeIndex;
789 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000790 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700791 if (chosenPPEM < strikePPEM) {
792 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000793 chosenStrikeIndex = strikeIndex;
794 }
795 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700796 // attempt to decrease chosenPPEM, but not below requestedPPEM
797 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
798 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000799 chosenStrikeIndex = strikeIndex;
800 }
801 }
802 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000803 return chosenStrikeIndex;
804}
805
bungeman7cfd46a2016-10-20 16:06:52 -0400806SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700807 const SkScalerContextEffects& effects,
808 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400809 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800810 , fFace(nullptr)
811 , fFTSize(nullptr)
812 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700813{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000814 SkAutoMutexAcquire ac(gFTMutex);
815
bungeman9dc24682014-12-01 14:01:32 -0800816 if (!ref_ft_library()) {
817 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000818 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000819
Ben Wagnerfc497342017-02-24 11:15:26 -0500820 fFaceRec.reset(ref_ft_face(this->getTypeface()));
821
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500823 if (nullptr == fFaceRec) {
bungemanaabd71c2016-03-01 15:15:09 -0800824 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000825 return;
826 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000827
bungeman5f14c5e2014-12-05 12:26:44 -0800828 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000829
bungeman401ae2d2016-07-18 15:46:27 -0700830 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
831 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000832 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700833 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
834 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000835 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000836
reed@google.coma1bfa212012-03-08 21:57:12 +0000837 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
838
reed@android.com8a1c16f2008-12-17 15:59:43 +0000839 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000840 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000841 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000842 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000843
agl@chromium.org70a303f2010-05-10 14:15:50 +0000844 if (SkMask::kBW_Format == fRec.fMaskFormat) {
845 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
846 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000847 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000848 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000849 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000850 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000851 } else {
852 switch (fRec.getHinting()) {
853 case SkPaint::kNo_Hinting:
854 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000855 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000856 break;
857 case SkPaint::kSlight_Hinting:
858 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
859 break;
860 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000861 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000862 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700863#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
864 } else {
865 loadFlags = FT_LOAD_NO_AUTOHINT;
866#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000867 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000868 break;
869 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000870 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000871 loadFlags = FT_LOAD_FORCE_AUTOHINT;
872 break;
873 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000874 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000875 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000876 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000877 loadFlags = FT_LOAD_TARGET_LCD_V;
878 } else {
879 loadFlags = FT_LOAD_TARGET_LCD;
880 }
reed@google.comea2333d2011-03-14 16:44:56 +0000881 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000882 break;
883 default:
884 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
885 break;
886 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000887 }
888
reed@google.comeffc5012011-06-27 16:44:46 +0000889 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000890 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000891 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000892
reed@google.com96a9f7912011-05-06 11:49:30 +0000893 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
894 // advances, as fontconfig and cairo do.
895 // See http://code.google.com/p/skia/issues/detail?id=222.
896 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
897
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000898 // Use vertical layout if requested.
899 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
900 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
901 }
902
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000903 loadFlags |= FT_LOAD_COLOR;
904
reed@android.come4d0bc02009-07-24 19:53:20 +0000905 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000906 }
907
bungemanaabd71c2016-03-01 15:15:09 -0800908 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500909 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800910 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500911 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800912 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500913 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800914 return nullptr;
915 }
916 return size;
917 }());
918 if (nullptr == ftSize) {
919 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000920 return;
921 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000922
bungemanaabd71c2016-03-01 15:15:09 -0800923 FT_Error err = FT_Activate_Size(ftSize.get());
924 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500925 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800926 return;
927 }
928
Ben Wagnerfc497342017-02-24 11:15:26 -0500929 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
930 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000931 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700932 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500933 fFaceRec->fFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000934 return;
935 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500936 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
937 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000938 if (fStrikeIndex == -1) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500939 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n",
940 fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700941 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000942 }
bungeman401ae2d2016-07-18 15:46:27 -0700943
Ben Wagnerfc497342017-02-24 11:15:26 -0500944 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700945 if (err != 0) {
946 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500947 fFaceRec->fFace->family_name, fStrikeIndex, err));
bungeman401ae2d2016-07-18 15:46:27 -0700948 fStrikeIndex = -1;
949 return;
950 }
951
952 // A non-ideal size was picked, so recompute the matrix.
953 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
Ben Wagnerfc497342017-02-24 11:15:26 -0500954 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
955 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700956 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
957 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
958 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
959 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
960
961 // FreeType does not provide linear metrics for bitmap fonts.
962 linearMetrics = false;
963
964 // FreeType documentation says:
965 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
966 // Bitmap-only fonts ignore this flag.
967 //
968 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
969 // Force this flag off for bitmap only fonts.
970 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000971 } else {
Ben Wagnerfc497342017-02-24 11:15:26 -0500972 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700973 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000974 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000975
bungemanaabd71c2016-03-01 15:15:09 -0800976 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500977 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000978 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000979}
980
981SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000982 SkAutoMutexAcquire ac(gFTMutex);
983
halcanary96fcdcc2015-08-27 07:41:13 -0700984 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000985 FT_Done_Size(fFTSize);
986 }
987
Ben Wagnerfc497342017-02-24 11:15:26 -0500988 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -0800989
990 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000991}
992
993/* We call this before each use of the fFace, since we may be sharing
994 this face with other context (at different sizes).
995*/
996FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800997 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000998 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000999 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001000 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001001 }
halcanary96fcdcc2015-08-27 07:41:13 -07001002 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001003 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001004}
1005
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001006unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001007 return fFace->num_glyphs;
1008}
1009
1010uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -08001011 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001012 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1013}
1014
reed@android.com9d3a9852010-01-08 14:07:42 +00001015SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -08001016 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +00001017 // iterate through each cmap entry, looking for matching glyph indices
1018 FT_UInt glyphIndex;
1019 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1020
1021 while (glyphIndex != 0) {
1022 if (glyphIndex == glyph) {
1023 return charCode;
1024 }
1025 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1026 }
1027
1028 return 0;
1029}
1030
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001031static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
1032 return SkFixedToScalar(x);
1033}
1034
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001036 /* unhinted and light hinted text have linearly scaled advances
1037 * which are very cheap to compute with some font formats...
1038 */
reed@google.combdc99882011-11-21 14:36:57 +00001039 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001040 SkAutoMutexAcquire ac(gFTMutex);
1041
1042 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001043 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001044 return;
1045 }
1046
1047 FT_Error error;
1048 FT_Fixed advance;
1049
djsollen1b277042014-08-06 06:58:06 -07001050 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001051 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1052 &advance );
1053 if (0 == error) {
1054 glyph->fRsbDelta = 0;
1055 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001056 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1057 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001058 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001059 return;
1060 }
1061 }
bungeman5ec443c2014-11-21 13:18:34 -08001062
reed@android.com8a1c16f2008-12-17 15:59:43 +00001063 /* otherwise, we need to load/hint the glyph, which is slower */
1064 this->generateMetrics(glyph);
1065 return;
1066}
1067
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001068void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1069 FT_BBox* bbox,
1070 bool snapToPixelBoundary) {
1071
1072 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1073
1074 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001075 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1076 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001077 // negate dy since freetype-y-goes-up and skia-y-goes-down
1078 bbox->xMin += dx;
1079 bbox->yMin -= dy;
1080 bbox->xMax += dx;
1081 bbox->yMax -= dy;
1082 }
1083
1084 // outset the box to integral boundaries
1085 if (snapToPixelBoundary) {
1086 bbox->xMin &= ~63;
1087 bbox->yMin &= ~63;
1088 bbox->xMax = (bbox->xMax + 63) & ~63;
1089 bbox->yMax = (bbox->yMax + 63) & ~63;
1090 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001091
1092 // Must come after snapToPixelBoundary so that the width and height are
1093 // consistent. Otherwise asserts will fire later on when generating the
1094 // glyph image.
1095 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1096 FT_Vector vector;
1097 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1098 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1099 FT_Vector_Transform(&vector, &fMatrix22);
1100 bbox->xMin += vector.x;
1101 bbox->xMax += vector.x;
1102 bbox->yMin += vector.y;
1103 bbox->yMax += vector.y;
1104 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001105}
1106
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001107bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1108 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001109 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001110 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001111 }
1112 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001113 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001114 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001115 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001116 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1117 return true;
1118}
1119
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001120void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1121 if (isLCD(fRec)) {
1122 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001123 glyph->fHeight += gFTLibrary->lcdExtra();
1124 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001125 } else {
bungeman9dc24682014-12-01 14:01:32 -08001126 glyph->fWidth += gFTLibrary->lcdExtra();
1127 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001128 }
1129 }
1130}
1131
bungeman401ae2d2016-07-18 15:46:27 -07001132bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1133 // If subpixel rendering of a bitmap *can* be done.
1134 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1135 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1136 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001137
bungeman401ae2d2016-07-18 15:46:27 -07001138 // If subpixel rendering of a bitmap *should* be done.
1139 // 1. If the face is not scalable then always allow subpixel rendering.
1140 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1141 // 2. If the matrix is already not identity the bitmap will already be resampled,
1142 // so resampling slightly differently shouldn't make much difference.
1143 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1144
1145 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001146}
1147
reed@android.com8a1c16f2008-12-17 15:59:43 +00001148void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1149 SkAutoMutexAcquire ac(gFTMutex);
1150
1151 glyph->fRsbDelta = 0;
1152 glyph->fLsbDelta = 0;
1153
1154 FT_Error err;
1155
1156 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001157 glyph->zeroMetrics();
1158 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001159 }
1160
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001161 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1162 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001163 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001164 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001165 return;
1166 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001167 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001168
1169 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001170 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001171 if (0 == fFace->glyph->outline.n_contours) {
1172 glyph->fWidth = 0;
1173 glyph->fHeight = 0;
1174 glyph->fTop = 0;
1175 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001176 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001177 FT_BBox bbox;
1178 getBBoxForCurrentGlyph(glyph, &bbox, true);
1179
1180 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1181 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1182 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1183 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1184
1185 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001186 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001187 break;
1188
1189 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001190 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1191 FT_Vector vector;
1192 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1193 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1194 FT_Vector_Transform(&vector, &fMatrix22);
1195 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1196 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1197 }
1198
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001199 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1200 glyph->fMaskFormat = SkMask::kARGB32_Format;
1201 }
1202
bungeman401ae2d2016-07-18 15:46:27 -07001203 {
1204 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1205 -SkIntToScalar(fFace->glyph->bitmap_top),
1206 SkIntToScalar(fFace->glyph->bitmap.width),
1207 SkIntToScalar(fFace->glyph->bitmap.rows));
1208 fMatrix22Scalar.mapRect(&rect);
1209 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1210 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1211 SkFixedToScalar(glyph->getSubYFixed()));
1212 }
1213 SkIRect irect = rect.roundOut();
1214 glyph->fWidth = SkToU16(irect.width());
1215 glyph->fHeight = SkToU16(irect.height());
1216 glyph->fTop = SkToS16(irect.top());
1217 glyph->fLeft = SkToS16(irect.left());
1218 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001219 break;
1220
1221 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001222 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001223 glyph->zeroMetrics();
1224 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001225 }
1226
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001227 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1228 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001229 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001230 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001231 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001232 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001233 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1234 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001235 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001236 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001237 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001238 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1239 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001240 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001241 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001242 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1243 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001244
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001245 if (fRec.fFlags & kDevKernText_Flag) {
1246 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1247 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001248 }
1249 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001250 }
1251
reed@android.com8a1c16f2008-12-17 15:59:43 +00001252#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001253 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001254#endif
1255}
1256
bungeman5ec443c2014-11-21 13:18:34 -08001257static void clear_glyph_image(const SkGlyph& glyph) {
1258 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1259}
reed@google.comea2333d2011-03-14 16:44:56 +00001260
bungeman@google.coma76de722012-10-26 19:35:54 +00001261void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001262 SkAutoMutexAcquire ac(gFTMutex);
1263
reed@android.com8a1c16f2008-12-17 15:59:43 +00001264 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001265 clear_glyph_image(glyph);
1266 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001267 }
1268
bungeman5ec443c2014-11-21 13:18:34 -08001269 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001270 if (err != 0) {
1271 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 -08001272 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1273 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001274 return;
1275 }
1276
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001277 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001278 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1279 SkMatrix subpixelBitmapMatrix;
1280 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1281 subpixelBitmapMatrix = fMatrix22Scalar;
1282 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1283 SkFixedToScalar(glyph.getSubYFixed()));
1284 bitmapMatrix = &subpixelBitmapMatrix;
1285 }
1286 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001287}
1288
reed@android.com8a1c16f2008-12-17 15:59:43 +00001289
Ben Wagner6e9ac122016-11-11 14:31:06 -05001290void SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001291 SkAutoMutexAcquire ac(gFTMutex);
1292
caryclarka10742c2014-09-18 11:00:40 -07001293 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001294
1295 if (this->setupSize()) {
1296 path->reset();
1297 return;
1298 }
1299
1300 uint32_t flags = fLoadGlyphFlags;
1301 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1302 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1303
Ben Wagner6e9ac122016-11-11 14:31:06 -05001304 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001305
1306 if (err != 0) {
1307 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
Ben Wagner6e9ac122016-11-11 14:31:06 -05001308 glyphID, flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001309 path->reset();
1310 return;
1311 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001312 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001313
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001314 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001315
1316 // The path's origin from FreeType is always the horizontal layout origin.
1317 // Offset the path so that it is relative to the vertical origin if needed.
1318 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1319 FT_Vector vector;
1320 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1321 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1322 FT_Vector_Transform(&vector, &fMatrix22);
1323 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1324 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001325}
1326
bungeman41078062014-07-07 08:16:37 -07001327void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001328 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001329 return;
1330 }
1331
bungeman41078062014-07-07 08:16:37 -07001332 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001333
1334 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001335 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001336 return;
1337 }
1338
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001339 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001340
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001341 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1342 SkScalar upem = SkIntToScalar(face->units_per_EM);
1343 if (!upem) {
1344 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1345 if (ttHeader) {
1346 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001347 }
1348 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001349
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001350 // use the os/2 table as a source of reasonable defaults.
1351 SkScalar x_height = 0.0f;
1352 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001353 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001354 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1355 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001356 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001357 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001358 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001359 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001360 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001361 }
1362
1363 // pull from format-specific metrics as needed
1364 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001365 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001366 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001367 // FreeType will always use HHEA metrics if they're not zero.
1368 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1369 // It also ignores the VDMX tables, which are also of interest here
1370 // (and override everything else when they apply).
1371 static const int kUseTypoMetricsMask = (1 << 7);
1372 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1373 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1374 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1375 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1376 } else {
1377 ascent = -SkIntToScalar(face->ascender) / upem;
1378 descent = -SkIntToScalar(face->descender) / upem;
1379 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1380 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001381 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1382 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1383 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1384 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001385 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001386 underlinePosition = -SkIntToScalar(face->underline_position +
1387 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001388
bungeman41078062014-07-07 08:16:37 -07001389 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1390 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1391
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001392 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001393 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001394 FT_BBox bbox;
1395 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001396 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1397 }
1398 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001399 if (!cap_height) {
1400 FT_BBox bbox;
1401 if (getCBoxForLetter('H', &bbox)) {
1402 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1403 }
1404 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001405 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1406 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1407 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1408 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1409 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001410 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001411 xmin = 0.0f;
1412 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1413 ymin = descent + leading;
1414 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001415 underlineThickness = 0;
1416 underlinePosition = 0;
1417
bungeman41078062014-07-07 08:16:37 -07001418 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1419 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001420 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001421 sk_bzero(metrics, sizeof(*metrics));
1422 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001423 }
1424
1425 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1426 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001427 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001428 }
1429 if (!avgCharWidth) {
1430 avgCharWidth = xmax - xmin;
1431 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001432 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001433 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001434 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001435
1436 // disallow negative linespacing
1437 if (leading < 0.0f) {
1438 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001439 }
1440
bungeman53790512016-07-21 13:32:09 -07001441 metrics->fTop = ymax * fScale.y();
1442 metrics->fAscent = ascent * fScale.y();
1443 metrics->fDescent = descent * fScale.y();
1444 metrics->fBottom = ymin * fScale.y();
1445 metrics->fLeading = leading * fScale.y();
1446 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1447 metrics->fXMin = xmin * fScale.y();
1448 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001449 metrics->fXHeight = x_height;
1450 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001451 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1452 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001453}
1454
djsollenfcfea992015-01-09 08:18:13 -08001455///////////////////////////////////////////////////////////////////////////////
1456
1457// hand-tuned value to reduce outline embolden strength
1458#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1459 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1460 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1461 #else
1462 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1463 #endif
1464#endif
1465
1466///////////////////////////////////////////////////////////////////////////////
1467
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001468void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1469{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001470 // check to see if the embolden bit is set
1471 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1472 return;
1473 }
1474
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001475 switch (glyph->format) {
1476 case FT_GLYPH_FORMAT_OUTLINE:
1477 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001478 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1479 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001480 FT_Outline_Embolden(&glyph->outline, strength);
1481 break;
1482 case FT_GLYPH_FORMAT_BITMAP:
1483 FT_GlyphSlot_Own_Bitmap(glyph);
1484 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1485 break;
1486 default:
1487 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001488 }
1489}
1490
reed@google.comb4162b12013-07-02 16:32:29 +00001491///////////////////////////////////////////////////////////////////////////////
1492
1493#include "SkUtils.h"
1494
1495static SkUnichar next_utf8(const void** chars) {
1496 return SkUTF8_NextUnichar((const char**)chars);
1497}
1498
1499static SkUnichar next_utf16(const void** chars) {
1500 return SkUTF16_NextUnichar((const uint16_t**)chars);
1501}
1502
1503static SkUnichar next_utf32(const void** chars) {
1504 const SkUnichar** uniChars = (const SkUnichar**)chars;
1505 SkUnichar uni = **uniChars;
1506 *uniChars += 1;
1507 return uni;
1508}
1509
1510typedef SkUnichar (*EncodingProc)(const void**);
1511
1512static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1513 static const EncodingProc gProcs[] = {
1514 next_utf8, next_utf16, next_utf32
1515 };
1516 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1517 return gProcs[enc];
1518}
1519
1520int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001521 uint16_t glyphs[], int glyphCount) const
1522{
reed@google.comb4162b12013-07-02 16:32:29 +00001523 AutoFTAccess fta(this);
1524 FT_Face face = fta.face();
1525 if (!face) {
1526 if (glyphs) {
1527 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1528 }
1529 return 0;
1530 }
1531
1532 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1533
halcanary96fcdcc2015-08-27 07:41:13 -07001534 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001535 for (int i = 0; i < glyphCount; ++i) {
1536 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1537 return i;
1538 }
1539 }
1540 return glyphCount;
1541 } else {
1542 int first = glyphCount;
1543 for (int i = 0; i < glyphCount; ++i) {
1544 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1545 glyphs[i] = SkToU16(id);
1546 if (0 == id && i < first) {
1547 first = i;
1548 }
1549 }
1550 return first;
1551 }
1552}
1553
1554int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001555 AutoFTAccess fta(this);
1556 FT_Face face = fta.face();
1557 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001558}
1559
bungeman@google.com839702b2013-08-07 17:09:22 +00001560SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001561 SkTypeface::LocalizedStrings* nameIter =
1562 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001563 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001564 SkString familyName;
1565 this->getFamilyName(&familyName);
1566 SkString language("und"); //undetermined
1567 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1568 }
1569 return nameIter;
1570}
1571
Ben Wagnerfc497342017-02-24 11:15:26 -05001572int SkTypeface_FreeType::onGetVariationDesignPosition(
1573 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1574{
1575 AutoFTAccess fta(this);
1576 FT_Face face = fta.face();
1577
Ben Wagnere7e54992017-03-02 11:48:38 -05001578 if (!face || !(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001579 return 0;
1580 }
1581
1582 FT_MM_Var* variations = nullptr;
1583 if (FT_Get_MM_Var(face, &variations)) {
1584 return 0;
1585 }
1586 SkAutoFree autoFreeVariations(variations);
1587
1588 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1589 return variations->num_axis;
1590 }
1591
1592 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1593 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1594 if (gFTLibrary->fGetVarDesignCoordinates &&
1595 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1596 {
1597 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1598 coordinates[i].axis = variations->axis[i].tag;
1599 coordinates[i].value = SkFixedToScalar(coords[i]);
1600 }
1601 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1602 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1603 coordinates[i].axis = variations->axis[i].tag;
1604 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1605 }
1606 } else if (fta.isNamedVariationSpecified()) {
1607 // The font has axes, they cannot be retrieved, and some named axis was specified.
1608 return -1;
1609 } else {
1610 // The font has axes, they cannot be retrieved, but no named instance was specified.
1611 return 0;
1612 }
1613
1614 return variations->num_axis;
1615}
1616
bungeman@google.comddc218e2013-08-01 22:29:43 +00001617int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1618 AutoFTAccess fta(this);
1619 FT_Face face = fta.face();
1620
1621 FT_ULong tableCount = 0;
1622 FT_Error error;
1623
halcanary96fcdcc2015-08-27 07:41:13 -07001624 // When 'tag' is nullptr, returns number of tables in 'length'.
1625 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001626 if (error) {
1627 return 0;
1628 }
1629
1630 if (tags) {
1631 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1632 FT_ULong tableTag;
1633 FT_ULong tablelength;
1634 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1635 if (error) {
1636 return 0;
1637 }
1638 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1639 }
1640 }
1641 return tableCount;
1642}
1643
1644size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1645 size_t length, void* data) const
1646{
1647 AutoFTAccess fta(this);
1648 FT_Face face = fta.face();
1649
1650 FT_ULong tableLength = 0;
1651 FT_Error error;
1652
1653 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001654 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001655 if (error) {
1656 return 0;
1657 }
1658
1659 if (offset > tableLength) {
1660 return 0;
1661 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001662 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001663 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001664 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1665 if (error) {
1666 return 0;
1667 }
1668 }
1669
1670 return size;
1671}
1672
reed@google.comb4162b12013-07-02 16:32:29 +00001673///////////////////////////////////////////////////////////////////////////////
1674///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001675
halcanary96fcdcc2015-08-27 07:41:13 -07001676SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001677 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1678 return;
bungeman14df8332014-10-28 15:07:23 -07001679 }
bungeman9dc24682014-12-01 14:01:32 -08001680 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001681}
1682SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001683 if (fLibrary) {
1684 FT_Done_Library(fLibrary);
1685 }
bungeman14df8332014-10-28 15:07:23 -07001686}
1687
bungemanf93d7112016-09-16 06:24:20 -07001688FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001689 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001690{
halcanary96fcdcc2015-08-27 07:41:13 -07001691 if (fLibrary == nullptr) {
1692 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001693 }
1694
bungeman14df8332014-10-28 15:07:23 -07001695 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001696 memset(&args, 0, sizeof(args));
1697
1698 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001699
bsalomon49f085d2014-09-05 13:34:00 -07001700 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001701 args.flags = FT_OPEN_MEMORY;
1702 args.memory_base = (const FT_Byte*)memoryBase;
1703 args.memory_size = stream->getLength();
1704 } else {
bungeman14df8332014-10-28 15:07:23 -07001705 memset(ftStream, 0, sizeof(*ftStream));
1706 ftStream->size = stream->getLength();
1707 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001708 ftStream->read = sk_ft_stream_io;
1709 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001710
1711 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001712 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001713 }
1714
1715 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001716 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001717 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001718 }
1719 return face;
1720}
1721
bungemanf93d7112016-09-16 06:24:20 -07001722bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001723 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1724
1725 FT_StreamRec streamRec;
1726 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001727 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001728 return false;
1729 }
1730
1731 *numFaces = face->num_faces;
1732
1733 FT_Done_Face(face);
1734 return true;
1735}
1736
1737#include "SkTSearch.h"
1738bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001739 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001740 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001741{
1742 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1743
1744 FT_StreamRec streamRec;
1745 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001746 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001747 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001748 }
1749
bungemana4c4a2d2014-10-20 13:33:19 -07001750 int weight = SkFontStyle::kNormal_Weight;
1751 int width = SkFontStyle::kNormal_Width;
1752 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001753 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001754 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001755 }
1756 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001757 slant = SkFontStyle::kItalic_Slant;
1758 }
1759
1760 PS_FontInfoRec psFontInfo;
1761 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1762 if (os2 && os2->version != 0xffff) {
1763 weight = os2->usWeightClass;
1764 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001765
1766 // OS/2::fsSelection bit 9 indicates oblique.
1767 if (SkToBool(os2->fsSelection & (1u << 9))) {
1768 slant = SkFontStyle::kOblique_Slant;
1769 }
bungemana4c4a2d2014-10-20 13:33:19 -07001770 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1771 static const struct {
1772 char const * const name;
1773 int const weight;
1774 } commonWeights [] = {
1775 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001776 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001777 { "black", SkFontStyle::kBlack_Weight },
1778 { "bold", SkFontStyle::kBold_Weight },
1779 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1780 { "demi", SkFontStyle::kSemiBold_Weight },
1781 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001782 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001783 { "extrabold", SkFontStyle::kExtraBold_Weight },
1784 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001785 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001786 { "heavy", SkFontStyle::kBlack_Weight },
1787 { "light", SkFontStyle::kLight_Weight },
1788 { "medium", SkFontStyle::kMedium_Weight },
1789 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001790 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001791 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001792 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001793 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001794 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001795 { "thin", SkFontStyle::kThin_Weight },
1796 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001797 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001798 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001799 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001800 { "ultralight", SkFontStyle::kExtraLight_Weight },
1801 };
1802 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001803 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001804 if (index >= 0) {
1805 weight = commonWeights[index].weight;
1806 } else {
bungeman14df8332014-10-28 15:07:23 -07001807 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001808 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001809 }
1810
1811 if (name) {
1812 name->set(face->family_name);
1813 }
1814 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001815 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001816 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001817 if (isFixedPitch) {
1818 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001819 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001820
bungeman41868fe2015-05-20 09:21:04 -07001821 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001822 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001823 FT_Error err = FT_Get_MM_Var(face, &variations);
1824 if (err) {
1825 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1826 face->family_name));
1827 return false;
1828 }
1829 SkAutoFree autoFreeVariations(variations);
1830
1831 axes->reset(variations->num_axis);
1832 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1833 const FT_Var_Axis& ftAxis = variations->axis[i];
1834 (*axes)[i].fTag = ftAxis.tag;
1835 (*axes)[i].fMinimum = ftAxis.minimum;
1836 (*axes)[i].fDefault = ftAxis.def;
1837 (*axes)[i].fMaximum = ftAxis.maximum;
1838 }
1839 }
bungeman41868fe2015-05-20 09:21:04 -07001840
reed@android.com8a1c16f2008-12-17 15:59:43 +00001841 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001842 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001843}
bungemanf6c71072016-01-21 14:17:47 -08001844
1845/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1846 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001847 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001848 SkFixed* axisValues,
1849 const SkString& name)
1850{
1851 for (int i = 0; i < axisDefinitions.count(); ++i) {
1852 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001853 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1854 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001855 axisValues[i] = axisDefinition.fDefault;
Ben Wagnerfc497342017-02-24 11:15:26 -05001856 for (int j = 0; j < position.coordinateCount; ++j) {
1857 const auto& coordinate = position.coordinates[j];
1858 if (axisDefinition.fTag == coordinate.axis) {
1859 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1860 if (coordinate.value != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001861 SkDEBUGF(("Requested font axis value out of range: "
1862 "%s '%c%c%c%c' %f; pinned to %f.\n",
1863 name.c_str(),
1864 (axisDefinition.fTag >> 24) & 0xFF,
1865 (axisDefinition.fTag >> 16) & 0xFF,
1866 (axisDefinition.fTag >> 8) & 0xFF,
1867 (axisDefinition.fTag ) & 0xFF,
Ben Wagnerfc497342017-02-24 11:15:26 -05001868 SkScalarToDouble(coordinate.value),
benjaminwagner64a3c952016-02-25 12:20:40 -08001869 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001870 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001871 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001872 break;
1873 }
1874 }
1875 // TODO: warn on defaulted axis?
1876 }
1877
1878 SkDEBUGCODE(
1879 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001880 for (int i = 0; i < position.coordinateCount; ++i) {
1881 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001882 bool found = false;
1883 for (int j = 0; j < axisDefinitions.count(); ++j) {
1884 if (skTag == axisDefinitions[j].fTag) {
1885 found = true;
1886 break;
1887 }
1888 }
1889 if (!found) {
1890 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1891 name.c_str(),
1892 (skTag >> 24) & 0xFF,
1893 (skTag >> 16) & 0xFF,
1894 (skTag >> 8) & 0xFF,
1895 (skTag) & 0xFF));
1896 }
1897 }
1898 )
1899}