blob: d155308074f424be4f4cb131c520d8536478f054 [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.
Ben Wagnerf1b61af2017-03-09 15:12:09 -0500391// Marked extern because vc++ does not support internal linkage template parameters.
392extern /*static*/ void unref_ft_face(SkFaceRec* faceRec) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500393 gFTMutex.assertHeld();
394
395 SkFaceRec* rec = gFaceRecHead;
396 SkFaceRec* prev = nullptr;
397 while (rec) {
398 SkFaceRec* next = rec->fNext;
399 if (rec->fFace == faceRec->fFace) {
400 if (--rec->fRefCnt == 0) {
401 if (prev) {
402 prev->fNext = next;
403 } else {
404 gFaceRecHead = next;
405 }
406 delete rec;
407 }
408 return;
409 }
410 prev = rec;
411 rec = next;
412 }
413 SkDEBUGFAIL("shouldn't get here, face not in list");
414}
415
416class AutoFTAccess {
417public:
418 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
419 gFTMutex.acquire();
420 if (!ref_ft_library()) {
421 sk_throw();
422 }
423 fFaceRec = ref_ft_face(tf);
424 }
425
426 ~AutoFTAccess() {
427 if (fFaceRec) {
428 unref_ft_face(fFaceRec);
429 }
430 unref_ft_library();
431 gFTMutex.release();
432 }
433
434 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
435 int getAxesCount() { return fFaceRec ? fFaceRec->fAxesCount : 0; }
436 SkFixed* getAxes() { return fFaceRec ? fFaceRec->fAxes.get() : nullptr; }
437 bool isNamedVariationSpecified() {
438 return fFaceRec ? fFaceRec->fNamedVariationSpecified : false;
439 }
440
441private:
442 SkFaceRec* fFaceRec;
443};
444
445///////////////////////////////////////////////////////////////////////////
446
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000447class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000448public:
bungeman7cfd46a2016-10-20 16:06:52 -0400449 SkScalerContext_FreeType(sk_sp<SkTypeface>,
450 const SkScalerContextEffects&,
451 const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000452 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000453
reed@android.com62900b42009-02-11 15:07:19 +0000454 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700455 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000456 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000457
458protected:
mtklein36352bf2015-03-25 18:17:31 -0700459 unsigned generateGlyphCount() override;
460 uint16_t generateCharToGlyph(SkUnichar uni) override;
461 void generateAdvance(SkGlyph* glyph) override;
462 void generateMetrics(SkGlyph* glyph) override;
463 void generateImage(const SkGlyph& glyph) override;
Ben Wagner6e9ac122016-11-11 14:31:06 -0500464 void generatePath(SkGlyphID glyphID, SkPath* path) override;
mtklein36352bf2015-03-25 18:17:31 -0700465 void generateFontMetrics(SkPaint::FontMetrics*) override;
466 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000467
468private:
Ben Wagnerfc497342017-02-24 11:15:26 -0500469 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
470 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
471
472 FT_Face fFace; // Borrowed face from gFaceRecHead.
bungeman401ae2d2016-07-18 15:46:27 -0700473 FT_Size fFTSize; // The size on the fFace for this scaler.
474 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000475
bungeman401ae2d2016-07-18 15:46:27 -0700476 /** The rest of the matrix after FreeType handles the size.
477 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
478 * With bitmap only fonts this matrix must be applied to scale the bitmap.
479 */
480 SkMatrix fMatrix22Scalar;
481 /** Same as fMatrix22Scalar, but in FreeType units and space. */
482 FT_Matrix fMatrix22;
483 /** The actual size requested. */
484 SkVector fScale;
485
486 uint32_t fLoadGlyphFlags;
487 bool fDoLinearMetrics;
488 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000489
reed@android.com8a1c16f2008-12-17 15:59:43 +0000490 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000491 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
492 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000493 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000494 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000495 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000496 // Caller must lock gFTMutex before calling this function.
497 // update FreeType2 glyph slot with glyph emboldened
498 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
bungeman401ae2d2016-07-18 15:46:27 -0700499 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000500};
501
502///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000503
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000504static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000505 FT_UShort fsType = FT_Get_FSType_Flags(face);
506 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
507 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000508}
509
vandebo0f9bad02014-06-19 11:05:39 -0700510static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700511 FT_UShort fsType = FT_Get_FSType_Flags(face);
512 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700513}
514
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000515static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
516 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
517 if (!glyph_id)
518 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000519 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
520 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
522 return true;
523}
524
bungeman5ec443c2014-11-21 13:18:34 -0800525static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
halcanaryf8c74a12016-04-20 08:37:43 -0700526 FT_Long numGlyphs = face->num_glyphs;
527 glyphToUnicode->setCount(SkToInt(numGlyphs));
528 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000529
bungeman726cf902015-06-05 13:38:12 -0700530 FT_UInt glyphIndex;
531 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
532 while (glyphIndex) {
halcanaryf8c74a12016-04-20 08:37:43 -0700533 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
halcanary5f1d0f62016-09-13 08:08:38 -0700534 // Use the first character that maps to this glyphID. https://crbug.com/359065
535 if (0 == (*glyphToUnicode)[glyphIndex]) {
536 (*glyphToUnicode)[glyphIndex] = charCode;
537 }
bungeman726cf902015-06-05 13:38:12 -0700538 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000539 }
540}
541
reed@google.com2689f612013-03-20 20:01:47 +0000542SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700543 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000544 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000545 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000546 AutoFTAccess fta(this);
547 FT_Face face = fta.face();
548 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700549 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000550 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000551
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000552 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
553 info->fFontName.set(FT_Get_Postscript_Name(face));
halcanary32875882016-08-16 09:36:23 -0700554
vandebo0f9bad02014-06-19 11:05:39 -0700555 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700556 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700557 }
558 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700559 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700560 }
561 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700562 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700563 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000564
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000565 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000566 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000567 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000568 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000569 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000570 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000571 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000572 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000573 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
bungeman@google.com4d71db82013-12-02 19:10:02 +0000574 } else {
575 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000576 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000577
halcanary32875882016-08-16 09:36:23 -0700578 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700579 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000580 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700581 }
582 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000583 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700584 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000585
bungemanf1491692016-07-22 11:19:24 -0700586 PS_FontInfoRec psFontInfo;
587 TT_Postscript* postTable;
588 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
589 info->fItalicAngle = psFontInfo.italic_angle;
590 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
591 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000592 } else {
593 info->fItalicAngle = 0;
594 }
595
596 info->fAscent = face->ascender;
597 info->fDescent = face->descender;
598
599 // Figure out a good guess for StemV - Min width of i, I, !, 1.
600 // This probably isn't very good with an italic font.
601 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000602 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000603 char stem_chars[] = {'i', 'I', '!', '1'};
604 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
605 FT_BBox bbox;
606 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
607 int16_t width = bbox.xMax - bbox.xMin;
608 if (width > 0 && width < min_width) {
609 min_width = width;
610 info->fStemV = min_width;
611 }
612 }
613 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000614
bungemanf1491692016-07-22 11:19:24 -0700615 TT_PCLT* pcltTable;
616 TT_OS2* os2Table;
617 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
618 info->fCapHeight = pcltTable->CapHeight;
619 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
620 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000621 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700622 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000623 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700624 }
625 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000626 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700627 os2Table->version != 0xFFFF &&
628 os2Table->version >= 2)
629 {
630 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000631 } else {
632 // Figure out a good guess for CapHeight: average the height of M and X.
633 FT_BBox m_bbox, x_bbox;
634 bool got_m, got_x;
635 got_m = GetLetterCBox(face, 'M', &m_bbox);
636 got_x = GetLetterCBox(face, 'X', &x_bbox);
637 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700638 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000639 } else if (got_m && !got_x) {
640 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
641 } else if (!got_m && got_x) {
642 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000643 } else {
644 // Last resort, use the ascent.
645 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000646 }
647 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000648
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000649 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
650 face->bbox.xMax, face->bbox.yMin);
651
vandebo0f9bad02014-06-19 11:05:39 -0700652 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700653 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000654 }
655
reed39a9a502015-05-12 09:50:04 -0700656 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700657 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
658 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000659 // Postscript fonts may contain more than 255 glyphs, so we end up
660 // using multiple font descriptions with a glyph ordering. Record
661 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700662 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000663 for (int gID = 0; gID < face->num_glyphs; gID++) {
664 char glyphName[128]; // PS limit for names is 127 bytes.
665 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700666 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000667 }
668 }
669
reed39a9a502015-05-12 09:50:04 -0700670 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700671 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
672 face->num_charmaps)
673 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000674 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
675 }
676
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000677 return info;
678}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000679
reed@google.com618ef5e2011-01-26 22:10:41 +0000680///////////////////////////////////////////////////////////////////////////
681
reed@google.com8ed436c2011-07-21 14:12:36 +0000682static bool bothZero(SkScalar a, SkScalar b) {
683 return 0 == a && 0 == b;
684}
685
686// returns false if there is any non-90-rotation or skew
687static bool isAxisAligned(const SkScalerContext::Rec& rec) {
688 return 0 == rec.fPreSkewX &&
689 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
690 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
691}
692
reeda9322c22016-04-12 06:47:05 -0700693SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
694 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400695 auto c = skstd::make_unique<SkScalerContext_FreeType>(
696 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000697 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400698 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000699 }
bungeman7cfd46a2016-10-20 16:06:52 -0400700 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000701}
702
703void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000704 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
705 //Cap the requested size as larger sizes give bogus values.
706 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800707 //Note that this also currently only protects against large text size requests,
708 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000709 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000710 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000711 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000712
bungemanec7e12f2015-01-21 11:55:16 -0800713 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800714 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
715 SkAutoMutexAcquire ama(gFTMutex);
716 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800717 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800718 // If the runtime Freetype library doesn't support LCD, disable it here.
719 rec->fMaskFormat = SkMask::kA8_Format;
720 }
721 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000722 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000723
reed@google.com618ef5e2011-01-26 22:10:41 +0000724 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000725 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000726 // collapse full->normal hinting if we're not doing LCD
727 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000728 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000729 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000730 if (SkPaint::kNo_Hinting != h) {
731 h = SkPaint::kSlight_Hinting;
732 }
733 }
734
reed@google.com8ed436c2011-07-21 14:12:36 +0000735 // rotated text looks bad with hinting, so we disable it as needed
736 if (!isAxisAligned(*rec)) {
737 h = SkPaint::kNo_Hinting;
738 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000739 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000740
bungeman@google.com97efada2012-07-30 20:40:50 +0000741#ifndef SK_GAMMA_APPLY_TO_A8
742 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700743 // SRGBTODO: Is this correct? Do we want contrast boost?
744 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000745 }
reed@google.com1ac83502012-02-28 17:06:02 +0000746#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000747}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000748
reed@google.com38c37dd2013-03-21 15:36:26 +0000749int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000750 AutoFTAccess fta(this);
751 FT_Face face = fta.face();
752 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000753}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000754
reed@google.com35fe7372013-10-30 15:07:03 +0000755bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
756 int count, int32_t adjustments[]) const {
757 AutoFTAccess fta(this);
758 FT_Face face = fta.face();
759 if (!face || !FT_HAS_KERNING(face)) {
760 return false;
761 }
762
763 for (int i = 0; i < count - 1; ++i) {
764 FT_Vector delta;
765 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
766 FT_KERNING_UNSCALED, &delta);
767 if (err) {
768 return false;
769 }
770 adjustments[i] = delta.x;
771 }
772 return true;
773}
774
bungeman401ae2d2016-07-18 15:46:27 -0700775/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800776static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700777 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700778 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000779 return -1;
780 }
bungeman401ae2d2016-07-18 15:46:27 -0700781
782 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000783 FT_Int chosenStrikeIndex = -1;
784 FT_Pos chosenPPEM = 0;
785 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700786 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
787 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000788 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700789 return strikeIndex;
790 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000791 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700792 if (chosenPPEM < strikePPEM) {
793 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000794 chosenStrikeIndex = strikeIndex;
795 }
796 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700797 // attempt to decrease chosenPPEM, but not below requestedPPEM
798 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
799 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000800 chosenStrikeIndex = strikeIndex;
801 }
802 }
803 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000804 return chosenStrikeIndex;
805}
806
bungeman7cfd46a2016-10-20 16:06:52 -0400807SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700808 const SkScalerContextEffects& effects,
809 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400810 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800811 , fFace(nullptr)
812 , fFTSize(nullptr)
813 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700814{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000815 SkAutoMutexAcquire ac(gFTMutex);
816
bungeman9dc24682014-12-01 14:01:32 -0800817 if (!ref_ft_library()) {
818 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000819 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820
Ben Wagnerfc497342017-02-24 11:15:26 -0500821 fFaceRec.reset(ref_ft_face(this->getTypeface()));
822
reed@android.com8a1c16f2008-12-17 15:59:43 +0000823 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500824 if (nullptr == fFaceRec) {
bungemanaabd71c2016-03-01 15:15:09 -0800825 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000826 return;
827 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000828
bungeman5f14c5e2014-12-05 12:26:44 -0800829 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000830
bungeman401ae2d2016-07-18 15:46:27 -0700831 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
832 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000833 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700834 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
835 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000836 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837
reed@google.coma1bfa212012-03-08 21:57:12 +0000838 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
839
reed@android.com8a1c16f2008-12-17 15:59:43 +0000840 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000841 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000842 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000843 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000844
agl@chromium.org70a303f2010-05-10 14:15:50 +0000845 if (SkMask::kBW_Format == fRec.fMaskFormat) {
846 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
847 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000848 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000849 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000850 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000851 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000852 } else {
853 switch (fRec.getHinting()) {
854 case SkPaint::kNo_Hinting:
855 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000856 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000857 break;
858 case SkPaint::kSlight_Hinting:
859 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
860 break;
861 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000862 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000863 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700864#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
865 } else {
866 loadFlags = FT_LOAD_NO_AUTOHINT;
867#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000868 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000869 break;
870 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000871 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000872 loadFlags = FT_LOAD_FORCE_AUTOHINT;
873 break;
874 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000875 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000876 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000877 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000878 loadFlags = FT_LOAD_TARGET_LCD_V;
879 } else {
880 loadFlags = FT_LOAD_TARGET_LCD;
881 }
reed@google.comea2333d2011-03-14 16:44:56 +0000882 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000883 break;
884 default:
885 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
886 break;
887 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000888 }
889
reed@google.comeffc5012011-06-27 16:44:46 +0000890 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000891 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000892 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000893
reed@google.com96a9f7912011-05-06 11:49:30 +0000894 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
895 // advances, as fontconfig and cairo do.
896 // See http://code.google.com/p/skia/issues/detail?id=222.
897 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
898
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000899 // Use vertical layout if requested.
900 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
901 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
902 }
903
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000904 loadFlags |= FT_LOAD_COLOR;
905
reed@android.come4d0bc02009-07-24 19:53:20 +0000906 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000907 }
908
bungemanaabd71c2016-03-01 15:15:09 -0800909 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
Ben Wagnerfc497342017-02-24 11:15:26 -0500910 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800911 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500912 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800913 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500914 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800915 return nullptr;
916 }
917 return size;
918 }());
919 if (nullptr == ftSize) {
920 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000921 return;
922 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000923
bungemanaabd71c2016-03-01 15:15:09 -0800924 FT_Error err = FT_Activate_Size(ftSize.get());
925 if (err != 0) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500926 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800927 return;
928 }
929
Ben Wagnerfc497342017-02-24 11:15:26 -0500930 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
931 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000932 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700933 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500934 fFaceRec->fFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000935 return;
936 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500937 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
938 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000939 if (fStrikeIndex == -1) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500940 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n",
941 fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700942 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000943 }
bungeman401ae2d2016-07-18 15:46:27 -0700944
Ben Wagnerfc497342017-02-24 11:15:26 -0500945 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700946 if (err != 0) {
947 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
Ben Wagnerfc497342017-02-24 11:15:26 -0500948 fFaceRec->fFace->family_name, fStrikeIndex, err));
bungeman401ae2d2016-07-18 15:46:27 -0700949 fStrikeIndex = -1;
950 return;
951 }
952
953 // A non-ideal size was picked, so recompute the matrix.
954 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
Ben Wagnerfc497342017-02-24 11:15:26 -0500955 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
956 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700957 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
958 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
959 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
960 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
961
962 // FreeType does not provide linear metrics for bitmap fonts.
963 linearMetrics = false;
964
965 // FreeType documentation says:
966 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
967 // Bitmap-only fonts ignore this flag.
968 //
969 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
970 // Force this flag off for bitmap only fonts.
971 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000972 } else {
Ben Wagnerfc497342017-02-24 11:15:26 -0500973 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY));
bungeman401ae2d2016-07-18 15:46:27 -0700974 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000975 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000976
bungemanaabd71c2016-03-01 15:15:09 -0800977 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500978 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000979 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000980}
981
982SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000983 SkAutoMutexAcquire ac(gFTMutex);
984
halcanary96fcdcc2015-08-27 07:41:13 -0700985 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000986 FT_Done_Size(fFTSize);
987 }
988
Ben Wagnerfc497342017-02-24 11:15:26 -0500989 fFaceRec = nullptr;
bungeman9dc24682014-12-01 14:01:32 -0800990
991 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000992}
993
994/* We call this before each use of the fFace, since we may be sharing
995 this face with other context (at different sizes).
996*/
997FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800998 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000999 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001000 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001001 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001002 }
halcanary96fcdcc2015-08-27 07:41:13 -07001003 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001004 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001005}
1006
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001007unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001008 return fFace->num_glyphs;
1009}
1010
1011uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -08001012 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1014}
1015
reed@android.com9d3a9852010-01-08 14:07:42 +00001016SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -08001017 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +00001018 // iterate through each cmap entry, looking for matching glyph indices
1019 FT_UInt glyphIndex;
1020 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1021
1022 while (glyphIndex != 0) {
1023 if (glyphIndex == glyph) {
1024 return charCode;
1025 }
1026 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1027 }
1028
1029 return 0;
1030}
1031
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001032static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
1033 return SkFixedToScalar(x);
1034}
1035
reed@android.com8a1c16f2008-12-17 15:59:43 +00001036void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001037 /* unhinted and light hinted text have linearly scaled advances
1038 * which are very cheap to compute with some font formats...
1039 */
reed@google.combdc99882011-11-21 14:36:57 +00001040 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001041 SkAutoMutexAcquire ac(gFTMutex);
1042
1043 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001044 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001045 return;
1046 }
1047
1048 FT_Error error;
1049 FT_Fixed advance;
1050
djsollen1b277042014-08-06 06:58:06 -07001051 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001052 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1053 &advance );
1054 if (0 == error) {
1055 glyph->fRsbDelta = 0;
1056 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001057 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1058 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001059 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001060 return;
1061 }
1062 }
bungeman5ec443c2014-11-21 13:18:34 -08001063
reed@android.com8a1c16f2008-12-17 15:59:43 +00001064 /* otherwise, we need to load/hint the glyph, which is slower */
1065 this->generateMetrics(glyph);
1066 return;
1067}
1068
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001069void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1070 FT_BBox* bbox,
1071 bool snapToPixelBoundary) {
1072
1073 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1074
1075 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001076 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1077 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001078 // negate dy since freetype-y-goes-up and skia-y-goes-down
1079 bbox->xMin += dx;
1080 bbox->yMin -= dy;
1081 bbox->xMax += dx;
1082 bbox->yMax -= dy;
1083 }
1084
1085 // outset the box to integral boundaries
1086 if (snapToPixelBoundary) {
1087 bbox->xMin &= ~63;
1088 bbox->yMin &= ~63;
1089 bbox->xMax = (bbox->xMax + 63) & ~63;
1090 bbox->yMax = (bbox->yMax + 63) & ~63;
1091 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001092
1093 // Must come after snapToPixelBoundary so that the width and height are
1094 // consistent. Otherwise asserts will fire later on when generating the
1095 // glyph image.
1096 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1097 FT_Vector vector;
1098 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1099 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1100 FT_Vector_Transform(&vector, &fMatrix22);
1101 bbox->xMin += vector.x;
1102 bbox->xMax += vector.x;
1103 bbox->yMin += vector.y;
1104 bbox->yMax += vector.y;
1105 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001106}
1107
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001108bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1109 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001110 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001111 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001112 }
1113 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001114 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001115 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001116 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001117 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1118 return true;
1119}
1120
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001121void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1122 if (isLCD(fRec)) {
1123 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001124 glyph->fHeight += gFTLibrary->lcdExtra();
1125 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001126 } else {
bungeman9dc24682014-12-01 14:01:32 -08001127 glyph->fWidth += gFTLibrary->lcdExtra();
1128 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001129 }
1130 }
1131}
1132
bungeman401ae2d2016-07-18 15:46:27 -07001133bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1134 // If subpixel rendering of a bitmap *can* be done.
1135 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1136 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1137 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001138
bungeman401ae2d2016-07-18 15:46:27 -07001139 // If subpixel rendering of a bitmap *should* be done.
1140 // 1. If the face is not scalable then always allow subpixel rendering.
1141 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1142 // 2. If the matrix is already not identity the bitmap will already be resampled,
1143 // so resampling slightly differently shouldn't make much difference.
1144 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1145
1146 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001147}
1148
reed@android.com8a1c16f2008-12-17 15:59:43 +00001149void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1150 SkAutoMutexAcquire ac(gFTMutex);
1151
1152 glyph->fRsbDelta = 0;
1153 glyph->fLsbDelta = 0;
1154
1155 FT_Error err;
1156
1157 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001158 glyph->zeroMetrics();
1159 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001160 }
1161
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001162 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1163 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001164 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001165 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001166 return;
1167 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001168 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001169
1170 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001171 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001172 if (0 == fFace->glyph->outline.n_contours) {
1173 glyph->fWidth = 0;
1174 glyph->fHeight = 0;
1175 glyph->fTop = 0;
1176 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001177 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001178 FT_BBox bbox;
1179 getBBoxForCurrentGlyph(glyph, &bbox, true);
1180
1181 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1182 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1183 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1184 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1185
1186 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001187 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188 break;
1189
1190 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001191 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1192 FT_Vector vector;
1193 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1194 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1195 FT_Vector_Transform(&vector, &fMatrix22);
1196 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1197 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1198 }
1199
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001200 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1201 glyph->fMaskFormat = SkMask::kARGB32_Format;
1202 }
1203
bungeman401ae2d2016-07-18 15:46:27 -07001204 {
1205 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1206 -SkIntToScalar(fFace->glyph->bitmap_top),
1207 SkIntToScalar(fFace->glyph->bitmap.width),
1208 SkIntToScalar(fFace->glyph->bitmap.rows));
1209 fMatrix22Scalar.mapRect(&rect);
1210 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1211 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1212 SkFixedToScalar(glyph->getSubYFixed()));
1213 }
1214 SkIRect irect = rect.roundOut();
1215 glyph->fWidth = SkToU16(irect.width());
1216 glyph->fHeight = SkToU16(irect.height());
1217 glyph->fTop = SkToS16(irect.top());
1218 glyph->fLeft = SkToS16(irect.left());
1219 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001220 break;
1221
1222 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001223 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001224 glyph->zeroMetrics();
1225 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001226 }
1227
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001228 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1229 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001230 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001231 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001232 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001233 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001234 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1235 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001236 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001237 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001238 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001239 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1240 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001241 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001242 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001243 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1244 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001245
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001246 if (fRec.fFlags & kDevKernText_Flag) {
1247 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1248 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001249 }
1250 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001251 }
1252
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001254 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001255#endif
1256}
1257
bungeman5ec443c2014-11-21 13:18:34 -08001258static void clear_glyph_image(const SkGlyph& glyph) {
1259 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1260}
reed@google.comea2333d2011-03-14 16:44:56 +00001261
bungeman@google.coma76de722012-10-26 19:35:54 +00001262void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001263 SkAutoMutexAcquire ac(gFTMutex);
1264
reed@android.com8a1c16f2008-12-17 15:59:43 +00001265 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001266 clear_glyph_image(glyph);
1267 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001268 }
1269
bungeman5ec443c2014-11-21 13:18:34 -08001270 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001271 if (err != 0) {
1272 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 -08001273 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1274 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001275 return;
1276 }
1277
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001278 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001279 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1280 SkMatrix subpixelBitmapMatrix;
1281 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1282 subpixelBitmapMatrix = fMatrix22Scalar;
1283 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1284 SkFixedToScalar(glyph.getSubYFixed()));
1285 bitmapMatrix = &subpixelBitmapMatrix;
1286 }
1287 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001288}
1289
reed@android.com8a1c16f2008-12-17 15:59:43 +00001290
Ben Wagner6e9ac122016-11-11 14:31:06 -05001291void SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001292 SkAutoMutexAcquire ac(gFTMutex);
1293
caryclarka10742c2014-09-18 11:00:40 -07001294 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001295
1296 if (this->setupSize()) {
1297 path->reset();
1298 return;
1299 }
1300
1301 uint32_t flags = fLoadGlyphFlags;
1302 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1303 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1304
Ben Wagner6e9ac122016-11-11 14:31:06 -05001305 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001306
1307 if (err != 0) {
1308 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
Ben Wagner6e9ac122016-11-11 14:31:06 -05001309 glyphID, flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001310 path->reset();
1311 return;
1312 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001313 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001315 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001316
1317 // The path's origin from FreeType is always the horizontal layout origin.
1318 // Offset the path so that it is relative to the vertical origin if needed.
1319 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1320 FT_Vector vector;
1321 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1322 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1323 FT_Vector_Transform(&vector, &fMatrix22);
1324 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1325 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001326}
1327
bungeman41078062014-07-07 08:16:37 -07001328void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001329 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330 return;
1331 }
1332
bungeman41078062014-07-07 08:16:37 -07001333 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001334
1335 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001336 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001337 return;
1338 }
1339
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001340 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001341
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001342 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1343 SkScalar upem = SkIntToScalar(face->units_per_EM);
1344 if (!upem) {
1345 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1346 if (ttHeader) {
1347 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001348 }
1349 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001350
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001351 // use the os/2 table as a source of reasonable defaults.
1352 SkScalar x_height = 0.0f;
1353 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001354 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001355 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1356 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001357 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001358 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001359 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001360 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001361 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001362 }
1363
1364 // pull from format-specific metrics as needed
1365 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001366 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001367 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001368 // FreeType will always use HHEA metrics if they're not zero.
1369 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1370 // It also ignores the VDMX tables, which are also of interest here
1371 // (and override everything else when they apply).
1372 static const int kUseTypoMetricsMask = (1 << 7);
1373 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1374 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1375 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1376 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1377 } else {
1378 ascent = -SkIntToScalar(face->ascender) / upem;
1379 descent = -SkIntToScalar(face->descender) / upem;
1380 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1381 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001382 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1383 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1384 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1385 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001386 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001387 underlinePosition = -SkIntToScalar(face->underline_position +
1388 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001389
bungeman41078062014-07-07 08:16:37 -07001390 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1391 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1392
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001393 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001394 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001395 FT_BBox bbox;
1396 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001397 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1398 }
1399 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001400 if (!cap_height) {
1401 FT_BBox bbox;
1402 if (getCBoxForLetter('H', &bbox)) {
1403 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1404 }
1405 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001406 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1407 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1408 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1409 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1410 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001411 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001412 xmin = 0.0f;
1413 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1414 ymin = descent + leading;
1415 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001416 underlineThickness = 0;
1417 underlinePosition = 0;
1418
bungeman41078062014-07-07 08:16:37 -07001419 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1420 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001421 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001422 sk_bzero(metrics, sizeof(*metrics));
1423 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001424 }
1425
1426 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1427 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001428 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001429 }
1430 if (!avgCharWidth) {
1431 avgCharWidth = xmax - xmin;
1432 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001433 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001434 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001435 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001436
1437 // disallow negative linespacing
1438 if (leading < 0.0f) {
1439 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001440 }
1441
bungeman53790512016-07-21 13:32:09 -07001442 metrics->fTop = ymax * fScale.y();
1443 metrics->fAscent = ascent * fScale.y();
1444 metrics->fDescent = descent * fScale.y();
1445 metrics->fBottom = ymin * fScale.y();
1446 metrics->fLeading = leading * fScale.y();
1447 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1448 metrics->fXMin = xmin * fScale.y();
1449 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001450 metrics->fXHeight = x_height;
1451 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001452 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1453 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001454}
1455
djsollenfcfea992015-01-09 08:18:13 -08001456///////////////////////////////////////////////////////////////////////////////
1457
1458// hand-tuned value to reduce outline embolden strength
1459#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1460 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1461 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1462 #else
1463 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1464 #endif
1465#endif
1466
1467///////////////////////////////////////////////////////////////////////////////
1468
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001469void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1470{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001471 // check to see if the embolden bit is set
1472 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1473 return;
1474 }
1475
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001476 switch (glyph->format) {
1477 case FT_GLYPH_FORMAT_OUTLINE:
1478 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001479 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1480 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001481 FT_Outline_Embolden(&glyph->outline, strength);
1482 break;
1483 case FT_GLYPH_FORMAT_BITMAP:
1484 FT_GlyphSlot_Own_Bitmap(glyph);
1485 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1486 break;
1487 default:
1488 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001489 }
1490}
1491
reed@google.comb4162b12013-07-02 16:32:29 +00001492///////////////////////////////////////////////////////////////////////////////
1493
1494#include "SkUtils.h"
1495
1496static SkUnichar next_utf8(const void** chars) {
1497 return SkUTF8_NextUnichar((const char**)chars);
1498}
1499
1500static SkUnichar next_utf16(const void** chars) {
1501 return SkUTF16_NextUnichar((const uint16_t**)chars);
1502}
1503
1504static SkUnichar next_utf32(const void** chars) {
1505 const SkUnichar** uniChars = (const SkUnichar**)chars;
1506 SkUnichar uni = **uniChars;
1507 *uniChars += 1;
1508 return uni;
1509}
1510
1511typedef SkUnichar (*EncodingProc)(const void**);
1512
1513static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1514 static const EncodingProc gProcs[] = {
1515 next_utf8, next_utf16, next_utf32
1516 };
1517 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1518 return gProcs[enc];
1519}
1520
1521int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001522 uint16_t glyphs[], int glyphCount) const
1523{
reed@google.comb4162b12013-07-02 16:32:29 +00001524 AutoFTAccess fta(this);
1525 FT_Face face = fta.face();
1526 if (!face) {
1527 if (glyphs) {
1528 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1529 }
1530 return 0;
1531 }
1532
1533 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1534
halcanary96fcdcc2015-08-27 07:41:13 -07001535 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001536 for (int i = 0; i < glyphCount; ++i) {
1537 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1538 return i;
1539 }
1540 }
1541 return glyphCount;
1542 } else {
1543 int first = glyphCount;
1544 for (int i = 0; i < glyphCount; ++i) {
1545 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1546 glyphs[i] = SkToU16(id);
1547 if (0 == id && i < first) {
1548 first = i;
1549 }
1550 }
1551 return first;
1552 }
1553}
1554
1555int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001556 AutoFTAccess fta(this);
1557 FT_Face face = fta.face();
1558 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001559}
1560
bungeman@google.com839702b2013-08-07 17:09:22 +00001561SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001562 SkTypeface::LocalizedStrings* nameIter =
1563 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001564 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001565 SkString familyName;
1566 this->getFamilyName(&familyName);
1567 SkString language("und"); //undetermined
1568 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1569 }
1570 return nameIter;
1571}
1572
Ben Wagnerfc497342017-02-24 11:15:26 -05001573int SkTypeface_FreeType::onGetVariationDesignPosition(
1574 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1575{
1576 AutoFTAccess fta(this);
1577 FT_Face face = fta.face();
1578
Ben Wagnere7e54992017-03-02 11:48:38 -05001579 if (!face || !(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -05001580 return 0;
1581 }
1582
1583 FT_MM_Var* variations = nullptr;
1584 if (FT_Get_MM_Var(face, &variations)) {
1585 return 0;
1586 }
1587 SkAutoFree autoFreeVariations(variations);
1588
1589 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1590 return variations->num_axis;
1591 }
1592
1593 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
1594 // FT_Get_{MM,Var}_{Blend,Design}_Coordinates were added in FreeType 2.7.1.
1595 if (gFTLibrary->fGetVarDesignCoordinates &&
1596 !gFTLibrary->fGetVarDesignCoordinates(face, variations->num_axis, coords.get()))
1597 {
1598 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1599 coordinates[i].axis = variations->axis[i].tag;
1600 coordinates[i].value = SkFixedToScalar(coords[i]);
1601 }
1602 } else if (static_cast<FT_UInt>(fta.getAxesCount()) == variations->num_axis) {
1603 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1604 coordinates[i].axis = variations->axis[i].tag;
1605 coordinates[i].value = SkFixedToScalar(fta.getAxes()[i]);
1606 }
1607 } else if (fta.isNamedVariationSpecified()) {
1608 // The font has axes, they cannot be retrieved, and some named axis was specified.
1609 return -1;
1610 } else {
1611 // The font has axes, they cannot be retrieved, but no named instance was specified.
1612 return 0;
1613 }
1614
1615 return variations->num_axis;
1616}
1617
bungeman@google.comddc218e2013-08-01 22:29:43 +00001618int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1619 AutoFTAccess fta(this);
1620 FT_Face face = fta.face();
1621
1622 FT_ULong tableCount = 0;
1623 FT_Error error;
1624
halcanary96fcdcc2015-08-27 07:41:13 -07001625 // When 'tag' is nullptr, returns number of tables in 'length'.
1626 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001627 if (error) {
1628 return 0;
1629 }
1630
1631 if (tags) {
1632 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1633 FT_ULong tableTag;
1634 FT_ULong tablelength;
1635 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1636 if (error) {
1637 return 0;
1638 }
1639 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1640 }
1641 }
1642 return tableCount;
1643}
1644
1645size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1646 size_t length, void* data) const
1647{
1648 AutoFTAccess fta(this);
1649 FT_Face face = fta.face();
1650
1651 FT_ULong tableLength = 0;
1652 FT_Error error;
1653
1654 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001655 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001656 if (error) {
1657 return 0;
1658 }
1659
1660 if (offset > tableLength) {
1661 return 0;
1662 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001663 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001664 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001665 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1666 if (error) {
1667 return 0;
1668 }
1669 }
1670
1671 return size;
1672}
1673
reed@google.comb4162b12013-07-02 16:32:29 +00001674///////////////////////////////////////////////////////////////////////////////
1675///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001676
halcanary96fcdcc2015-08-27 07:41:13 -07001677SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001678 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1679 return;
bungeman14df8332014-10-28 15:07:23 -07001680 }
bungeman9dc24682014-12-01 14:01:32 -08001681 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001682}
1683SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001684 if (fLibrary) {
1685 FT_Done_Library(fLibrary);
1686 }
bungeman14df8332014-10-28 15:07:23 -07001687}
1688
bungemanf93d7112016-09-16 06:24:20 -07001689FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001690 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001691{
halcanary96fcdcc2015-08-27 07:41:13 -07001692 if (fLibrary == nullptr) {
1693 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001694 }
1695
bungeman14df8332014-10-28 15:07:23 -07001696 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001697 memset(&args, 0, sizeof(args));
1698
1699 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001700
bsalomon49f085d2014-09-05 13:34:00 -07001701 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001702 args.flags = FT_OPEN_MEMORY;
1703 args.memory_base = (const FT_Byte*)memoryBase;
1704 args.memory_size = stream->getLength();
1705 } else {
bungeman14df8332014-10-28 15:07:23 -07001706 memset(ftStream, 0, sizeof(*ftStream));
1707 ftStream->size = stream->getLength();
1708 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001709 ftStream->read = sk_ft_stream_io;
1710 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001711
1712 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001713 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001714 }
1715
1716 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001717 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001718 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001719 }
1720 return face;
1721}
1722
bungemanf93d7112016-09-16 06:24:20 -07001723bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001724 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1725
1726 FT_StreamRec streamRec;
1727 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001728 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001729 return false;
1730 }
1731
1732 *numFaces = face->num_faces;
1733
1734 FT_Done_Face(face);
1735 return true;
1736}
1737
1738#include "SkTSearch.h"
1739bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001740 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001741 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001742{
1743 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1744
1745 FT_StreamRec streamRec;
1746 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001747 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001748 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001749 }
1750
bungemana4c4a2d2014-10-20 13:33:19 -07001751 int weight = SkFontStyle::kNormal_Weight;
1752 int width = SkFontStyle::kNormal_Width;
1753 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001754 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001755 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001756 }
1757 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001758 slant = SkFontStyle::kItalic_Slant;
1759 }
1760
1761 PS_FontInfoRec psFontInfo;
1762 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1763 if (os2 && os2->version != 0xffff) {
1764 weight = os2->usWeightClass;
1765 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001766
1767 // OS/2::fsSelection bit 9 indicates oblique.
1768 if (SkToBool(os2->fsSelection & (1u << 9))) {
1769 slant = SkFontStyle::kOblique_Slant;
1770 }
bungemana4c4a2d2014-10-20 13:33:19 -07001771 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1772 static const struct {
1773 char const * const name;
1774 int const weight;
1775 } commonWeights [] = {
1776 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001777 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001778 { "black", SkFontStyle::kBlack_Weight },
1779 { "bold", SkFontStyle::kBold_Weight },
1780 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1781 { "demi", SkFontStyle::kSemiBold_Weight },
1782 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001783 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001784 { "extrabold", SkFontStyle::kExtraBold_Weight },
1785 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001786 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001787 { "heavy", SkFontStyle::kBlack_Weight },
1788 { "light", SkFontStyle::kLight_Weight },
1789 { "medium", SkFontStyle::kMedium_Weight },
1790 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001791 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001792 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001793 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001794 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001795 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001796 { "thin", SkFontStyle::kThin_Weight },
1797 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001798 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001799 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001800 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001801 { "ultralight", SkFontStyle::kExtraLight_Weight },
1802 };
1803 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001804 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001805 if (index >= 0) {
1806 weight = commonWeights[index].weight;
1807 } else {
bungeman14df8332014-10-28 15:07:23 -07001808 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001809 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001810 }
1811
1812 if (name) {
1813 name->set(face->family_name);
1814 }
1815 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001816 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001817 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001818 if (isFixedPitch) {
1819 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001820 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001821
bungeman41868fe2015-05-20 09:21:04 -07001822 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001823 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001824 FT_Error err = FT_Get_MM_Var(face, &variations);
1825 if (err) {
1826 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1827 face->family_name));
1828 return false;
1829 }
1830 SkAutoFree autoFreeVariations(variations);
1831
1832 axes->reset(variations->num_axis);
1833 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1834 const FT_Var_Axis& ftAxis = variations->axis[i];
1835 (*axes)[i].fTag = ftAxis.tag;
1836 (*axes)[i].fMinimum = ftAxis.minimum;
1837 (*axes)[i].fDefault = ftAxis.def;
1838 (*axes)[i].fMaximum = ftAxis.maximum;
1839 }
1840 }
bungeman41868fe2015-05-20 09:21:04 -07001841
reed@android.com8a1c16f2008-12-17 15:59:43 +00001842 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001843 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001844}
bungemanf6c71072016-01-21 14:17:47 -08001845
1846/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1847 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001848 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001849 SkFixed* axisValues,
1850 const SkString& name)
1851{
1852 for (int i = 0; i < axisDefinitions.count(); ++i) {
1853 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001854 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1855 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001856 axisValues[i] = axisDefinition.fDefault;
Ben Wagnerfc497342017-02-24 11:15:26 -05001857 for (int j = 0; j < position.coordinateCount; ++j) {
1858 const auto& coordinate = position.coordinates[j];
1859 if (axisDefinition.fTag == coordinate.axis) {
1860 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1861 if (coordinate.value != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001862 SkDEBUGF(("Requested font axis value out of range: "
1863 "%s '%c%c%c%c' %f; pinned to %f.\n",
1864 name.c_str(),
1865 (axisDefinition.fTag >> 24) & 0xFF,
1866 (axisDefinition.fTag >> 16) & 0xFF,
1867 (axisDefinition.fTag >> 8) & 0xFF,
1868 (axisDefinition.fTag ) & 0xFF,
Ben Wagnerfc497342017-02-24 11:15:26 -05001869 SkScalarToDouble(coordinate.value),
benjaminwagner64a3c952016-02-25 12:20:40 -08001870 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001871 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001872 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001873 break;
1874 }
1875 }
1876 // TODO: warn on defaulted axis?
1877 }
1878
1879 SkDEBUGCODE(
1880 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05001881 for (int i = 0; i < position.coordinateCount; ++i) {
1882 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08001883 bool found = false;
1884 for (int j = 0; j < axisDefinitions.count(); ++j) {
1885 if (skTag == axisDefinitions[j].fTag) {
1886 found = true;
1887 break;
1888 }
1889 }
1890 if (!found) {
1891 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1892 name.c_str(),
1893 (skTag >> 24) & 0xFF,
1894 (skTag >> 16) & 0xFF,
1895 (skTag >> 8) & 0xFF,
1896 (skTag) & 0xFF));
1897 }
1898 }
1899 )
1900}