blob: 6f235edb8f7a70afde5ee5e81575be958b8b11aa [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"
reed@android.com8a1c16f2008-12-17 15:59:43 +000017#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000018#include "SkMaskGamma.h"
bungeman@google.comd3fbd342014-04-15 15:52:07 +000019#include "SkMatrix22.h"
mtklein1b249332015-07-07 12:21:21 -070020#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000021#include "SkOTUtils.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000022#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000023#include "SkStream.h"
24#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000025#include "SkTemplates.h"
bungeman9dc24682014-12-01 14:01:32 -080026#include "SkTypes.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027
bungeman@google.comfd668cf2012-08-24 17:46:11 +000028#if defined(SK_CAN_USE_DLOPEN)
29#include <dlfcn.h>
30#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000031#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080032#include FT_ADVANCES_H
33#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000034#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080035#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080036#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070037#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000038#include FT_OUTLINE_H
39#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080040#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000041#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000042#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000043#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000044
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000045// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
46// were introduced in FreeType 2.5.0.
47// The following may be removed once FreeType 2.5.0 is required to build.
48#ifndef FT_LOAD_COLOR
49# define FT_LOAD_COLOR ( 1L << 20 )
50# define FT_PIXEL_MODE_BGRA 7
51#endif
52
reed@android.com8a1c16f2008-12-17 15:59:43 +000053//#define ENABLE_GLYPH_SPEW // for tracing calls
54//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080055//#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
56//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000057//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000058
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000059using namespace skia_advanced_typeface_metrics_utils;
60
reed@google.comeffc5012011-06-27 16:44:46 +000061static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080062 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000063}
64
reed@android.com8a1c16f2008-12-17 15:59:43 +000065//////////////////////////////////////////////////////////////////////////
66
bungeman9dc24682014-12-01 14:01:32 -080067extern "C" {
68 static void* sk_ft_alloc(FT_Memory, long size) {
69 return sk_malloc_throw(size);
70 }
71 static void sk_ft_free(FT_Memory, void* block) {
72 sk_free(block);
73 }
74 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
75 return sk_realloc_throw(block, new_size);
76 }
77};
78FT_MemoryRec_ gFTMemory = { NULL, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
79
80class FreeTypeLibrary : SkNoncopyable {
81public:
82 FreeTypeLibrary() : fLibrary(NULL), fIsLCDSupported(false), fLCDExtra(0) {
83 if (FT_New_Library(&gFTMemory, &fLibrary)) {
84 return;
85 }
86 FT_Add_Default_Modules(fLibrary);
87
88 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
89 // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
90 // SetLcdFilter must be called before SetLcdFilterWeights.
91 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
92 fIsLCDSupported = true;
93 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
94
95#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
96 // Adds to 0x110 simulating ink spread, but provides better results than default.
97 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
98
99# if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
100 FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
101# elif SK_CAN_USE_DLOPEN == 1
102 //The FreeType library is already loaded, so symbols are available in process.
103 void* self = dlopen(NULL, RTLD_LAZY);
104 if (self) {
105 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
106 //The following cast is non-standard, but safe for POSIX.
107 *reinterpret_cast<void**>(&setLcdFilterWeights) =
108 dlsym(self, "FT_Library_SetLcdFilterWeights");
109 dlclose(self);
110
111 if (setLcdFilterWeights) {
112 setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
113 }
114 }
115# endif
116#endif
117 }
118 }
119 ~FreeTypeLibrary() {
120 if (fLibrary) {
121 FT_Done_Library(fLibrary);
122 }
123 }
124
125 FT_Library library() { return fLibrary; }
126 bool isLCDSupported() { return fIsLCDSupported; }
127 int lcdExtra() { return fLCDExtra; }
128
129private:
130 FT_Library fLibrary;
131 bool fIsLCDSupported;
132 int fLCDExtra;
133
134 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
135 // The following platforms provide FreeType of at least 2.4.0.
136 // Ubuntu >= 11.04 (previous deprecated April 2013)
137 // Debian >= 6.0 (good)
138 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
139 // Fedora >= 14 (good)
140 // Android >= Gingerbread (good)
141 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
142};
143
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144struct SkFaceRec;
145
digit@google.com1771cbf2012-01-26 21:26:40 +0000146SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800147static FreeTypeLibrary* gFTLibrary;
148static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000149
bungeman9dc24682014-12-01 14:01:32 -0800150// Private to RefFreeType and UnrefFreeType
151static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000152
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000153// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800154static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800155 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800156 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800157
bungeman9dc24682014-12-01 14:01:32 -0800158 if (0 == gFTCount) {
159 SkASSERT(NULL == gFTLibrary);
160 gFTLibrary = SkNEW(FreeTypeLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000161 }
bungeman9dc24682014-12-01 14:01:32 -0800162 ++gFTCount;
163 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000164}
165
bungeman9dc24682014-12-01 14:01:32 -0800166// Caller must lock gFTMutex before calling this function.
167static void unref_ft_library() {
168 gFTMutex.assertHeld();
169 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000170
bungeman9dc24682014-12-01 14:01:32 -0800171 --gFTCount;
172 if (0 == gFTCount) {
173 SkASSERT(NULL != gFTLibrary);
174 SkDELETE(gFTLibrary);
175 SkDEBUGCODE(gFTLibrary = NULL;)
176 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000177}
178
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000179class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000180public:
reed@google.com0da48612013-03-19 16:06:52 +0000181 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000183
reed@android.com62900b42009-02-11 15:07:19 +0000184 bool success() const {
bungeman13a007d2015-06-19 05:09:39 -0700185 return fFTSize != NULL && fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000186 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000187
188protected:
mtklein36352bf2015-03-25 18:17:31 -0700189 unsigned generateGlyphCount() override;
190 uint16_t generateCharToGlyph(SkUnichar uni) override;
191 void generateAdvance(SkGlyph* glyph) override;
192 void generateMetrics(SkGlyph* glyph) override;
193 void generateImage(const SkGlyph& glyph) override;
194 void generatePath(const SkGlyph& glyph, SkPath* path) override;
195 void generateFontMetrics(SkPaint::FontMetrics*) override;
196 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000197
198private:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000199 FT_Face fFace; // reference to shared face in gFaceRecHead
200 FT_Size fFTSize; // our own copy
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000201 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000202 SkFixed fScaleX, fScaleY;
203 FT_Matrix fMatrix22;
204 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000205 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000206 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000207
reed@google.comf073b332013-05-06 12:21:16 +0000208 // Need scalar versions for generateFontMetrics
209 SkVector fScale;
210 SkMatrix fMatrix22Scalar;
211
reed@android.com8a1c16f2008-12-17 15:59:43 +0000212 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000213 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
214 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000215 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000216 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000217 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000218 // Caller must lock gFTMutex before calling this function.
219 // update FreeType2 glyph slot with glyph emboldened
220 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000221};
222
223///////////////////////////////////////////////////////////////////////////
224///////////////////////////////////////////////////////////////////////////
225
reed@android.com8a1c16f2008-12-17 15:59:43 +0000226struct SkFaceRec {
bungeman52b64b42015-01-27 10:41:17 -0800227 SkFaceRec* fNext;
228 FT_Face fFace;
229 FT_StreamRec fFTStream;
230 SkAutoTDelete<SkStreamAsset> fSkStream;
231 uint32_t fRefCnt;
232 uint32_t fFontID;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000233
scroggoa1193e42015-01-21 12:09:53 -0800234 // assumes ownership of the stream, will delete when its done
bungeman52b64b42015-01-27 10:41:17 -0800235 SkFaceRec(SkStreamAsset* strm, uint32_t fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000236};
237
238extern "C" {
bungeman52b64b42015-01-27 10:41:17 -0800239 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
bungeman9dc24682014-12-01 14:01:32 -0800240 unsigned long offset,
241 unsigned char* buffer,
242 unsigned long count)
243 {
bungeman52b64b42015-01-27 10:41:17 -0800244 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000245
246 if (count) {
bungeman52b64b42015-01-27 10:41:17 -0800247 if (!stream->seek(offset)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000248 return 0;
bungeman9dc24682014-12-01 14:01:32 -0800249 }
bungeman52b64b42015-01-27 10:41:17 -0800250 count = stream->read(buffer, count);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000251 }
252 return count;
253 }
254
bungeman9dc24682014-12-01 14:01:32 -0800255 static void sk_ft_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000256}
257
bungeman52b64b42015-01-27 10:41:17 -0800258SkFaceRec::SkFaceRec(SkStreamAsset* stream, uint32_t fontID)
259 : fNext(NULL), fSkStream(stream), fRefCnt(1), fFontID(fontID)
260{
reed@android.com4516f472009-06-29 16:25:36 +0000261 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000262 fFTStream.size = fSkStream->getLength();
263 fFTStream.descriptor.pointer = fSkStream;
bungeman9dc24682014-12-01 14:01:32 -0800264 fFTStream.read = sk_ft_stream_io;
265 fFTStream.close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000266}
267
bungeman41868fe2015-05-20 09:21:04 -0700268static void ft_face_setup_axes(FT_Face face, const SkFontData& data) {
269 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
270 return;
271 }
272
273 SkDEBUGCODE(
274 FT_MM_Var* variations = NULL;
275 if (FT_Get_MM_Var(face, &variations)) {
276 SkDEBUGF(("INFO: font %s claims variations, but none found.\n", face->family_name));
277 return;
278 }
279 SkAutoFree autoFreeVariations(variations);
280
281 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
282 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
283 face->family_name, variations->num_axis, data.getAxisCount()));
284 return;
285 }
286 )
287
288 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
289 for (int i = 0; i < data.getAxisCount(); ++i) {
290 coords[i] = data.getAxis()[i];
291 }
292 if (FT_Set_Var_Design_Coordinates(face, data.getAxisCount(), coords.get())) {
293 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
294 face->family_name));
295 return;
296 }
297}
bungeman41868fe2015-05-20 09:21:04 -0700298
reed@android.com62900b42009-02-11 15:07:19 +0000299// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000300// Caller must lock gFTMutex before calling this function.
bungeman13a007d2015-06-19 05:09:39 -0700301static FT_Face ref_ft_face(const SkTypeface* typeface) {
bungeman5ec443c2014-11-21 13:18:34 -0800302 gFTMutex.assertHeld();
303
reed@google.com2cdc6712013-03-21 18:22:00 +0000304 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000305 SkFaceRec* rec = gFaceRecHead;
306 while (rec) {
307 if (rec->fFontID == fontID) {
308 SkASSERT(rec->fFace);
309 rec->fRefCnt += 1;
bungeman13a007d2015-06-19 05:09:39 -0700310 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000311 }
312 rec = rec->fNext;
313 }
314
bungeman41868fe2015-05-20 09:21:04 -0700315 SkAutoTDelete<SkFontData> data(typeface->createFontData());
316 if (NULL == data || !data->hasStream()) {
reed@google.com2cdc6712013-03-21 18:22:00 +0000317 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000318 }
319
bungeman52b64b42015-01-27 10:41:17 -0800320 // this passes ownership of stream to the rec
bungeman41868fe2015-05-20 09:21:04 -0700321 rec = SkNEW_ARGS(SkFaceRec, (data->detachStream(), fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000322
bungeman9dc24682014-12-01 14:01:32 -0800323 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000324 memset(&args, 0, sizeof(args));
bungeman41868fe2015-05-20 09:21:04 -0700325 const void* memoryBase = rec->fSkStream->getMemoryBase();
bsalomon49f085d2014-09-05 13:34:00 -0700326 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000327 args.flags = FT_OPEN_MEMORY;
328 args.memory_base = (const FT_Byte*)memoryBase;
bungeman41868fe2015-05-20 09:21:04 -0700329 args.memory_size = rec->fSkStream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000330 } else {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000331 args.flags = FT_OPEN_STREAM;
332 args.stream = &rec->fFTStream;
333 }
334
bungeman41868fe2015-05-20 09:21:04 -0700335 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rec->fFace);
336 if (err) {
bungeman5ec443c2014-11-21 13:18:34 -0800337 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338 SkDELETE(rec);
reed@google.com2cdc6712013-03-21 18:22:00 +0000339 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000340 }
bungeman9dc24682014-12-01 14:01:32 -0800341 SkASSERT(rec->fFace);
bungeman41868fe2015-05-20 09:21:04 -0700342
bungeman41868fe2015-05-20 09:21:04 -0700343 ft_face_setup_axes(rec->fFace, *data);
bungeman41868fe2015-05-20 09:21:04 -0700344
bungeman726cf902015-06-05 13:38:12 -0700345 // FreeType will set the charmap to the "most unicode" cmap if it exists.
346 // If there are no unicode cmaps, the charmap is set to NULL.
347 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
348 // because they are effectively private use area only (even if they aren't).
349 // This is the last on the fallback list at
350 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
351 if (!rec->fFace->charmap) {
352 FT_Select_Charmap(rec->fFace, FT_ENCODING_MS_SYMBOL);
353 }
354
bungeman9dc24682014-12-01 14:01:32 -0800355 rec->fNext = gFaceRecHead;
356 gFaceRecHead = rec;
bungeman13a007d2015-06-19 05:09:39 -0700357 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000358}
359
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000360// Caller must lock gFTMutex before calling this function.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000361static void unref_ft_face(FT_Face face) {
bungeman5ec443c2014-11-21 13:18:34 -0800362 gFTMutex.assertHeld();
363
reed@android.com8a1c16f2008-12-17 15:59:43 +0000364 SkFaceRec* rec = gFaceRecHead;
365 SkFaceRec* prev = NULL;
366 while (rec) {
367 SkFaceRec* next = rec->fNext;
368 if (rec->fFace == face) {
369 if (--rec->fRefCnt == 0) {
370 if (prev) {
371 prev->fNext = next;
372 } else {
373 gFaceRecHead = next;
374 }
375 FT_Done_Face(face);
376 SkDELETE(rec);
377 }
378 return;
379 }
380 prev = rec;
381 rec = next;
382 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000383 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000384}
385
reed@google.comb4162b12013-07-02 16:32:29 +0000386class AutoFTAccess {
387public:
bungeman13a007d2015-06-19 05:09:39 -0700388 AutoFTAccess(const SkTypeface* tf) : fFace(NULL) {
reed@google.comb4162b12013-07-02 16:32:29 +0000389 gFTMutex.acquire();
bungeman9dc24682014-12-01 14:01:32 -0800390 if (!ref_ft_library()) {
391 sk_throw();
reed@google.comb4162b12013-07-02 16:32:29 +0000392 }
bungeman13a007d2015-06-19 05:09:39 -0700393 fFace = ref_ft_face(tf);
reed@google.comb4162b12013-07-02 16:32:29 +0000394 }
395
396 ~AutoFTAccess() {
397 if (fFace) {
398 unref_ft_face(fFace);
399 }
bungeman9dc24682014-12-01 14:01:32 -0800400 unref_ft_library();
reed@google.comb4162b12013-07-02 16:32:29 +0000401 gFTMutex.release();
402 }
403
reed@google.comb4162b12013-07-02 16:32:29 +0000404 FT_Face face() { return fFace; }
405
406private:
reed@google.comb4162b12013-07-02 16:32:29 +0000407 FT_Face fFace;
408};
409
reed@android.com8a1c16f2008-12-17 15:59:43 +0000410///////////////////////////////////////////////////////////////////////////
411
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000412static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000413 FT_UShort fsType = FT_Get_FSType_Flags(face);
414 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
415 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000416}
417
vandebo0f9bad02014-06-19 11:05:39 -0700418static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700419 FT_UShort fsType = FT_Get_FSType_Flags(face);
420 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700421}
422
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000423static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
424 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
425 if (!glyph_id)
426 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000427 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
428 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000429 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
430 return true;
431}
432
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000433static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000434 FT_Fixed advance = 0;
bungeman5ec443c2014-11-21 13:18:34 -0800435 if (FT_Get_Advances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000436 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000437 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000438 SkASSERT(data);
439 *data = advance;
440 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000441}
442
bungeman5ec443c2014-11-21 13:18:34 -0800443static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
bungeman726cf902015-06-05 13:38:12 -0700444 glyphToUnicode->setCount(face->num_glyphs);
445 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * face->num_glyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000446
bungeman726cf902015-06-05 13:38:12 -0700447 FT_UInt glyphIndex;
448 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
449 while (glyphIndex) {
450 (*glyphToUnicode)[glyphIndex] = charCode;
451 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000452 }
453}
454
reed@google.com2689f612013-03-20 20:01:47 +0000455SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700456 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000457 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000458 uint32_t glyphIDsCount) const {
djsollen@google.comda957722011-11-16 17:00:46 +0000459#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000460 return NULL;
461#else
reed@google.comb4162b12013-07-02 16:32:29 +0000462 AutoFTAccess fta(this);
463 FT_Face face = fta.face();
464 if (!face) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000465 return NULL;
reed@google.comb4162b12013-07-02 16:32:29 +0000466 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000467
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000468 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
469 info->fFontName.set(FT_Get_Postscript_Name(face));
vandebo0f9bad02014-06-19 11:05:39 -0700470 info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag;
471 if (FT_HAS_MULTIPLE_MASTERS(face)) {
472 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
473 info->fFlags, SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag);
474 }
475 if (!canEmbed(face)) {
476 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
477 info->fFlags,
478 SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag);
479 }
480 if (!canSubset(face)) {
481 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
482 info->fFlags,
483 SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag);
484 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000485 info->fLastGlyphID = face->num_glyphs - 1;
486 info->fEmSize = 1000;
487
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000488 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000489 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000490 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000491 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000492 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000493 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000494 cid = true;
495 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000496 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000497 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000498 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000499 cid = true;
500 TT_Header* ttHeader;
501 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
502 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000503 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000504 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000505 } else {
506 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000507 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000508
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000509 info->fStyle = 0;
510 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000511 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000512 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000513 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000514
515 PS_FontInfoRec ps_info;
516 TT_Postscript* tt_info;
517 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
518 info->fItalicAngle = ps_info.italic_angle;
519 } else if ((tt_info =
520 (TT_Postscript*)FT_Get_Sfnt_Table(face,
521 ft_sfnt_post)) != NULL) {
522 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
523 } else {
524 info->fItalicAngle = 0;
525 }
526
527 info->fAscent = face->ascender;
528 info->fDescent = face->descender;
529
530 // Figure out a good guess for StemV - Min width of i, I, !, 1.
531 // This probably isn't very good with an italic font.
532 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000533 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000534 char stem_chars[] = {'i', 'I', '!', '1'};
535 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
536 FT_BBox bbox;
537 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
538 int16_t width = bbox.xMax - bbox.xMin;
539 if (width > 0 && width < min_width) {
540 min_width = width;
541 info->fStemV = min_width;
542 }
543 }
544 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000545
546 TT_PCLT* pclt_info;
547 TT_OS2* os2_table;
548 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
549 info->fCapHeight = pclt_info->CapHeight;
550 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
551 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000552 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000553 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000554 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000555 } else if (((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) &&
556 // sCapHeight is available only when version 2 or later.
557 os2_table->version != 0xFFFF &&
558 os2_table->version >= 2) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000559 info->fCapHeight = os2_table->sCapHeight;
560 } else {
561 // Figure out a good guess for CapHeight: average the height of M and X.
562 FT_BBox m_bbox, x_bbox;
563 bool got_m, got_x;
564 got_m = GetLetterCBox(face, 'M', &m_bbox);
565 got_x = GetLetterCBox(face, 'X', &x_bbox);
566 if (got_m && got_x) {
567 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
568 x_bbox.yMin) / 2;
569 } else if (got_m && !got_x) {
570 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
571 } else if (!got_m && got_x) {
572 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000573 } else {
574 // Last resort, use the ascent.
575 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000576 }
577 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000578
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000579 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
580 face->bbox.xMax, face->bbox.yMin);
581
vandebo0f9bad02014-06-19 11:05:39 -0700582 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700583 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000584 }
585
reed39a9a502015-05-12 09:50:04 -0700586 if (perGlyphInfo & kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000587 if (FT_IS_FIXED_WIDTH(face)) {
588 appendRange(&info->fGlyphWidths, 0);
589 int16_t advance = face->max_advance_width;
590 info->fGlyphWidths->fAdvance.append(1, &advance);
591 finishRange(info->fGlyphWidths.get(), 0,
592 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000593 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000594 appendRange(&info->fGlyphWidths, 0);
595 // So as to not blow out the stack, get advances in batches.
596 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
597 FT_Fixed advances[128];
598 int advanceCount = 128;
bungeman5ec443c2014-11-21 13:18:34 -0800599 if (gID + advanceCount > face->num_glyphs) {
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000600 advanceCount = face->num_glyphs - gID;
bungeman5ec443c2014-11-21 13:18:34 -0800601 }
602 FT_Get_Advances(face, gID, advanceCount, FT_LOAD_NO_SCALE, advances);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000603 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000604 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000605 info->fGlyphWidths->fAdvance.append(1, &advance);
606 }
607 }
608 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
609 SkAdvancedTypefaceMetrics::WidthRange::kRange);
610 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000611 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000612 getAdvanceData(face,
613 face->num_glyphs,
614 glyphIDs,
615 glyphIDsCount,
616 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000617 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000618 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000619
reed39a9a502015-05-12 09:50:04 -0700620 if (perGlyphInfo & kVAdvance_PerGlyphInfo &&
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000621 FT_HAS_VERTICAL(face)) {
622 SkASSERT(false); // Not implemented yet.
623 }
624
reed39a9a502015-05-12 09:50:04 -0700625 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000626 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
627 // Postscript fonts may contain more than 255 glyphs, so we end up
628 // using multiple font descriptions with a glyph ordering. Record
629 // the name of each glyph.
630 info->fGlyphNames.reset(
631 new SkAutoTArray<SkString>(face->num_glyphs));
632 for (int gID = 0; gID < face->num_glyphs; gID++) {
633 char glyphName[128]; // PS limit for names is 127 bytes.
634 FT_Get_Glyph_Name(face, gID, glyphName, 128);
635 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000636 }
637 }
638
reed39a9a502015-05-12 09:50:04 -0700639 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000640 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
641 face->num_charmaps) {
642 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
643 }
644
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000645 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000646#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000647}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000648
reed@google.com618ef5e2011-01-26 22:10:41 +0000649///////////////////////////////////////////////////////////////////////////
650
reed@google.com8ed436c2011-07-21 14:12:36 +0000651static bool bothZero(SkScalar a, SkScalar b) {
652 return 0 == a && 0 == b;
653}
654
655// returns false if there is any non-90-rotation or skew
656static bool isAxisAligned(const SkScalerContext::Rec& rec) {
657 return 0 == rec.fPreSkewX &&
658 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
659 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
660}
661
reed@google.com0da48612013-03-19 16:06:52 +0000662SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
663 const SkDescriptor* desc) const {
664 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
665 (const_cast<SkTypeface_FreeType*>(this),
666 desc));
667 if (!c->success()) {
668 SkDELETE(c);
669 c = NULL;
670 }
671 return c;
672}
673
674void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000675 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
676 //Cap the requested size as larger sizes give bogus values.
677 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000678 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000679 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000680 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000681
bungemanec7e12f2015-01-21 11:55:16 -0800682 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800683 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
684 SkAutoMutexAcquire ama(gFTMutex);
685 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800686 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800687 // If the runtime Freetype library doesn't support LCD, disable it here.
688 rec->fMaskFormat = SkMask::kA8_Format;
689 }
690 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000691 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000692
reed@google.com618ef5e2011-01-26 22:10:41 +0000693 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000694 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000695 // collapse full->normal hinting if we're not doing LCD
696 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000697 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000698 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000699 if (SkPaint::kNo_Hinting != h) {
700 h = SkPaint::kSlight_Hinting;
701 }
702 }
703
reed@google.com8ed436c2011-07-21 14:12:36 +0000704 // rotated text looks bad with hinting, so we disable it as needed
705 if (!isAxisAligned(*rec)) {
706 h = SkPaint::kNo_Hinting;
707 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000708 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000709
bungeman@google.com97efada2012-07-30 20:40:50 +0000710#ifndef SK_GAMMA_APPLY_TO_A8
711 if (!isLCD(*rec)) {
712 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000713 }
reed@google.com1ac83502012-02-28 17:06:02 +0000714#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000715}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000716
reed@google.com38c37dd2013-03-21 15:36:26 +0000717int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000718 AutoFTAccess fta(this);
719 FT_Face face = fta.face();
720 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000721}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000722
reed@google.com35fe7372013-10-30 15:07:03 +0000723bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
724 int count, int32_t adjustments[]) const {
725 AutoFTAccess fta(this);
726 FT_Face face = fta.face();
727 if (!face || !FT_HAS_KERNING(face)) {
728 return false;
729 }
730
731 for (int i = 0; i < count - 1; ++i) {
732 FT_Vector delta;
733 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
734 FT_KERNING_UNSCALED, &delta);
735 if (err) {
736 return false;
737 }
738 adjustments[i] = delta.x;
739 }
740 return true;
741}
742
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000743static FT_Int chooseBitmapStrike(FT_Face face, SkFixed scaleY) {
744 // early out if face is bad
745 if (face == NULL) {
746 SkDEBUGF(("chooseBitmapStrike aborted due to NULL face\n"));
747 return -1;
748 }
749 // determine target ppem
750 FT_Pos targetPPEM = SkFixedToFDot6(scaleY);
751 // find a bitmap strike equal to or just larger than the requested size
752 FT_Int chosenStrikeIndex = -1;
753 FT_Pos chosenPPEM = 0;
754 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
755 FT_Pos thisPPEM = face->available_sizes[strikeIndex].y_ppem;
756 if (thisPPEM == targetPPEM) {
757 // exact match - our search stops here
758 chosenPPEM = thisPPEM;
759 chosenStrikeIndex = strikeIndex;
760 break;
761 } else if (chosenPPEM < targetPPEM) {
762 // attempt to increase chosenPPEM
763 if (thisPPEM > chosenPPEM) {
764 chosenPPEM = thisPPEM;
765 chosenStrikeIndex = strikeIndex;
766 }
767 } else {
768 // attempt to decrease chosenPPEM, but not below targetPPEM
769 if (thisPPEM < chosenPPEM && thisPPEM > targetPPEM) {
770 chosenPPEM = thisPPEM;
771 chosenStrikeIndex = strikeIndex;
772 }
773 }
774 }
775 if (chosenStrikeIndex != -1) {
776 // use the chosen strike
777 FT_Error err = FT_Select_Size(face, chosenStrikeIndex);
778 if (err != 0) {
779 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x\n", face->family_name,
780 chosenStrikeIndex, err));
781 chosenStrikeIndex = -1;
782 }
783 }
784 return chosenStrikeIndex;
785}
786
bungeman13a007d2015-06-19 05:09:39 -0700787SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface, const SkDescriptor* desc)
788 : SkScalerContext_FreeType_Base(typeface, desc)
789{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790 SkAutoMutexAcquire ac(gFTMutex);
791
bungeman9dc24682014-12-01 14:01:32 -0800792 if (!ref_ft_library()) {
793 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000794 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000795
796 // load the font file
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000797 fStrikeIndex = -1;
reed@android.com62900b42009-02-11 15:07:19 +0000798 fFTSize = NULL;
bungeman13a007d2015-06-19 05:09:39 -0700799 fFace = ref_ft_face(typeface);
800 if (NULL == fFace) {
reed@android.com62900b42009-02-11 15:07:19 +0000801 return;
802 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000803
bungeman5f14c5e2014-12-05 12:26:44 -0800804 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
805 fMatrix22Scalar.setSkewX(-fMatrix22Scalar.getSkewX());
806 fMatrix22Scalar.setSkewY(-fMatrix22Scalar.getSkewY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000807
bungeman5f14c5e2014-12-05 12:26:44 -0800808 fScaleX = SkScalarToFixed(fScale.fX);
809 fScaleY = SkScalarToFixed(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000810 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
811 fMatrix22.xy = SkScalarToFixed(fMatrix22Scalar.getSkewX());
812 fMatrix22.yx = SkScalarToFixed(fMatrix22Scalar.getSkewY());
813 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000814
reed@google.coma1bfa212012-03-08 21:57:12 +0000815 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
816
reed@android.com8a1c16f2008-12-17 15:59:43 +0000817 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000818 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000819 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000820 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000821
agl@chromium.org70a303f2010-05-10 14:15:50 +0000822 if (SkMask::kBW_Format == fRec.fMaskFormat) {
823 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
824 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000825 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000826 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000827 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000828 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000829 } else {
830 switch (fRec.getHinting()) {
831 case SkPaint::kNo_Hinting:
832 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000833 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000834 break;
835 case SkPaint::kSlight_Hinting:
836 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
837 break;
838 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000839 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000840 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700841#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
842 } else {
843 loadFlags = FT_LOAD_NO_AUTOHINT;
844#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000845 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000846 break;
847 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000848 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000849 loadFlags = FT_LOAD_FORCE_AUTOHINT;
850 break;
851 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000852 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000853 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000854 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000855 loadFlags = FT_LOAD_TARGET_LCD_V;
856 } else {
857 loadFlags = FT_LOAD_TARGET_LCD;
858 }
reed@google.comea2333d2011-03-14 16:44:56 +0000859 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000860 break;
861 default:
862 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
863 break;
864 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000865 }
866
reed@google.comeffc5012011-06-27 16:44:46 +0000867 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000868 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000869 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000870
reed@google.com96a9f7912011-05-06 11:49:30 +0000871 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
872 // advances, as fontconfig and cairo do.
873 // See http://code.google.com/p/skia/issues/detail?id=222.
874 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
875
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000876 // Use vertical layout if requested.
877 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
878 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
879 }
880
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000881 loadFlags |= FT_LOAD_COLOR;
882
reed@android.come4d0bc02009-07-24 19:53:20 +0000883 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000884 }
885
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000886 FT_Error err = FT_New_Size(fFace, &fFTSize);
887 if (err != 0) {
888 SkDEBUGF(("FT_New_Size returned %x for face %s\n", err, fFace->family_name));
889 fFace = NULL;
890 return;
891 }
892 err = FT_Activate_Size(fFTSize);
893 if (err != 0) {
894 SkDEBUGF(("FT_Activate_Size(%08x, 0x%x, 0x%x) returned 0x%x\n", fFace, fScaleX, fScaleY,
895 err));
896 fFTSize = NULL;
897 return;
898 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000899
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000900 if (FT_IS_SCALABLE(fFace)) {
901 err = FT_Set_Char_Size(fFace, SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000902 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000903 SkDEBUGF(("FT_Set_CharSize(%08x, 0x%x, 0x%x) returned 0x%x\n",
904 fFace, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000905 fFace = NULL;
906 return;
907 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000908 FT_Set_Transform(fFace, &fMatrix22, NULL);
909 } else if (FT_HAS_FIXED_SIZES(fFace)) {
910 fStrikeIndex = chooseBitmapStrike(fFace, fScaleY);
911 if (fStrikeIndex == -1) {
912 SkDEBUGF(("no glyphs for font \"%s\" size %f?\n",
913 fFace->family_name, SkFixedToScalar(fScaleY)));
914 } else {
915 // FreeType does no provide linear metrics for bitmap fonts.
916 linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000917
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000918 // FreeType documentation says:
919 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
920 // Bitmap-only fonts ignore this flag.
921 //
922 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
923 // Force this flag off for bitmap only fonts.
924 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000926 } else {
927 SkDEBUGF(("unknown kind of font \"%s\" size %f?\n",
928 fFace->family_name, SkFixedToScalar(fScaleY)));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000929 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000930
931 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000932}
933
934SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000935 SkAutoMutexAcquire ac(gFTMutex);
936
reed@android.com8a1c16f2008-12-17 15:59:43 +0000937 if (fFTSize != NULL) {
938 FT_Done_Size(fFTSize);
939 }
940
reed@android.com8a1c16f2008-12-17 15:59:43 +0000941 if (fFace != NULL) {
942 unref_ft_face(fFace);
943 }
bungeman9dc24682014-12-01 14:01:32 -0800944
945 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000946}
947
948/* We call this before each use of the fFace, since we may be sharing
949 this face with other context (at different sizes).
950*/
951FT_Error SkScalerContext_FreeType::setupSize() {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000952 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000953 if (err != 0) {
bungeman13a007d2015-06-19 05:09:39 -0700954 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%s %s, 0x%x, 0x%x) returned 0x%x\n",
955 fFace->family_name, fFace->style_name, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000956 fFTSize = NULL;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000957 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000958 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000959
960 // seems we need to reset this every time (not sure why, but without it
961 // I get random italics from some other fFTSize)
962 FT_Set_Transform(fFace, &fMatrix22, NULL);
963 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000964}
965
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000966unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000967 return fFace->num_glyphs;
968}
969
970uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
971 return SkToU16(FT_Get_Char_Index( fFace, uni ));
972}
973
reed@android.com9d3a9852010-01-08 14:07:42 +0000974SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
975 // iterate through each cmap entry, looking for matching glyph indices
976 FT_UInt glyphIndex;
977 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
978
979 while (glyphIndex != 0) {
980 if (glyphIndex == glyph) {
981 return charCode;
982 }
983 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
984 }
985
986 return 0;
987}
988
reed@android.com8a1c16f2008-12-17 15:59:43 +0000989void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000990 /* unhinted and light hinted text have linearly scaled advances
991 * which are very cheap to compute with some font formats...
992 */
reed@google.combdc99882011-11-21 14:36:57 +0000993 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000994 SkAutoMutexAcquire ac(gFTMutex);
995
996 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000997 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000998 return;
999 }
1000
1001 FT_Error error;
1002 FT_Fixed advance;
1003
djsollen1b277042014-08-06 06:58:06 -07001004 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001005 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1006 &advance );
1007 if (0 == error) {
1008 glyph->fRsbDelta = 0;
1009 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +00001010 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1011 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001012 return;
1013 }
1014 }
bungeman5ec443c2014-11-21 13:18:34 -08001015
reed@android.com8a1c16f2008-12-17 15:59:43 +00001016 /* otherwise, we need to load/hint the glyph, which is slower */
1017 this->generateMetrics(glyph);
1018 return;
1019}
1020
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001021void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1022 FT_BBox* bbox,
1023 bool snapToPixelBoundary) {
1024
1025 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1026
1027 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001028 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1029 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001030 // negate dy since freetype-y-goes-up and skia-y-goes-down
1031 bbox->xMin += dx;
1032 bbox->yMin -= dy;
1033 bbox->xMax += dx;
1034 bbox->yMax -= dy;
1035 }
1036
1037 // outset the box to integral boundaries
1038 if (snapToPixelBoundary) {
1039 bbox->xMin &= ~63;
1040 bbox->yMin &= ~63;
1041 bbox->xMax = (bbox->xMax + 63) & ~63;
1042 bbox->yMax = (bbox->yMax + 63) & ~63;
1043 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001044
1045 // Must come after snapToPixelBoundary so that the width and height are
1046 // consistent. Otherwise asserts will fire later on when generating the
1047 // glyph image.
1048 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1049 FT_Vector vector;
1050 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1051 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1052 FT_Vector_Transform(&vector, &fMatrix22);
1053 bbox->xMin += vector.x;
1054 bbox->xMax += vector.x;
1055 bbox->yMin += vector.y;
1056 bbox->yMax += vector.y;
1057 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001058}
1059
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001060bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1061 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001062 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001063 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001064 }
1065 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001066 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001067 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001068 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001069 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1070 return true;
1071}
1072
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001073void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1074 if (isLCD(fRec)) {
1075 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001076 glyph->fHeight += gFTLibrary->lcdExtra();
1077 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001078 } else {
bungeman9dc24682014-12-01 14:01:32 -08001079 glyph->fWidth += gFTLibrary->lcdExtra();
1080 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001081 }
1082 }
1083}
1084
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001085inline void scaleGlyphMetrics(SkGlyph& glyph, SkScalar scale) {
1086 glyph.fWidth *= scale;
1087 glyph.fHeight *= scale;
1088 glyph.fTop *= scale;
1089 glyph.fLeft *= scale;
1090
1091 SkFixed fixedScale = SkScalarToFixed(scale);
1092 glyph.fAdvanceX = SkFixedMul(glyph.fAdvanceX, fixedScale);
1093 glyph.fAdvanceY = SkFixedMul(glyph.fAdvanceY, fixedScale);
1094}
1095
reed@android.com8a1c16f2008-12-17 15:59:43 +00001096void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1097 SkAutoMutexAcquire ac(gFTMutex);
1098
1099 glyph->fRsbDelta = 0;
1100 glyph->fLsbDelta = 0;
1101
1102 FT_Error err;
1103
1104 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001105 glyph->zeroMetrics();
1106 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001107 }
1108
djsollen1b277042014-08-06 06:58:06 -07001109 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001110 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001111 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001112 return;
1113 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001114 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001115
1116 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001117 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001118 if (0 == fFace->glyph->outline.n_contours) {
1119 glyph->fWidth = 0;
1120 glyph->fHeight = 0;
1121 glyph->fTop = 0;
1122 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001123 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001124 FT_BBox bbox;
1125 getBBoxForCurrentGlyph(glyph, &bbox, true);
1126
1127 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1128 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1129 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1130 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1131
1132 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001133 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001134 break;
1135
1136 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001137 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1138 FT_Vector vector;
1139 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1140 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1141 FT_Vector_Transform(&vector, &fMatrix22);
1142 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1143 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1144 }
1145
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001146 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1147 glyph->fMaskFormat = SkMask::kARGB32_Format;
1148 }
1149
reed@android.com8a1c16f2008-12-17 15:59:43 +00001150 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1151 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1152 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1153 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1154 break;
1155
1156 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001157 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001158 glyph->zeroMetrics();
1159 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001160 }
1161
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001162 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1163 if (fDoLinearMetrics) {
1164 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1165 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1166 } else {
1167 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1168 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1169 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001170 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001171 if (fDoLinearMetrics) {
1172 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1173 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1174 } else {
1175 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1176 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001177
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001178 if (fRec.fFlags & kDevKernText_Flag) {
1179 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1180 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001181 }
1182 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001183 }
1184
bungemana85511a2014-09-22 12:24:41 -07001185 // If the font isn't scalable, scale the metrics from the non-scalable strike.
1186 // This means do not try to scale embedded bitmaps; only scale bitmaps in bitmap only fonts.
1187 if (!FT_IS_SCALABLE(fFace) && fScaleY && fFace->size->metrics.y_ppem) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001188 // NOTE: both dimensions are scaled by y_ppem. this is WAI.
reed80ea19c2015-05-12 10:37:34 -07001189 scaleGlyphMetrics(*glyph, SkFixedToScalar(fScaleY) / fFace->size->metrics.y_ppem);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001190 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001191
reed@android.com8a1c16f2008-12-17 15:59:43 +00001192#ifdef ENABLE_GLYPH_SPEW
1193 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
djsollen1b277042014-08-06 06:58:06 -07001194 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195#endif
1196}
1197
bungeman5ec443c2014-11-21 13:18:34 -08001198static void clear_glyph_image(const SkGlyph& glyph) {
1199 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1200}
reed@google.comea2333d2011-03-14 16:44:56 +00001201
bungeman@google.coma76de722012-10-26 19:35:54 +00001202void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001203 SkAutoMutexAcquire ac(gFTMutex);
1204
reed@android.com8a1c16f2008-12-17 15:59:43 +00001205 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001206 clear_glyph_image(glyph);
1207 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001208 }
1209
bungeman5ec443c2014-11-21 13:18:34 -08001210 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001211 if (err != 0) {
1212 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 -08001213 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1214 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001215 return;
1216 }
1217
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001218 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.coma76de722012-10-26 19:35:54 +00001219 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001220}
1221
reed@android.com8a1c16f2008-12-17 15:59:43 +00001222
bungeman5ec443c2014-11-21 13:18:34 -08001223void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001224 SkAutoMutexAcquire ac(gFTMutex);
1225
caryclarka10742c2014-09-18 11:00:40 -07001226 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001227
1228 if (this->setupSize()) {
1229 path->reset();
1230 return;
1231 }
1232
1233 uint32_t flags = fLoadGlyphFlags;
1234 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1235 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1236
djsollen1b277042014-08-06 06:58:06 -07001237 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001238
1239 if (err != 0) {
1240 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001241 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001242 path->reset();
1243 return;
1244 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001245 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001246
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001247 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001248
1249 // The path's origin from FreeType is always the horizontal layout origin.
1250 // Offset the path so that it is relative to the vertical origin if needed.
1251 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1252 FT_Vector vector;
1253 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1254 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1255 FT_Vector_Transform(&vector, &fMatrix22);
1256 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1257 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001258}
1259
bungeman41078062014-07-07 08:16:37 -07001260void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
1261 if (NULL == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001262 return;
1263 }
1264
bungeman41078062014-07-07 08:16:37 -07001265 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001266
1267 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001268 ERROR:
bungeman41078062014-07-07 08:16:37 -07001269 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001270 return;
1271 }
1272
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001273 FT_Face face = fFace;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001274 SkScalar scaleX = fScale.x();
reed@google.comf073b332013-05-06 12:21:16 +00001275 SkScalar scaleY = fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001276 SkScalar mxy = fMatrix22Scalar.getSkewX() * scaleY;
1277 SkScalar myy = fMatrix22Scalar.getScaleY() * scaleY;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001278
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001279 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1280 SkScalar upem = SkIntToScalar(face->units_per_EM);
1281 if (!upem) {
1282 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1283 if (ttHeader) {
1284 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001285 }
1286 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001287
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001288 // use the os/2 table as a source of reasonable defaults.
1289 SkScalar x_height = 0.0f;
1290 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001291 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001292 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1293 if (os2) {
1294 x_height = scaleX * SkIntToScalar(os2->sxHeight) / upem;
1295 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001296 if (os2->version != 0xFFFF && os2->version >= 2) {
1297 cap_height = scaleX * SkIntToScalar(os2->sCapHeight) / upem;
1298 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001299 }
1300
1301 // pull from format-specific metrics as needed
1302 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001303 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001304 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001305 // FreeType will always use HHEA metrics if they're not zero.
1306 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1307 // It also ignores the VDMX tables, which are also of interest here
1308 // (and override everything else when they apply).
1309 static const int kUseTypoMetricsMask = (1 << 7);
1310 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1311 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1312 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1313 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1314 } else {
1315 ascent = -SkIntToScalar(face->ascender) / upem;
1316 descent = -SkIntToScalar(face->descender) / upem;
1317 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1318 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001319 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1320 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1321 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1322 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001323 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001324 underlinePosition = -SkIntToScalar(face->underline_position +
1325 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001326
bungeman41078062014-07-07 08:16:37 -07001327 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1328 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1329
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001330 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001331 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001332 FT_BBox bbox;
1333 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001334 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1335 }
1336 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001337 if (!cap_height) {
1338 FT_BBox bbox;
1339 if (getCBoxForLetter('H', &bbox)) {
1340 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1341 }
1342 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001343 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1344 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1345 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1346 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1347 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1348 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f))
1349 + ascent - descent;
1350 xmin = 0.0f;
1351 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1352 ymin = descent + leading;
1353 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001354 underlineThickness = 0;
1355 underlinePosition = 0;
1356
bungeman41078062014-07-07 08:16:37 -07001357 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1358 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001359 } else {
1360 goto ERROR;
1361 }
1362
1363 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1364 if (!x_height) {
1365 x_height = -ascent;
1366 }
1367 if (!avgCharWidth) {
1368 avgCharWidth = xmax - xmin;
1369 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001370 if (!cap_height) {
1371 cap_height = -ascent;
1372 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001373
1374 // disallow negative linespacing
1375 if (leading < 0.0f) {
1376 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377 }
1378
bungeman41078062014-07-07 08:16:37 -07001379 SkScalar scale = myy;
1380 if (this->isVertical()) {
1381 scale = mxy;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001382 }
bungeman41078062014-07-07 08:16:37 -07001383 metrics->fTop = ymax * scale;
1384 metrics->fAscent = ascent * scale;
1385 metrics->fDescent = descent * scale;
1386 metrics->fBottom = ymin * scale;
1387 metrics->fLeading = leading * scale;
1388 metrics->fAvgCharWidth = avgCharWidth * scale;
reedc17c6582014-10-31 08:20:46 -07001389 metrics->fXMin = xmin * scale;
1390 metrics->fXMax = xmax * scale;
bungeman7316b102014-10-29 12:46:52 -07001391 metrics->fXHeight = x_height;
1392 metrics->fCapHeight = cap_height;
bungeman41078062014-07-07 08:16:37 -07001393 metrics->fUnderlineThickness = underlineThickness * scale;
1394 metrics->fUnderlinePosition = underlinePosition * scale;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001395}
1396
djsollenfcfea992015-01-09 08:18:13 -08001397///////////////////////////////////////////////////////////////////////////////
1398
1399// hand-tuned value to reduce outline embolden strength
1400#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1401 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1402 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1403 #else
1404 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1405 #endif
1406#endif
1407
1408///////////////////////////////////////////////////////////////////////////////
1409
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001410void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1411{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001412 // check to see if the embolden bit is set
1413 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1414 return;
1415 }
1416
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001417 switch (glyph->format) {
1418 case FT_GLYPH_FORMAT_OUTLINE:
1419 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001420 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1421 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001422 FT_Outline_Embolden(&glyph->outline, strength);
1423 break;
1424 case FT_GLYPH_FORMAT_BITMAP:
1425 FT_GlyphSlot_Own_Bitmap(glyph);
1426 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1427 break;
1428 default:
1429 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001430 }
1431}
1432
reed@google.comb4162b12013-07-02 16:32:29 +00001433///////////////////////////////////////////////////////////////////////////////
1434
1435#include "SkUtils.h"
1436
1437static SkUnichar next_utf8(const void** chars) {
1438 return SkUTF8_NextUnichar((const char**)chars);
1439}
1440
1441static SkUnichar next_utf16(const void** chars) {
1442 return SkUTF16_NextUnichar((const uint16_t**)chars);
1443}
1444
1445static SkUnichar next_utf32(const void** chars) {
1446 const SkUnichar** uniChars = (const SkUnichar**)chars;
1447 SkUnichar uni = **uniChars;
1448 *uniChars += 1;
1449 return uni;
1450}
1451
1452typedef SkUnichar (*EncodingProc)(const void**);
1453
1454static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1455 static const EncodingProc gProcs[] = {
1456 next_utf8, next_utf16, next_utf32
1457 };
1458 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1459 return gProcs[enc];
1460}
1461
1462int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001463 uint16_t glyphs[], int glyphCount) const
1464{
reed@google.comb4162b12013-07-02 16:32:29 +00001465 AutoFTAccess fta(this);
1466 FT_Face face = fta.face();
1467 if (!face) {
1468 if (glyphs) {
1469 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1470 }
1471 return 0;
1472 }
1473
1474 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1475
1476 if (NULL == glyphs) {
1477 for (int i = 0; i < glyphCount; ++i) {
1478 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1479 return i;
1480 }
1481 }
1482 return glyphCount;
1483 } else {
1484 int first = glyphCount;
1485 for (int i = 0; i < glyphCount; ++i) {
1486 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1487 glyphs[i] = SkToU16(id);
1488 if (0 == id && i < first) {
1489 first = i;
1490 }
1491 }
1492 return first;
1493 }
1494}
1495
1496int SkTypeface_FreeType::onCountGlyphs() const {
1497 // we cache this value, using -1 as a sentinel for "not computed"
1498 if (fGlyphCount < 0) {
1499 AutoFTAccess fta(this);
1500 FT_Face face = fta.face();
1501 // if the face failed, we still assign a non-negative value
1502 fGlyphCount = face ? face->num_glyphs : 0;
1503 }
1504 return fGlyphCount;
1505}
1506
bungeman@google.com839702b2013-08-07 17:09:22 +00001507SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001508 SkTypeface::LocalizedStrings* nameIter =
1509 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1510 if (NULL == nameIter) {
1511 SkString familyName;
1512 this->getFamilyName(&familyName);
1513 SkString language("und"); //undetermined
1514 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1515 }
1516 return nameIter;
1517}
1518
bungeman@google.comddc218e2013-08-01 22:29:43 +00001519int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1520 AutoFTAccess fta(this);
1521 FT_Face face = fta.face();
1522
1523 FT_ULong tableCount = 0;
1524 FT_Error error;
1525
1526 // When 'tag' is NULL, returns number of tables in 'length'.
1527 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1528 if (error) {
1529 return 0;
1530 }
1531
1532 if (tags) {
1533 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1534 FT_ULong tableTag;
1535 FT_ULong tablelength;
1536 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1537 if (error) {
1538 return 0;
1539 }
1540 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1541 }
1542 }
1543 return tableCount;
1544}
1545
1546size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1547 size_t length, void* data) const
1548{
1549 AutoFTAccess fta(this);
1550 FT_Face face = fta.face();
1551
1552 FT_ULong tableLength = 0;
1553 FT_Error error;
1554
1555 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1556 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1557 if (error) {
1558 return 0;
1559 }
1560
1561 if (offset > tableLength) {
1562 return 0;
1563 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001564 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001565 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001566 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1567 if (error) {
1568 return 0;
1569 }
1570 }
1571
1572 return size;
1573}
1574
reed@google.comb4162b12013-07-02 16:32:29 +00001575///////////////////////////////////////////////////////////////////////////////
1576///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001577
bungeman9dc24682014-12-01 14:01:32 -08001578SkTypeface_FreeType::Scanner::Scanner() : fLibrary(NULL) {
1579 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1580 return;
bungeman14df8332014-10-28 15:07:23 -07001581 }
bungeman9dc24682014-12-01 14:01:32 -08001582 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001583}
1584SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001585 if (fLibrary) {
1586 FT_Done_Library(fLibrary);
1587 }
bungeman14df8332014-10-28 15:07:23 -07001588}
1589
1590FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1591 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001592{
bungeman14df8332014-10-28 15:07:23 -07001593 if (fLibrary == NULL) {
1594 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001595 }
1596
bungeman14df8332014-10-28 15:07:23 -07001597 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001598 memset(&args, 0, sizeof(args));
1599
1600 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001601
bsalomon49f085d2014-09-05 13:34:00 -07001602 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001603 args.flags = FT_OPEN_MEMORY;
1604 args.memory_base = (const FT_Byte*)memoryBase;
1605 args.memory_size = stream->getLength();
1606 } else {
bungeman14df8332014-10-28 15:07:23 -07001607 memset(ftStream, 0, sizeof(*ftStream));
1608 ftStream->size = stream->getLength();
1609 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001610 ftStream->read = sk_ft_stream_io;
1611 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001612
1613 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001614 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001615 }
1616
1617 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001618 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
1619 return NULL;
1620 }
1621 return face;
1622}
1623
1624bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1625 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1626
1627 FT_StreamRec streamRec;
1628 FT_Face face = this->openFace(stream, -1, &streamRec);
1629 if (NULL == face) {
1630 return false;
1631 }
1632
1633 *numFaces = face->num_faces;
1634
1635 FT_Done_Face(face);
1636 return true;
1637}
1638
1639#include "SkTSearch.h"
1640bool SkTypeface_FreeType::Scanner::scanFont(
bungeman41868fe2015-05-20 09:21:04 -07001641 SkStream* stream, int ttcIndex,
1642 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001643{
1644 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1645
1646 FT_StreamRec streamRec;
1647 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
1648 if (NULL == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001649 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001650 }
1651
bungemana4c4a2d2014-10-20 13:33:19 -07001652 int weight = SkFontStyle::kNormal_Weight;
1653 int width = SkFontStyle::kNormal_Width;
1654 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001655 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001656 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001657 }
1658 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001659 slant = SkFontStyle::kItalic_Slant;
1660 }
1661
1662 PS_FontInfoRec psFontInfo;
1663 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1664 if (os2 && os2->version != 0xffff) {
1665 weight = os2->usWeightClass;
1666 width = os2->usWidthClass;
1667 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1668 static const struct {
1669 char const * const name;
1670 int const weight;
1671 } commonWeights [] = {
1672 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001673 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001674 { "black", SkFontStyle::kBlack_Weight },
1675 { "bold", SkFontStyle::kBold_Weight },
1676 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1677 { "demi", SkFontStyle::kSemiBold_Weight },
1678 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001679 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001680 { "extrabold", SkFontStyle::kExtraBold_Weight },
1681 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001682 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001683 { "heavy", SkFontStyle::kBlack_Weight },
1684 { "light", SkFontStyle::kLight_Weight },
1685 { "medium", SkFontStyle::kMedium_Weight },
1686 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001687 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001688 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001689 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001690 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001691 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001692 { "thin", SkFontStyle::kThin_Weight },
1693 { "ultra", SkFontStyle::kExtraBold_Weight },
1694 { "ultrablack", 1000 },
1695 { "ultrabold", SkFontStyle::kExtraBold_Weight },
1696 { "ultraheavy", 1000 },
1697 { "ultralight", SkFontStyle::kExtraLight_Weight },
1698 };
1699 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001700 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001701 if (index >= 0) {
1702 weight = commonWeights[index].weight;
1703 } else {
bungeman14df8332014-10-28 15:07:23 -07001704 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001705 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001706 }
1707
1708 if (name) {
1709 name->set(face->family_name);
1710 }
1711 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001712 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001713 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001714 if (isFixedPitch) {
1715 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001716 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001717
bungeman41868fe2015-05-20 09:21:04 -07001718 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
1719 FT_MM_Var* variations = NULL;
1720 FT_Error err = FT_Get_MM_Var(face, &variations);
1721 if (err) {
1722 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1723 face->family_name));
1724 return false;
1725 }
1726 SkAutoFree autoFreeVariations(variations);
1727
1728 axes->reset(variations->num_axis);
1729 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1730 const FT_Var_Axis& ftAxis = variations->axis[i];
1731 (*axes)[i].fTag = ftAxis.tag;
1732 (*axes)[i].fMinimum = ftAxis.minimum;
1733 (*axes)[i].fDefault = ftAxis.def;
1734 (*axes)[i].fMaximum = ftAxis.maximum;
1735 }
1736 }
bungeman41868fe2015-05-20 09:21:04 -07001737
reed@android.com8a1c16f2008-12-17 15:59:43 +00001738 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001739 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001740}