blob: d5b79855281cb05ee5edda36fc9ba75d3e2c5d08 [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"
14#include "SkFontHost.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"
bungeman@google.coma9802692013-08-07 02:45:25 +000020#include "SkOTUtils.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000021#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000022#include "SkStream.h"
23#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000024#include "SkTemplates.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000025#include "SkThread.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
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
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000044// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
45// were introduced in FreeType 2.5.0.
46// The following may be removed once FreeType 2.5.0 is required to build.
47#ifndef FT_LOAD_COLOR
48# define FT_LOAD_COLOR ( 1L << 20 )
49# define FT_PIXEL_MODE_BGRA 7
50#endif
51
52// FT_HAS_COLOR and the corresponding FT_FACE_FLAG_COLOR
53// were introduced in FreeType 2.5.1
54// The following may be removed once FreeType 2.5.1 is required to build.
55#ifndef FT_HAS_COLOR
56# define FT_HAS_COLOR(face) false
57#endif
58
reed@android.com8a1c16f2008-12-17 15:59:43 +000059//#define ENABLE_GLYPH_SPEW // for tracing calls
60//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080061//#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
62//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000063//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000064
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000065using namespace skia_advanced_typeface_metrics_utils;
66
reed@google.comeffc5012011-06-27 16:44:46 +000067static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080068 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000069}
70
reed@android.com8a1c16f2008-12-17 15:59:43 +000071//////////////////////////////////////////////////////////////////////////
72
bungeman9dc24682014-12-01 14:01:32 -080073extern "C" {
74 static void* sk_ft_alloc(FT_Memory, long size) {
75 return sk_malloc_throw(size);
76 }
77 static void sk_ft_free(FT_Memory, void* block) {
78 sk_free(block);
79 }
80 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
81 return sk_realloc_throw(block, new_size);
82 }
83};
84FT_MemoryRec_ gFTMemory = { NULL, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
85
86class FreeTypeLibrary : SkNoncopyable {
87public:
88 FreeTypeLibrary() : fLibrary(NULL), fIsLCDSupported(false), fLCDExtra(0) {
89 if (FT_New_Library(&gFTMemory, &fLibrary)) {
90 return;
91 }
92 FT_Add_Default_Modules(fLibrary);
93
94 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
95 // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
96 // SetLcdFilter must be called before SetLcdFilterWeights.
97 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
98 fIsLCDSupported = true;
99 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
100
101#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
102 // Adds to 0x110 simulating ink spread, but provides better results than default.
103 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
104
105# if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
106 FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
107# elif SK_CAN_USE_DLOPEN == 1
108 //The FreeType library is already loaded, so symbols are available in process.
109 void* self = dlopen(NULL, RTLD_LAZY);
110 if (self) {
111 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
112 //The following cast is non-standard, but safe for POSIX.
113 *reinterpret_cast<void**>(&setLcdFilterWeights) =
114 dlsym(self, "FT_Library_SetLcdFilterWeights");
115 dlclose(self);
116
117 if (setLcdFilterWeights) {
118 setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
119 }
120 }
121# endif
122#endif
123 }
124 }
125 ~FreeTypeLibrary() {
126 if (fLibrary) {
127 FT_Done_Library(fLibrary);
128 }
129 }
130
131 FT_Library library() { return fLibrary; }
132 bool isLCDSupported() { return fIsLCDSupported; }
133 int lcdExtra() { return fLCDExtra; }
134
135private:
136 FT_Library fLibrary;
137 bool fIsLCDSupported;
138 int fLCDExtra;
139
140 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
141 // The following platforms provide FreeType of at least 2.4.0.
142 // Ubuntu >= 11.04 (previous deprecated April 2013)
143 // Debian >= 6.0 (good)
144 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
145 // Fedora >= 14 (good)
146 // Android >= Gingerbread (good)
147 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
148};
149
reed@android.com8a1c16f2008-12-17 15:59:43 +0000150struct SkFaceRec;
151
digit@google.com1771cbf2012-01-26 21:26:40 +0000152SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800153static FreeTypeLibrary* gFTLibrary;
154static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000155
bungeman9dc24682014-12-01 14:01:32 -0800156// Private to RefFreeType and UnrefFreeType
157static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000158
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000159// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800160static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800161 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800162 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800163
bungeman9dc24682014-12-01 14:01:32 -0800164 if (0 == gFTCount) {
165 SkASSERT(NULL == gFTLibrary);
166 gFTLibrary = SkNEW(FreeTypeLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000167 }
bungeman9dc24682014-12-01 14:01:32 -0800168 ++gFTCount;
169 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000170}
171
bungeman9dc24682014-12-01 14:01:32 -0800172// Caller must lock gFTMutex before calling this function.
173static void unref_ft_library() {
174 gFTMutex.assertHeld();
175 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000176
bungeman9dc24682014-12-01 14:01:32 -0800177 --gFTCount;
178 if (0 == gFTCount) {
179 SkASSERT(NULL != gFTLibrary);
180 SkDELETE(gFTLibrary);
181 SkDEBUGCODE(gFTLibrary = NULL;)
182 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000183}
184
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000185class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000186public:
reed@google.com0da48612013-03-19 16:06:52 +0000187 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000188 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000189
reed@android.com62900b42009-02-11 15:07:19 +0000190 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000191 return fFaceRec != NULL &&
192 fFTSize != NULL &&
193 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000194 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000195
196protected:
bungeman@google.coma76de722012-10-26 19:35:54 +0000197 virtual unsigned generateGlyphCount() SK_OVERRIDE;
198 virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE;
199 virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE;
200 virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE;
201 virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE;
202 virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE;
bungeman41078062014-07-07 08:16:37 -0700203 virtual void generateFontMetrics(SkPaint::FontMetrics*) SK_OVERRIDE;
bungeman@google.coma76de722012-10-26 19:35:54 +0000204 virtual SkUnichar generateGlyphToChar(uint16_t glyph) SK_OVERRIDE;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000205
206private:
207 SkFaceRec* fFaceRec;
208 FT_Face fFace; // reference to shared face in gFaceRecHead
209 FT_Size fFTSize; // our own copy
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000210 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000211 SkFixed fScaleX, fScaleY;
212 FT_Matrix fMatrix22;
213 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000214 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000215 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000216
reed@google.comf073b332013-05-06 12:21:16 +0000217 // Need scalar versions for generateFontMetrics
218 SkVector fScale;
219 SkMatrix fMatrix22Scalar;
220
reed@android.com8a1c16f2008-12-17 15:59:43 +0000221 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000222 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
223 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000224 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000225 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000226 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000227 // Caller must lock gFTMutex before calling this function.
228 // update FreeType2 glyph slot with glyph emboldened
229 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000230};
231
232///////////////////////////////////////////////////////////////////////////
233///////////////////////////////////////////////////////////////////////////
234
reed@android.com8a1c16f2008-12-17 15:59:43 +0000235struct SkFaceRec {
236 SkFaceRec* fNext;
237 FT_Face fFace;
238 FT_StreamRec fFTStream;
239 SkStream* fSkStream;
240 uint32_t fRefCnt;
241 uint32_t fFontID;
242
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000243 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000244 SkFaceRec(SkStream* strm, uint32_t fontID);
245 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000246 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000247 }
248};
249
250extern "C" {
bungeman9dc24682014-12-01 14:01:32 -0800251 static unsigned long sk_ft_stream_io(FT_Stream stream,
252 unsigned long offset,
253 unsigned char* buffer,
254 unsigned long count)
255 {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000256 SkStream* str = (SkStream*)stream->descriptor.pointer;
257
258 if (count) {
259 if (!str->rewind()) {
260 return 0;
bungeman9dc24682014-12-01 14:01:32 -0800261 }
262 if (offset) {
263 if (str->skip(offset) != offset) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000264 return 0;
265 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000266 }
bungeman9dc24682014-12-01 14:01:32 -0800267 count = str->read(buffer, count);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000268 }
269 return count;
270 }
271
bungeman9dc24682014-12-01 14:01:32 -0800272 static void sk_ft_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000273}
274
275SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
vandebo@chromium.org9af25f32012-03-28 21:24:27 +0000276 : fNext(NULL), fSkStream(strm), fRefCnt(1), fFontID(fontID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000277// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
278
reed@android.com4516f472009-06-29 16:25:36 +0000279 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000280 fFTStream.size = fSkStream->getLength();
281 fFTStream.descriptor.pointer = fSkStream;
bungeman9dc24682014-12-01 14:01:32 -0800282 fFTStream.read = sk_ft_stream_io;
283 fFTStream.close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000284}
285
reed@android.com62900b42009-02-11 15:07:19 +0000286// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000287// Caller must lock gFTMutex before calling this function.
reed@google.com2cdc6712013-03-21 18:22:00 +0000288static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
bungeman5ec443c2014-11-21 13:18:34 -0800289 gFTMutex.assertHeld();
290
reed@google.com2cdc6712013-03-21 18:22:00 +0000291 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000292 SkFaceRec* rec = gFaceRecHead;
293 while (rec) {
294 if (rec->fFontID == fontID) {
295 SkASSERT(rec->fFace);
296 rec->fRefCnt += 1;
297 return rec;
298 }
299 rec = rec->fNext;
300 }
301
reed@google.com2cdc6712013-03-21 18:22:00 +0000302 int face_index;
303 SkStream* strm = typeface->openStream(&face_index);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000304 if (NULL == strm) {
reed@google.com2cdc6712013-03-21 18:22:00 +0000305 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306 }
307
308 // this passes ownership of strm to the rec
309 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
310
bungeman9dc24682014-12-01 14:01:32 -0800311 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000312 memset(&args, 0, sizeof(args));
313 const void* memoryBase = strm->getMemoryBase();
314
bsalomon49f085d2014-09-05 13:34:00 -0700315 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000316 args.flags = FT_OPEN_MEMORY;
317 args.memory_base = (const FT_Byte*)memoryBase;
318 args.memory_size = strm->getLength();
319 } else {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000320 args.flags = FT_OPEN_STREAM;
321 args.stream = &rec->fFTStream;
322 }
323
bungeman9dc24682014-12-01 14:01:32 -0800324 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, face_index, &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000325 if (err) { // bad filename, try the default font
bungeman5ec443c2014-11-21 13:18:34 -0800326 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000327 SkDELETE(rec);
reed@google.com2cdc6712013-03-21 18:22:00 +0000328 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000329 }
bungeman9dc24682014-12-01 14:01:32 -0800330 SkASSERT(rec->fFace);
331 rec->fNext = gFaceRecHead;
332 gFaceRecHead = rec;
333 return rec;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000334}
335
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000336// Caller must lock gFTMutex before calling this function.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000337static void unref_ft_face(FT_Face face) {
bungeman5ec443c2014-11-21 13:18:34 -0800338 gFTMutex.assertHeld();
339
reed@android.com8a1c16f2008-12-17 15:59:43 +0000340 SkFaceRec* rec = gFaceRecHead;
341 SkFaceRec* prev = NULL;
342 while (rec) {
343 SkFaceRec* next = rec->fNext;
344 if (rec->fFace == face) {
345 if (--rec->fRefCnt == 0) {
346 if (prev) {
347 prev->fNext = next;
348 } else {
349 gFaceRecHead = next;
350 }
351 FT_Done_Face(face);
352 SkDELETE(rec);
353 }
354 return;
355 }
356 prev = rec;
357 rec = next;
358 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000359 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000360}
361
reed@google.comb4162b12013-07-02 16:32:29 +0000362class AutoFTAccess {
363public:
364 AutoFTAccess(const SkTypeface* tf) : fRec(NULL), fFace(NULL) {
365 gFTMutex.acquire();
bungeman9dc24682014-12-01 14:01:32 -0800366 if (!ref_ft_library()) {
367 sk_throw();
reed@google.comb4162b12013-07-02 16:32:29 +0000368 }
369 fRec = ref_ft_face(tf);
370 if (fRec) {
371 fFace = fRec->fFace;
372 }
373 }
374
375 ~AutoFTAccess() {
376 if (fFace) {
377 unref_ft_face(fFace);
378 }
bungeman9dc24682014-12-01 14:01:32 -0800379 unref_ft_library();
reed@google.comb4162b12013-07-02 16:32:29 +0000380 gFTMutex.release();
381 }
382
383 SkFaceRec* rec() { return fRec; }
384 FT_Face face() { return fFace; }
385
386private:
387 SkFaceRec* fRec;
388 FT_Face fFace;
389};
390
reed@android.com8a1c16f2008-12-17 15:59:43 +0000391///////////////////////////////////////////////////////////////////////////
392
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000393static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000394 FT_UShort fsType = FT_Get_FSType_Flags(face);
395 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
396 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000397}
398
vandebo0f9bad02014-06-19 11:05:39 -0700399static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700400 FT_UShort fsType = FT_Get_FSType_Flags(face);
401 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700402}
403
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000404static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
405 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
406 if (!glyph_id)
407 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000408 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
409 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000410 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
411 return true;
412}
413
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000414static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000415 FT_Fixed advance = 0;
bungeman5ec443c2014-11-21 13:18:34 -0800416 if (FT_Get_Advances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000417 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000418 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000419 SkASSERT(data);
420 *data = advance;
421 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000422}
423
bungeman5ec443c2014-11-21 13:18:34 -0800424static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000425 // Check and see if we have Unicode cmaps.
426 for (int i = 0; i < face->num_charmaps; ++i) {
427 // CMaps known to support Unicode:
428 // Platform ID Encoding ID Name
429 // ----------- ----------- -----------------------------------
430 // 0 0,1 Apple Unicode
431 // 0 3 Apple Unicode 2.0 (preferred)
432 // 3 1 Microsoft Unicode UCS-2
433 // 3 10 Microsoft Unicode UCS-4 (preferred)
434 //
435 // See Apple TrueType Reference Manual
436 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
437 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
438 // Microsoft OpenType Specification
439 // http://www.microsoft.com/typography/otspec/cmap.htm
440
441 FT_UShort platformId = face->charmaps[i]->platform_id;
442 FT_UShort encodingId = face->charmaps[i]->encoding_id;
443
444 if (platformId != 0 && platformId != 3) {
445 continue;
446 }
447 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
448 continue;
449 }
450 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
451 (platformId == 0 && encodingId == 3));
452
453 FT_Set_Charmap(face, face->charmaps[i]);
454 if (glyphToUnicode->isEmpty()) {
455 glyphToUnicode->setCount(face->num_glyphs);
456 memset(glyphToUnicode->begin(), 0,
457 sizeof(SkUnichar) * face->num_glyphs);
458 }
459
460 // Iterate through each cmap entry.
461 FT_UInt glyphIndex;
462 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
463 glyphIndex != 0;
464 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
465 if (charCode &&
466 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
467 (*glyphToUnicode)[glyphIndex] = charCode;
468 }
469 }
470 }
471}
472
reed@google.com2689f612013-03-20 20:01:47 +0000473SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000474 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
475 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000476 uint32_t glyphIDsCount) const {
djsollen@google.comda957722011-11-16 17:00:46 +0000477#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000478 return NULL;
479#else
reed@google.comb4162b12013-07-02 16:32:29 +0000480 AutoFTAccess fta(this);
481 FT_Face face = fta.face();
482 if (!face) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000483 return NULL;
reed@google.comb4162b12013-07-02 16:32:29 +0000484 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000485
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000486 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
487 info->fFontName.set(FT_Get_Postscript_Name(face));
vandebo0f9bad02014-06-19 11:05:39 -0700488 info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag;
489 if (FT_HAS_MULTIPLE_MASTERS(face)) {
490 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
491 info->fFlags, SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag);
492 }
493 if (!canEmbed(face)) {
494 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
495 info->fFlags,
496 SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag);
497 }
498 if (!canSubset(face)) {
499 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
500 info->fFlags,
501 SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag);
502 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000503 info->fLastGlyphID = face->num_glyphs - 1;
504 info->fEmSize = 1000;
505
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000506 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000507 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000508 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000509 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000510 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000511 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000512 cid = true;
513 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000514 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000515 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000516 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000517 cid = true;
518 TT_Header* ttHeader;
519 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
520 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000521 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000522 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000523 } else {
524 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000525 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000526
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000527 info->fStyle = 0;
528 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000529 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000530 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000531 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000532
533 PS_FontInfoRec ps_info;
534 TT_Postscript* tt_info;
535 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
536 info->fItalicAngle = ps_info.italic_angle;
537 } else if ((tt_info =
538 (TT_Postscript*)FT_Get_Sfnt_Table(face,
539 ft_sfnt_post)) != NULL) {
540 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
541 } else {
542 info->fItalicAngle = 0;
543 }
544
545 info->fAscent = face->ascender;
546 info->fDescent = face->descender;
547
548 // Figure out a good guess for StemV - Min width of i, I, !, 1.
549 // This probably isn't very good with an italic font.
550 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000551 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000552 char stem_chars[] = {'i', 'I', '!', '1'};
553 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
554 FT_BBox bbox;
555 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
556 int16_t width = bbox.xMax - bbox.xMin;
557 if (width > 0 && width < min_width) {
558 min_width = width;
559 info->fStemV = min_width;
560 }
561 }
562 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000563
564 TT_PCLT* pclt_info;
565 TT_OS2* os2_table;
566 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
567 info->fCapHeight = pclt_info->CapHeight;
568 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
569 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000570 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000571 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000572 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000573 } else if (((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) &&
574 // sCapHeight is available only when version 2 or later.
575 os2_table->version != 0xFFFF &&
576 os2_table->version >= 2) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000577 info->fCapHeight = os2_table->sCapHeight;
578 } else {
579 // Figure out a good guess for CapHeight: average the height of M and X.
580 FT_BBox m_bbox, x_bbox;
581 bool got_m, got_x;
582 got_m = GetLetterCBox(face, 'M', &m_bbox);
583 got_x = GetLetterCBox(face, 'X', &x_bbox);
584 if (got_m && got_x) {
585 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
586 x_bbox.yMin) / 2;
587 } else if (got_m && !got_x) {
588 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
589 } else if (!got_m && got_x) {
590 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000591 } else {
592 // Last resort, use the ascent.
593 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000594 }
595 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000596
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000597 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
598 face->bbox.xMax, face->bbox.yMin);
599
vandebo0f9bad02014-06-19 11:05:39 -0700600 if (!FT_IS_SCALABLE(face)) {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000601 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
602 }
603
604 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000605 if (FT_IS_FIXED_WIDTH(face)) {
606 appendRange(&info->fGlyphWidths, 0);
607 int16_t advance = face->max_advance_width;
608 info->fGlyphWidths->fAdvance.append(1, &advance);
609 finishRange(info->fGlyphWidths.get(), 0,
610 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000611 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000612 appendRange(&info->fGlyphWidths, 0);
613 // So as to not blow out the stack, get advances in batches.
614 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
615 FT_Fixed advances[128];
616 int advanceCount = 128;
bungeman5ec443c2014-11-21 13:18:34 -0800617 if (gID + advanceCount > face->num_glyphs) {
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000618 advanceCount = face->num_glyphs - gID;
bungeman5ec443c2014-11-21 13:18:34 -0800619 }
620 FT_Get_Advances(face, gID, advanceCount, FT_LOAD_NO_SCALE, advances);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000621 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000622 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000623 info->fGlyphWidths->fAdvance.append(1, &advance);
624 }
625 }
626 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
627 SkAdvancedTypefaceMetrics::WidthRange::kRange);
628 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000629 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000630 getAdvanceData(face,
631 face->num_glyphs,
632 glyphIDs,
633 glyphIDsCount,
634 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000635 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000636 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000637
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000638 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
639 FT_HAS_VERTICAL(face)) {
640 SkASSERT(false); // Not implemented yet.
641 }
642
643 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
644 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
645 // Postscript fonts may contain more than 255 glyphs, so we end up
646 // using multiple font descriptions with a glyph ordering. Record
647 // the name of each glyph.
648 info->fGlyphNames.reset(
649 new SkAutoTArray<SkString>(face->num_glyphs));
650 for (int gID = 0; gID < face->num_glyphs; gID++) {
651 char glyphName[128]; // PS limit for names is 127 bytes.
652 FT_Get_Glyph_Name(face, gID, glyphName, 128);
653 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000654 }
655 }
656
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000657 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
658 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
659 face->num_charmaps) {
660 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
661 }
662
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000663 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000664#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000665}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000666
reed@google.com618ef5e2011-01-26 22:10:41 +0000667///////////////////////////////////////////////////////////////////////////
668
reed@google.com8ed436c2011-07-21 14:12:36 +0000669static bool bothZero(SkScalar a, SkScalar b) {
670 return 0 == a && 0 == b;
671}
672
673// returns false if there is any non-90-rotation or skew
674static bool isAxisAligned(const SkScalerContext::Rec& rec) {
675 return 0 == rec.fPreSkewX &&
676 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
677 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
678}
679
reed@google.com0da48612013-03-19 16:06:52 +0000680SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
681 const SkDescriptor* desc) const {
682 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
683 (const_cast<SkTypeface_FreeType*>(this),
684 desc));
685 if (!c->success()) {
686 SkDELETE(c);
687 c = NULL;
688 }
689 return c;
690}
691
692void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000693 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
694 //Cap the requested size as larger sizes give bogus values.
695 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000696 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000697 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000698 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000699
bungeman9dc24682014-12-01 14:01:32 -0800700 AutoFTAccess fta(this);
701 if (!gFTLibrary->isLCDSupported() && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000702 // If the runtime Freetype library doesn't support LCD mode, we disable
703 // it here.
704 rec->fMaskFormat = SkMask::kA8_Format;
705 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000706
reed@google.com618ef5e2011-01-26 22:10:41 +0000707 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000708 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000709 // collapse full->normal hinting if we're not doing LCD
710 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000711 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000712 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000713 if (SkPaint::kNo_Hinting != h) {
714 h = SkPaint::kSlight_Hinting;
715 }
716 }
717
reed@google.com8ed436c2011-07-21 14:12:36 +0000718 // rotated text looks bad with hinting, so we disable it as needed
719 if (!isAxisAligned(*rec)) {
720 h = SkPaint::kNo_Hinting;
721 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000722 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000723
bungeman@google.com97efada2012-07-30 20:40:50 +0000724#ifndef SK_GAMMA_APPLY_TO_A8
725 if (!isLCD(*rec)) {
726 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000727 }
reed@google.com1ac83502012-02-28 17:06:02 +0000728#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000729}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000730
reed@google.com38c37dd2013-03-21 15:36:26 +0000731int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000732 AutoFTAccess fta(this);
733 FT_Face face = fta.face();
734 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000735}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000736
reed@google.com35fe7372013-10-30 15:07:03 +0000737bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
738 int count, int32_t adjustments[]) const {
739 AutoFTAccess fta(this);
740 FT_Face face = fta.face();
741 if (!face || !FT_HAS_KERNING(face)) {
742 return false;
743 }
744
745 for (int i = 0; i < count - 1; ++i) {
746 FT_Vector delta;
747 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
748 FT_KERNING_UNSCALED, &delta);
749 if (err) {
750 return false;
751 }
752 adjustments[i] = delta.x;
753 }
754 return true;
755}
756
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000757static FT_Int chooseBitmapStrike(FT_Face face, SkFixed scaleY) {
758 // early out if face is bad
759 if (face == NULL) {
760 SkDEBUGF(("chooseBitmapStrike aborted due to NULL face\n"));
761 return -1;
762 }
763 // determine target ppem
764 FT_Pos targetPPEM = SkFixedToFDot6(scaleY);
765 // find a bitmap strike equal to or just larger than the requested size
766 FT_Int chosenStrikeIndex = -1;
767 FT_Pos chosenPPEM = 0;
768 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
769 FT_Pos thisPPEM = face->available_sizes[strikeIndex].y_ppem;
770 if (thisPPEM == targetPPEM) {
771 // exact match - our search stops here
772 chosenPPEM = thisPPEM;
773 chosenStrikeIndex = strikeIndex;
774 break;
775 } else if (chosenPPEM < targetPPEM) {
776 // attempt to increase chosenPPEM
777 if (thisPPEM > chosenPPEM) {
778 chosenPPEM = thisPPEM;
779 chosenStrikeIndex = strikeIndex;
780 }
781 } else {
782 // attempt to decrease chosenPPEM, but not below targetPPEM
783 if (thisPPEM < chosenPPEM && thisPPEM > targetPPEM) {
784 chosenPPEM = thisPPEM;
785 chosenStrikeIndex = strikeIndex;
786 }
787 }
788 }
789 if (chosenStrikeIndex != -1) {
790 // use the chosen strike
791 FT_Error err = FT_Select_Size(face, chosenStrikeIndex);
792 if (err != 0) {
793 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x\n", face->family_name,
794 chosenStrikeIndex, err));
795 chosenStrikeIndex = -1;
796 }
797 }
798 return chosenStrikeIndex;
799}
800
reed@google.com0da48612013-03-19 16:06:52 +0000801SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
802 const SkDescriptor* desc)
803 : SkScalerContext_FreeType_Base(typeface, desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000804 SkAutoMutexAcquire ac(gFTMutex);
805
bungeman9dc24682014-12-01 14:01:32 -0800806 if (!ref_ft_library()) {
807 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000808 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000809
810 // load the font file
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000811 fStrikeIndex = -1;
reed@android.com62900b42009-02-11 15:07:19 +0000812 fFTSize = NULL;
813 fFace = NULL;
reed@google.com2cdc6712013-03-21 18:22:00 +0000814 fFaceRec = ref_ft_face(typeface);
reed@android.com62900b42009-02-11 15:07:19 +0000815 if (NULL == fFaceRec) {
816 return;
817 }
818 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000819
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000820 // A is the total matrix.
821 SkMatrix A;
822 fRec.getSingleMatrix(&A);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000823
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000824 SkScalar sx = A.getScaleX();
825 SkScalar sy = A.getScaleY();
reed@google.comf073b332013-05-06 12:21:16 +0000826 fMatrix22Scalar.reset();
827
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000828 // In GDI, the hinter is aware of the current transformation
829 // (the transform is in some sense applied before/with the hinting).
830 // The bytecode can then test if it is rotated or stretched and decide
831 // to apply instructions or not.
832 //
833 // FreeType, however, always does the transformation strictly after hinting.
834 // It just sets 'rotated' and 'stretched' to false and only applies the
835 // size before hinting.
836 //
837 // Also, FreeType respects the head::flags::IntegerScaling flag,
838 // (although this is patched out on most major distros)
839 // so it is critical to get the size correct on the request.
840 //
841 // This also gets us the actual closest size on bitmap fonts as well.
842 if (A.getSkewX() || A.getSkewY() || sx < 0 || sy < 0) {
843 // h is where A maps the horizontal baseline.
844 SkPoint h = SkPoint::Make(SK_Scalar1, 0);
845 A.mapPoints(&h, 1);
846
847 // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
848 SkMatrix G;
849 SkComputeGivensRotation(h, &G);
850
851 // GA is the matrix A with rotation removed.
852 SkMatrix GA(G);
853 GA.preConcat(A);
854
855 sx = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
856 sy = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
857
858 // sA is the total matrix A without the text scale.
859 SkMatrix sA(A);
860 sA.preScale(SkScalarInvert(sx), SkScalarInvert(sy)); //remove text size
861
862 fMatrix22Scalar.setScaleX(sA.getScaleX());
863 fMatrix22Scalar.setSkewX(-sA.getSkewX());
864 fMatrix22Scalar.setSkewY(-sA.getSkewY());
865 fMatrix22Scalar.setScaleY(sA.getScaleY());
866 }
867 fScale.set(sx, sy);
868 fScaleX = SkScalarToFixed(sx);
869 fScaleY = SkScalarToFixed(sy);
870 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
871 fMatrix22.xy = SkScalarToFixed(fMatrix22Scalar.getSkewX());
872 fMatrix22.yx = SkScalarToFixed(fMatrix22Scalar.getSkewY());
873 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000874
reed@google.coma1bfa212012-03-08 21:57:12 +0000875 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
876
reed@android.com8a1c16f2008-12-17 15:59:43 +0000877 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000878 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000879 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000880 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000881
agl@chromium.org70a303f2010-05-10 14:15:50 +0000882 if (SkMask::kBW_Format == fRec.fMaskFormat) {
883 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
884 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000885 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000886 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000887 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000888 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000889 } else {
890 switch (fRec.getHinting()) {
891 case SkPaint::kNo_Hinting:
892 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000893 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000894 break;
895 case SkPaint::kSlight_Hinting:
896 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
897 break;
898 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000899 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000900 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700901#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
902 } else {
903 loadFlags = FT_LOAD_NO_AUTOHINT;
904#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000905 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000906 break;
907 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000908 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000909 loadFlags = FT_LOAD_FORCE_AUTOHINT;
910 break;
911 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000912 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000913 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000914 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000915 loadFlags = FT_LOAD_TARGET_LCD_V;
916 } else {
917 loadFlags = FT_LOAD_TARGET_LCD;
918 }
reed@google.comea2333d2011-03-14 16:44:56 +0000919 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000920 break;
921 default:
922 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
923 break;
924 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925 }
926
reed@google.comeffc5012011-06-27 16:44:46 +0000927 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000928 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000929 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000930
reed@google.com96a9f7912011-05-06 11:49:30 +0000931 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
932 // advances, as fontconfig and cairo do.
933 // See http://code.google.com/p/skia/issues/detail?id=222.
934 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
935
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000936 // Use vertical layout if requested.
937 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
938 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
939 }
940
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000941 loadFlags |= FT_LOAD_COLOR;
942
reed@android.come4d0bc02009-07-24 19:53:20 +0000943 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944 }
945
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000946 FT_Error err = FT_New_Size(fFace, &fFTSize);
947 if (err != 0) {
948 SkDEBUGF(("FT_New_Size returned %x for face %s\n", err, fFace->family_name));
949 fFace = NULL;
950 return;
951 }
952 err = FT_Activate_Size(fFTSize);
953 if (err != 0) {
954 SkDEBUGF(("FT_Activate_Size(%08x, 0x%x, 0x%x) returned 0x%x\n", fFace, fScaleX, fScaleY,
955 err));
956 fFTSize = NULL;
957 return;
958 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000959
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000960 if (FT_IS_SCALABLE(fFace)) {
961 err = FT_Set_Char_Size(fFace, SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000962 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000963 SkDEBUGF(("FT_Set_CharSize(%08x, 0x%x, 0x%x) returned 0x%x\n",
964 fFace, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000965 fFace = NULL;
966 return;
967 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000968 FT_Set_Transform(fFace, &fMatrix22, NULL);
969 } else if (FT_HAS_FIXED_SIZES(fFace)) {
970 fStrikeIndex = chooseBitmapStrike(fFace, fScaleY);
971 if (fStrikeIndex == -1) {
972 SkDEBUGF(("no glyphs for font \"%s\" size %f?\n",
973 fFace->family_name, SkFixedToScalar(fScaleY)));
974 } else {
975 // FreeType does no provide linear metrics for bitmap fonts.
976 linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000977
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000978 // FreeType documentation says:
979 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
980 // Bitmap-only fonts ignore this flag.
981 //
982 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
983 // Force this flag off for bitmap only fonts.
984 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000985 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000986 } else {
987 SkDEBUGF(("unknown kind of font \"%s\" size %f?\n",
988 fFace->family_name, SkFixedToScalar(fScaleY)));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000989 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000990
991 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000992}
993
994SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000995 SkAutoMutexAcquire ac(gFTMutex);
996
reed@android.com8a1c16f2008-12-17 15:59:43 +0000997 if (fFTSize != NULL) {
998 FT_Done_Size(fFTSize);
999 }
1000
reed@android.com8a1c16f2008-12-17 15:59:43 +00001001 if (fFace != NULL) {
1002 unref_ft_face(fFace);
1003 }
bungeman9dc24682014-12-01 14:01:32 -08001004
1005 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006}
1007
1008/* We call this before each use of the fFace, since we may be sharing
1009 this face with other context (at different sizes).
1010*/
1011FT_Error SkScalerContext_FreeType::setupSize() {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001012 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 if (err != 0) {
1014 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001015 fFaceRec->fFontID, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001016 fFTSize = NULL;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001017 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001018 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001019
1020 // seems we need to reset this every time (not sure why, but without it
1021 // I get random italics from some other fFTSize)
1022 FT_Set_Transform(fFace, &fMatrix22, NULL);
1023 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001024}
1025
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001026unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001027 return fFace->num_glyphs;
1028}
1029
1030uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
1031 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1032}
1033
reed@android.com9d3a9852010-01-08 14:07:42 +00001034SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
1035 // iterate through each cmap entry, looking for matching glyph indices
1036 FT_UInt glyphIndex;
1037 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1038
1039 while (glyphIndex != 0) {
1040 if (glyphIndex == glyph) {
1041 return charCode;
1042 }
1043 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1044 }
1045
1046 return 0;
1047}
1048
reed@android.com8a1c16f2008-12-17 15:59:43 +00001049void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001050 /* unhinted and light hinted text have linearly scaled advances
1051 * which are very cheap to compute with some font formats...
1052 */
reed@google.combdc99882011-11-21 14:36:57 +00001053 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001054 SkAutoMutexAcquire ac(gFTMutex);
1055
1056 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001057 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001058 return;
1059 }
1060
1061 FT_Error error;
1062 FT_Fixed advance;
1063
djsollen1b277042014-08-06 06:58:06 -07001064 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001065 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1066 &advance );
1067 if (0 == error) {
1068 glyph->fRsbDelta = 0;
1069 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +00001070 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1071 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001072 return;
1073 }
1074 }
bungeman5ec443c2014-11-21 13:18:34 -08001075
reed@android.com8a1c16f2008-12-17 15:59:43 +00001076 /* otherwise, we need to load/hint the glyph, which is slower */
1077 this->generateMetrics(glyph);
1078 return;
1079}
1080
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001081void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1082 FT_BBox* bbox,
1083 bool snapToPixelBoundary) {
1084
1085 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1086
1087 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001088 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1089 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001090 // negate dy since freetype-y-goes-up and skia-y-goes-down
1091 bbox->xMin += dx;
1092 bbox->yMin -= dy;
1093 bbox->xMax += dx;
1094 bbox->yMax -= dy;
1095 }
1096
1097 // outset the box to integral boundaries
1098 if (snapToPixelBoundary) {
1099 bbox->xMin &= ~63;
1100 bbox->yMin &= ~63;
1101 bbox->xMax = (bbox->xMax + 63) & ~63;
1102 bbox->yMax = (bbox->yMax + 63) & ~63;
1103 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001104
1105 // Must come after snapToPixelBoundary so that the width and height are
1106 // consistent. Otherwise asserts will fire later on when generating the
1107 // glyph image.
1108 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1109 FT_Vector vector;
1110 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1111 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1112 FT_Vector_Transform(&vector, &fMatrix22);
1113 bbox->xMin += vector.x;
1114 bbox->xMax += vector.x;
1115 bbox->yMin += vector.y;
1116 bbox->yMax += vector.y;
1117 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001118}
1119
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001120bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1121 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001122 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001123 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001124 }
1125 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001126 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001127 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001128 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001129 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1130 return true;
1131}
1132
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001133void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1134 if (isLCD(fRec)) {
1135 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001136 glyph->fHeight += gFTLibrary->lcdExtra();
1137 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001138 } else {
bungeman9dc24682014-12-01 14:01:32 -08001139 glyph->fWidth += gFTLibrary->lcdExtra();
1140 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001141 }
1142 }
1143}
1144
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001145inline void scaleGlyphMetrics(SkGlyph& glyph, SkScalar scale) {
1146 glyph.fWidth *= scale;
1147 glyph.fHeight *= scale;
1148 glyph.fTop *= scale;
1149 glyph.fLeft *= scale;
1150
1151 SkFixed fixedScale = SkScalarToFixed(scale);
1152 glyph.fAdvanceX = SkFixedMul(glyph.fAdvanceX, fixedScale);
1153 glyph.fAdvanceY = SkFixedMul(glyph.fAdvanceY, fixedScale);
1154}
1155
reed@android.com8a1c16f2008-12-17 15:59:43 +00001156void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1157 SkAutoMutexAcquire ac(gFTMutex);
1158
1159 glyph->fRsbDelta = 0;
1160 glyph->fLsbDelta = 0;
1161
1162 FT_Error err;
1163
1164 if (this->setupSize()) {
1165 goto ERROR;
1166 }
1167
djsollen1b277042014-08-06 06:58:06 -07001168 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001169 if (err != 0) {
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001170#if 0
1171 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%x) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001172 fFaceRec->fFontID, glyph->getGlyphID(), fLoadGlyphFlags, err));
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001173#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001174 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +00001175 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001176 return;
1177 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001178 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001179
1180 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001181 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001182 if (0 == fFace->glyph->outline.n_contours) {
1183 glyph->fWidth = 0;
1184 glyph->fHeight = 0;
1185 glyph->fTop = 0;
1186 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001187 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001188 FT_BBox bbox;
1189 getBBoxForCurrentGlyph(glyph, &bbox, true);
1190
1191 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1192 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1193 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1194 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1195
1196 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001197 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001198 break;
1199
1200 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001201 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1202 FT_Vector vector;
1203 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1204 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1205 FT_Vector_Transform(&vector, &fMatrix22);
1206 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1207 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1208 }
1209
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001210 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1211 glyph->fMaskFormat = SkMask::kARGB32_Format;
1212 }
1213
reed@android.com8a1c16f2008-12-17 15:59:43 +00001214 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1215 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1216 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1217 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1218 break;
1219
1220 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001221 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001222 goto ERROR;
1223 }
1224
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001225 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1226 if (fDoLinearMetrics) {
1227 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1228 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1229 } else {
1230 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1231 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1232 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001233 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001234 if (fDoLinearMetrics) {
1235 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1236 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1237 } else {
1238 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1239 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001240
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001241 if (fRec.fFlags & kDevKernText_Flag) {
1242 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1243 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001244 }
1245 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001246 }
1247
bungemana85511a2014-09-22 12:24:41 -07001248 // If the font isn't scalable, scale the metrics from the non-scalable strike.
1249 // This means do not try to scale embedded bitmaps; only scale bitmaps in bitmap only fonts.
1250 if (!FT_IS_SCALABLE(fFace) && fScaleY && fFace->size->metrics.y_ppem) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001251 // NOTE: both dimensions are scaled by y_ppem. this is WAI.
1252 scaleGlyphMetrics(*glyph, SkScalarDiv(SkFixedToScalar(fScaleY),
1253 SkIntToScalar(fFace->size->metrics.y_ppem)));
1254 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001255
reed@android.com8a1c16f2008-12-17 15:59:43 +00001256#ifdef ENABLE_GLYPH_SPEW
1257 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
djsollen1b277042014-08-06 06:58:06 -07001258 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001259#endif
1260}
1261
bungeman5ec443c2014-11-21 13:18:34 -08001262static void clear_glyph_image(const SkGlyph& glyph) {
1263 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1264}
reed@google.comea2333d2011-03-14 16:44:56 +00001265
bungeman@google.coma76de722012-10-26 19:35:54 +00001266void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001267 SkAutoMutexAcquire ac(gFTMutex);
1268
reed@android.com8a1c16f2008-12-17 15:59:43 +00001269 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001270 clear_glyph_image(glyph);
1271 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001272 }
1273
bungeman5ec443c2014-11-21 13:18:34 -08001274 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001275 if (err != 0) {
1276 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 -08001277 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1278 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001279 return;
1280 }
1281
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001282 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.coma76de722012-10-26 19:35:54 +00001283 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001284}
1285
reed@android.com8a1c16f2008-12-17 15:59:43 +00001286
bungeman5ec443c2014-11-21 13:18:34 -08001287void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001288 SkAutoMutexAcquire ac(gFTMutex);
1289
caryclarka10742c2014-09-18 11:00:40 -07001290 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001291
1292 if (this->setupSize()) {
1293 path->reset();
1294 return;
1295 }
1296
1297 uint32_t flags = fLoadGlyphFlags;
1298 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1299 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1300
djsollen1b277042014-08-06 06:58:06 -07001301 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001302
1303 if (err != 0) {
1304 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001305 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001306 path->reset();
1307 return;
1308 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001309 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001310
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001311 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001312
1313 // The path's origin from FreeType is always the horizontal layout origin.
1314 // Offset the path so that it is relative to the vertical origin if needed.
1315 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1316 FT_Vector vector;
1317 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1318 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1319 FT_Vector_Transform(&vector, &fMatrix22);
1320 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1321 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001322}
1323
bungeman41078062014-07-07 08:16:37 -07001324void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
1325 if (NULL == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001326 return;
1327 }
1328
bungeman41078062014-07-07 08:16:37 -07001329 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330
1331 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001332 ERROR:
bungeman41078062014-07-07 08:16:37 -07001333 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001334 return;
1335 }
1336
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001337 FT_Face face = fFace;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001338 SkScalar scaleX = fScale.x();
reed@google.comf073b332013-05-06 12:21:16 +00001339 SkScalar scaleY = fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001340 SkScalar mxy = fMatrix22Scalar.getSkewX() * scaleY;
1341 SkScalar myy = fMatrix22Scalar.getScaleY() * scaleY;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001342
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001343 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1344 SkScalar upem = SkIntToScalar(face->units_per_EM);
1345 if (!upem) {
1346 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1347 if (ttHeader) {
1348 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001349 }
1350 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001351
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001352 // use the os/2 table as a source of reasonable defaults.
1353 SkScalar x_height = 0.0f;
1354 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001355 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001356 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1357 if (os2) {
1358 x_height = scaleX * SkIntToScalar(os2->sxHeight) / upem;
1359 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001360 if (os2->version != 0xFFFF && os2->version >= 2) {
1361 cap_height = scaleX * SkIntToScalar(os2->sCapHeight) / upem;
1362 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001363 }
1364
1365 // pull from format-specific metrics as needed
1366 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001367 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001368 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
1369 ascent = -SkIntToScalar(face->ascender) / upem;
1370 descent = -SkIntToScalar(face->descender) / upem;
1371 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1372 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1373 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1374 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1375 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001376 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001377 underlinePosition = -SkIntToScalar(face->underline_position +
1378 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001379
bungeman41078062014-07-07 08:16:37 -07001380 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1381 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1382
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001383 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001384 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001385 FT_BBox bbox;
1386 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001387 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1388 }
1389 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001390 if (!cap_height) {
1391 FT_BBox bbox;
1392 if (getCBoxForLetter('H', &bbox)) {
1393 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1394 }
1395 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001396 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1397 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1398 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1399 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1400 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1401 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f))
1402 + ascent - descent;
1403 xmin = 0.0f;
1404 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1405 ymin = descent + leading;
1406 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001407 underlineThickness = 0;
1408 underlinePosition = 0;
1409
bungeman41078062014-07-07 08:16:37 -07001410 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1411 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001412 } else {
1413 goto ERROR;
1414 }
1415
1416 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1417 if (!x_height) {
1418 x_height = -ascent;
1419 }
1420 if (!avgCharWidth) {
1421 avgCharWidth = xmax - xmin;
1422 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001423 if (!cap_height) {
1424 cap_height = -ascent;
1425 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001426
1427 // disallow negative linespacing
1428 if (leading < 0.0f) {
1429 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001430 }
1431
bungeman41078062014-07-07 08:16:37 -07001432 SkScalar scale = myy;
1433 if (this->isVertical()) {
1434 scale = mxy;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001435 }
bungeman41078062014-07-07 08:16:37 -07001436 metrics->fTop = ymax * scale;
1437 metrics->fAscent = ascent * scale;
1438 metrics->fDescent = descent * scale;
1439 metrics->fBottom = ymin * scale;
1440 metrics->fLeading = leading * scale;
1441 metrics->fAvgCharWidth = avgCharWidth * scale;
reedc17c6582014-10-31 08:20:46 -07001442 metrics->fXMin = xmin * scale;
1443 metrics->fXMax = xmax * scale;
bungeman7316b102014-10-29 12:46:52 -07001444 metrics->fXHeight = x_height;
1445 metrics->fCapHeight = cap_height;
bungeman41078062014-07-07 08:16:37 -07001446 metrics->fUnderlineThickness = underlineThickness * scale;
1447 metrics->fUnderlinePosition = underlinePosition * scale;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001448}
1449
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001450void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1451{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001452 // check to see if the embolden bit is set
1453 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1454 return;
1455 }
1456
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001457 switch (glyph->format) {
1458 case FT_GLYPH_FORMAT_OUTLINE:
1459 FT_Pos strength;
1460 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale) / 24;
1461 FT_Outline_Embolden(&glyph->outline, strength);
1462 break;
1463 case FT_GLYPH_FORMAT_BITMAP:
1464 FT_GlyphSlot_Own_Bitmap(glyph);
1465 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1466 break;
1467 default:
1468 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001469 }
1470}
1471
reed@google.comb4162b12013-07-02 16:32:29 +00001472///////////////////////////////////////////////////////////////////////////////
1473
1474#include "SkUtils.h"
1475
1476static SkUnichar next_utf8(const void** chars) {
1477 return SkUTF8_NextUnichar((const char**)chars);
1478}
1479
1480static SkUnichar next_utf16(const void** chars) {
1481 return SkUTF16_NextUnichar((const uint16_t**)chars);
1482}
1483
1484static SkUnichar next_utf32(const void** chars) {
1485 const SkUnichar** uniChars = (const SkUnichar**)chars;
1486 SkUnichar uni = **uniChars;
1487 *uniChars += 1;
1488 return uni;
1489}
1490
1491typedef SkUnichar (*EncodingProc)(const void**);
1492
1493static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1494 static const EncodingProc gProcs[] = {
1495 next_utf8, next_utf16, next_utf32
1496 };
1497 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1498 return gProcs[enc];
1499}
1500
1501int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1502 uint16_t glyphs[], int glyphCount) const {
1503 AutoFTAccess fta(this);
1504 FT_Face face = fta.face();
1505 if (!face) {
1506 if (glyphs) {
1507 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1508 }
1509 return 0;
1510 }
1511
1512 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1513
1514 if (NULL == glyphs) {
1515 for (int i = 0; i < glyphCount; ++i) {
1516 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1517 return i;
1518 }
1519 }
1520 return glyphCount;
1521 } else {
1522 int first = glyphCount;
1523 for (int i = 0; i < glyphCount; ++i) {
1524 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1525 glyphs[i] = SkToU16(id);
1526 if (0 == id && i < first) {
1527 first = i;
1528 }
1529 }
1530 return first;
1531 }
1532}
1533
1534int SkTypeface_FreeType::onCountGlyphs() const {
1535 // we cache this value, using -1 as a sentinel for "not computed"
1536 if (fGlyphCount < 0) {
1537 AutoFTAccess fta(this);
1538 FT_Face face = fta.face();
1539 // if the face failed, we still assign a non-negative value
1540 fGlyphCount = face ? face->num_glyphs : 0;
1541 }
1542 return fGlyphCount;
1543}
1544
bungeman@google.com839702b2013-08-07 17:09:22 +00001545SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001546 SkTypeface::LocalizedStrings* nameIter =
1547 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1548 if (NULL == nameIter) {
1549 SkString familyName;
1550 this->getFamilyName(&familyName);
1551 SkString language("und"); //undetermined
1552 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1553 }
1554 return nameIter;
1555}
1556
bungeman@google.comddc218e2013-08-01 22:29:43 +00001557int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1558 AutoFTAccess fta(this);
1559 FT_Face face = fta.face();
1560
1561 FT_ULong tableCount = 0;
1562 FT_Error error;
1563
1564 // When 'tag' is NULL, returns number of tables in 'length'.
1565 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1566 if (error) {
1567 return 0;
1568 }
1569
1570 if (tags) {
1571 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1572 FT_ULong tableTag;
1573 FT_ULong tablelength;
1574 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1575 if (error) {
1576 return 0;
1577 }
1578 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1579 }
1580 }
1581 return tableCount;
1582}
1583
1584size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1585 size_t length, void* data) const
1586{
1587 AutoFTAccess fta(this);
1588 FT_Face face = fta.face();
1589
1590 FT_ULong tableLength = 0;
1591 FT_Error error;
1592
1593 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1594 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1595 if (error) {
1596 return 0;
1597 }
1598
1599 if (offset > tableLength) {
1600 return 0;
1601 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001602 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001603 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001604 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1605 if (error) {
1606 return 0;
1607 }
1608 }
1609
1610 return size;
1611}
1612
reed@google.comb4162b12013-07-02 16:32:29 +00001613///////////////////////////////////////////////////////////////////////////////
1614///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001615
bungeman9dc24682014-12-01 14:01:32 -08001616SkTypeface_FreeType::Scanner::Scanner() : fLibrary(NULL) {
1617 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1618 return;
bungeman14df8332014-10-28 15:07:23 -07001619 }
bungeman9dc24682014-12-01 14:01:32 -08001620 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001621}
1622SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001623 if (fLibrary) {
1624 FT_Done_Library(fLibrary);
1625 }
bungeman14df8332014-10-28 15:07:23 -07001626}
1627
1628FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1629 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001630{
bungeman14df8332014-10-28 15:07:23 -07001631 if (fLibrary == NULL) {
1632 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001633 }
1634
bungeman14df8332014-10-28 15:07:23 -07001635 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001636 memset(&args, 0, sizeof(args));
1637
1638 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001639
bsalomon49f085d2014-09-05 13:34:00 -07001640 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001641 args.flags = FT_OPEN_MEMORY;
1642 args.memory_base = (const FT_Byte*)memoryBase;
1643 args.memory_size = stream->getLength();
1644 } else {
bungeman14df8332014-10-28 15:07:23 -07001645 memset(ftStream, 0, sizeof(*ftStream));
1646 ftStream->size = stream->getLength();
1647 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001648 ftStream->read = sk_ft_stream_io;
1649 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001650
1651 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001652 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001653 }
1654
1655 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001656 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
1657 return NULL;
1658 }
1659 return face;
1660}
1661
1662bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1663 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1664
1665 FT_StreamRec streamRec;
1666 FT_Face face = this->openFace(stream, -1, &streamRec);
1667 if (NULL == face) {
1668 return false;
1669 }
1670
1671 *numFaces = face->num_faces;
1672
1673 FT_Done_Face(face);
1674 return true;
1675}
1676
1677#include "SkTSearch.h"
1678bool SkTypeface_FreeType::Scanner::scanFont(
1679 SkStream* stream, int ttcIndex, SkString* name, SkFontStyle* style, bool* isFixedPitch) const
1680{
1681 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1682
1683 FT_StreamRec streamRec;
1684 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
1685 if (NULL == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001686 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001687 }
1688
bungemana4c4a2d2014-10-20 13:33:19 -07001689 int weight = SkFontStyle::kNormal_Weight;
1690 int width = SkFontStyle::kNormal_Width;
1691 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001692 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001693 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001694 }
1695 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001696 slant = SkFontStyle::kItalic_Slant;
1697 }
1698
1699 PS_FontInfoRec psFontInfo;
1700 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1701 if (os2 && os2->version != 0xffff) {
1702 weight = os2->usWeightClass;
1703 width = os2->usWidthClass;
1704 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1705 static const struct {
1706 char const * const name;
1707 int const weight;
1708 } commonWeights [] = {
1709 // There are probably more common names, but these are known to exist.
1710 { "black", SkFontStyle::kBlack_Weight },
1711 { "bold", SkFontStyle::kBold_Weight },
1712 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1713 { "demi", SkFontStyle::kSemiBold_Weight },
1714 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001715 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001716 { "extrabold", SkFontStyle::kExtraBold_Weight },
1717 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001718 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001719 { "heavy", SkFontStyle::kBlack_Weight },
1720 { "light", SkFontStyle::kLight_Weight },
1721 { "medium", SkFontStyle::kMedium_Weight },
1722 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001723 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001724 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001725 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001726 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001727 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001728 { "thin", SkFontStyle::kThin_Weight },
1729 { "ultra", SkFontStyle::kExtraBold_Weight },
1730 { "ultrablack", 1000 },
1731 { "ultrabold", SkFontStyle::kExtraBold_Weight },
1732 { "ultraheavy", 1000 },
1733 { "ultralight", SkFontStyle::kExtraLight_Weight },
1734 };
1735 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001736 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001737 if (index >= 0) {
1738 weight = commonWeights[index].weight;
1739 } else {
bungeman14df8332014-10-28 15:07:23 -07001740 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001741 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001742 }
1743
1744 if (name) {
1745 name->set(face->family_name);
1746 }
1747 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001748 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001749 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001750 if (isFixedPitch) {
1751 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001752 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001753
1754 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001755 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001756}