blob: 63f598fd13d0df6a1604d0d74c7150540baad377 [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"
bungemand3ebb482015-08-05 13:57:49 -070022#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000023#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000024#include "SkStream.h"
25#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000026#include "SkTemplates.h"
bungeman9dc24682014-12-01 14:01:32 -080027#include "SkTypes.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000028
bungeman@google.comfd668cf2012-08-24 17:46:11 +000029#if defined(SK_CAN_USE_DLOPEN)
30#include <dlfcn.h>
31#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000032#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080033#include FT_ADVANCES_H
34#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000035#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080036#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080037#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070038#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000039#include FT_OUTLINE_H
40#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080041#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000042#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000043#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000044#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000045
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000046// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
47// were introduced in FreeType 2.5.0.
48// The following may be removed once FreeType 2.5.0 is required to build.
49#ifndef FT_LOAD_COLOR
50# define FT_LOAD_COLOR ( 1L << 20 )
51# define FT_PIXEL_MODE_BGRA 7
52#endif
53
reed@android.com8a1c16f2008-12-17 15:59:43 +000054//#define ENABLE_GLYPH_SPEW // for tracing calls
55//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080056//#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
57//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000058//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000059
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000060using namespace skia_advanced_typeface_metrics_utils;
61
reed@google.comeffc5012011-06-27 16:44:46 +000062static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080063 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000064}
65
reed@android.com8a1c16f2008-12-17 15:59:43 +000066//////////////////////////////////////////////////////////////////////////
67
bungeman9dc24682014-12-01 14:01:32 -080068extern "C" {
69 static void* sk_ft_alloc(FT_Memory, long size) {
70 return sk_malloc_throw(size);
71 }
72 static void sk_ft_free(FT_Memory, void* block) {
73 sk_free(block);
74 }
75 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
76 return sk_realloc_throw(block, new_size);
77 }
78};
79FT_MemoryRec_ gFTMemory = { NULL, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
80
81class FreeTypeLibrary : SkNoncopyable {
82public:
83 FreeTypeLibrary() : fLibrary(NULL), fIsLCDSupported(false), fLCDExtra(0) {
84 if (FT_New_Library(&gFTMemory, &fLibrary)) {
85 return;
86 }
87 FT_Add_Default_Modules(fLibrary);
88
89 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
90 // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
91 // SetLcdFilter must be called before SetLcdFilterWeights.
92 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
93 fIsLCDSupported = true;
94 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
95
96#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
97 // Adds to 0x110 simulating ink spread, but provides better results than default.
98 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
99
100# if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
101 FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
102# elif SK_CAN_USE_DLOPEN == 1
103 //The FreeType library is already loaded, so symbols are available in process.
104 void* self = dlopen(NULL, RTLD_LAZY);
105 if (self) {
106 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
107 //The following cast is non-standard, but safe for POSIX.
108 *reinterpret_cast<void**>(&setLcdFilterWeights) =
109 dlsym(self, "FT_Library_SetLcdFilterWeights");
110 dlclose(self);
111
112 if (setLcdFilterWeights) {
113 setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
114 }
115 }
116# endif
117#endif
118 }
119 }
120 ~FreeTypeLibrary() {
121 if (fLibrary) {
122 FT_Done_Library(fLibrary);
123 }
124 }
125
126 FT_Library library() { return fLibrary; }
127 bool isLCDSupported() { return fIsLCDSupported; }
128 int lcdExtra() { return fLCDExtra; }
129
130private:
131 FT_Library fLibrary;
132 bool fIsLCDSupported;
133 int fLCDExtra;
134
135 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
136 // The following platforms provide FreeType of at least 2.4.0.
137 // Ubuntu >= 11.04 (previous deprecated April 2013)
138 // Debian >= 6.0 (good)
139 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
140 // Fedora >= 14 (good)
141 // Android >= Gingerbread (good)
142 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
143};
144
reed@android.com8a1c16f2008-12-17 15:59:43 +0000145struct SkFaceRec;
146
digit@google.com1771cbf2012-01-26 21:26:40 +0000147SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800148static FreeTypeLibrary* gFTLibrary;
149static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000150
bungeman9dc24682014-12-01 14:01:32 -0800151// Private to RefFreeType and UnrefFreeType
152static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000153
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000154// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800155static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800156 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800157 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800158
bungeman9dc24682014-12-01 14:01:32 -0800159 if (0 == gFTCount) {
160 SkASSERT(NULL == gFTLibrary);
161 gFTLibrary = SkNEW(FreeTypeLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000162 }
bungeman9dc24682014-12-01 14:01:32 -0800163 ++gFTCount;
164 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000165}
166
bungeman9dc24682014-12-01 14:01:32 -0800167// Caller must lock gFTMutex before calling this function.
168static void unref_ft_library() {
169 gFTMutex.assertHeld();
170 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000171
bungeman9dc24682014-12-01 14:01:32 -0800172 --gFTCount;
173 if (0 == gFTCount) {
174 SkASSERT(NULL != gFTLibrary);
175 SkDELETE(gFTLibrary);
176 SkDEBUGCODE(gFTLibrary = NULL;)
177 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000178}
179
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000180class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000181public:
reed@google.com0da48612013-03-19 16:06:52 +0000182 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000183 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000184
reed@android.com62900b42009-02-11 15:07:19 +0000185 bool success() const {
bungeman13a007d2015-06-19 05:09:39 -0700186 return fFTSize != NULL && fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000187 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000188
189protected:
mtklein36352bf2015-03-25 18:17:31 -0700190 unsigned generateGlyphCount() override;
191 uint16_t generateCharToGlyph(SkUnichar uni) override;
192 void generateAdvance(SkGlyph* glyph) override;
193 void generateMetrics(SkGlyph* glyph) override;
194 void generateImage(const SkGlyph& glyph) override;
195 void generatePath(const SkGlyph& glyph, SkPath* path) override;
196 void generateFontMetrics(SkPaint::FontMetrics*) override;
197 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000198
199private:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000200 FT_Face fFace; // reference to shared face in gFaceRecHead
201 FT_Size fFTSize; // our own copy
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000202 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000203 SkFixed fScaleX, fScaleY;
204 FT_Matrix fMatrix22;
205 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000206 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000207 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000208
reed@google.comf073b332013-05-06 12:21:16 +0000209 // Need scalar versions for generateFontMetrics
210 SkVector fScale;
211 SkMatrix fMatrix22Scalar;
212
reed@android.com8a1c16f2008-12-17 15:59:43 +0000213 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000214 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
215 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000216 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000217 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000218 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000219 // Caller must lock gFTMutex before calling this function.
220 // update FreeType2 glyph slot with glyph emboldened
221 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000222};
223
224///////////////////////////////////////////////////////////////////////////
225///////////////////////////////////////////////////////////////////////////
226
reed@android.com8a1c16f2008-12-17 15:59:43 +0000227struct SkFaceRec {
bungeman52b64b42015-01-27 10:41:17 -0800228 SkFaceRec* fNext;
229 FT_Face fFace;
230 FT_StreamRec fFTStream;
231 SkAutoTDelete<SkStreamAsset> fSkStream;
232 uint32_t fRefCnt;
233 uint32_t fFontID;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000234
scroggoa1193e42015-01-21 12:09:53 -0800235 // assumes ownership of the stream, will delete when its done
bungeman52b64b42015-01-27 10:41:17 -0800236 SkFaceRec(SkStreamAsset* strm, uint32_t fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000237};
238
239extern "C" {
bungeman52b64b42015-01-27 10:41:17 -0800240 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
bungeman9dc24682014-12-01 14:01:32 -0800241 unsigned long offset,
242 unsigned char* buffer,
243 unsigned long count)
244 {
bungeman52b64b42015-01-27 10:41:17 -0800245 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000246
247 if (count) {
bungeman52b64b42015-01-27 10:41:17 -0800248 if (!stream->seek(offset)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000249 return 0;
bungeman9dc24682014-12-01 14:01:32 -0800250 }
bungeman52b64b42015-01-27 10:41:17 -0800251 count = stream->read(buffer, count);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000252 }
253 return count;
254 }
255
bungeman9dc24682014-12-01 14:01:32 -0800256 static void sk_ft_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000257}
258
bungeman52b64b42015-01-27 10:41:17 -0800259SkFaceRec::SkFaceRec(SkStreamAsset* stream, uint32_t fontID)
260 : fNext(NULL), fSkStream(stream), fRefCnt(1), fFontID(fontID)
261{
reed@android.com4516f472009-06-29 16:25:36 +0000262 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000263 fFTStream.size = fSkStream->getLength();
264 fFTStream.descriptor.pointer = fSkStream;
bungeman9dc24682014-12-01 14:01:32 -0800265 fFTStream.read = sk_ft_stream_io;
266 fFTStream.close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000267}
268
bungeman41868fe2015-05-20 09:21:04 -0700269static void ft_face_setup_axes(FT_Face face, const SkFontData& data) {
270 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
271 return;
272 }
273
274 SkDEBUGCODE(
275 FT_MM_Var* variations = NULL;
276 if (FT_Get_MM_Var(face, &variations)) {
277 SkDEBUGF(("INFO: font %s claims variations, but none found.\n", face->family_name));
278 return;
279 }
280 SkAutoFree autoFreeVariations(variations);
281
282 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
283 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
284 face->family_name, variations->num_axis, data.getAxisCount()));
285 return;
286 }
287 )
288
289 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
290 for (int i = 0; i < data.getAxisCount(); ++i) {
291 coords[i] = data.getAxis()[i];
292 }
293 if (FT_Set_Var_Design_Coordinates(face, data.getAxisCount(), coords.get())) {
294 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
295 face->family_name));
296 return;
297 }
298}
bungeman41868fe2015-05-20 09:21:04 -0700299
reed@android.com62900b42009-02-11 15:07:19 +0000300// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000301// Caller must lock gFTMutex before calling this function.
bungeman13a007d2015-06-19 05:09:39 -0700302static FT_Face ref_ft_face(const SkTypeface* typeface) {
bungeman5ec443c2014-11-21 13:18:34 -0800303 gFTMutex.assertHeld();
304
reed@google.com2cdc6712013-03-21 18:22:00 +0000305 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306 SkFaceRec* rec = gFaceRecHead;
307 while (rec) {
308 if (rec->fFontID == fontID) {
309 SkASSERT(rec->fFace);
310 rec->fRefCnt += 1;
bungeman13a007d2015-06-19 05:09:39 -0700311 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000312 }
313 rec = rec->fNext;
314 }
315
bungeman41868fe2015-05-20 09:21:04 -0700316 SkAutoTDelete<SkFontData> data(typeface->createFontData());
317 if (NULL == data || !data->hasStream()) {
reed@google.com2cdc6712013-03-21 18:22:00 +0000318 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000319 }
320
bungeman52b64b42015-01-27 10:41:17 -0800321 // this passes ownership of stream to the rec
bungeman41868fe2015-05-20 09:21:04 -0700322 rec = SkNEW_ARGS(SkFaceRec, (data->detachStream(), fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000323
bungeman9dc24682014-12-01 14:01:32 -0800324 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000325 memset(&args, 0, sizeof(args));
bungeman41868fe2015-05-20 09:21:04 -0700326 const void* memoryBase = rec->fSkStream->getMemoryBase();
bsalomon49f085d2014-09-05 13:34:00 -0700327 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000328 args.flags = FT_OPEN_MEMORY;
329 args.memory_base = (const FT_Byte*)memoryBase;
bungeman41868fe2015-05-20 09:21:04 -0700330 args.memory_size = rec->fSkStream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000331 } else {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000332 args.flags = FT_OPEN_STREAM;
333 args.stream = &rec->fFTStream;
334 }
335
bungeman41868fe2015-05-20 09:21:04 -0700336 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rec->fFace);
337 if (err) {
bungeman5ec443c2014-11-21 13:18:34 -0800338 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000339 SkDELETE(rec);
reed@google.com2cdc6712013-03-21 18:22:00 +0000340 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000341 }
bungeman9dc24682014-12-01 14:01:32 -0800342 SkASSERT(rec->fFace);
bungeman41868fe2015-05-20 09:21:04 -0700343
bungeman41868fe2015-05-20 09:21:04 -0700344 ft_face_setup_axes(rec->fFace, *data);
bungeman41868fe2015-05-20 09:21:04 -0700345
bungeman726cf902015-06-05 13:38:12 -0700346 // FreeType will set the charmap to the "most unicode" cmap if it exists.
347 // If there are no unicode cmaps, the charmap is set to NULL.
348 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
349 // because they are effectively private use area only (even if they aren't).
350 // This is the last on the fallback list at
351 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
352 if (!rec->fFace->charmap) {
353 FT_Select_Charmap(rec->fFace, FT_ENCODING_MS_SYMBOL);
354 }
355
bungeman9dc24682014-12-01 14:01:32 -0800356 rec->fNext = gFaceRecHead;
357 gFaceRecHead = rec;
bungeman13a007d2015-06-19 05:09:39 -0700358 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000359}
360
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000361// Caller must lock gFTMutex before calling this function.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000362static void unref_ft_face(FT_Face face) {
bungeman5ec443c2014-11-21 13:18:34 -0800363 gFTMutex.assertHeld();
364
reed@android.com8a1c16f2008-12-17 15:59:43 +0000365 SkFaceRec* rec = gFaceRecHead;
366 SkFaceRec* prev = NULL;
367 while (rec) {
368 SkFaceRec* next = rec->fNext;
369 if (rec->fFace == face) {
370 if (--rec->fRefCnt == 0) {
371 if (prev) {
372 prev->fNext = next;
373 } else {
374 gFaceRecHead = next;
375 }
376 FT_Done_Face(face);
377 SkDELETE(rec);
378 }
379 return;
380 }
381 prev = rec;
382 rec = next;
383 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000384 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000385}
386
reed@google.comb4162b12013-07-02 16:32:29 +0000387class AutoFTAccess {
388public:
bungeman13a007d2015-06-19 05:09:39 -0700389 AutoFTAccess(const SkTypeface* tf) : fFace(NULL) {
reed@google.comb4162b12013-07-02 16:32:29 +0000390 gFTMutex.acquire();
bungeman9dc24682014-12-01 14:01:32 -0800391 if (!ref_ft_library()) {
392 sk_throw();
reed@google.comb4162b12013-07-02 16:32:29 +0000393 }
bungeman13a007d2015-06-19 05:09:39 -0700394 fFace = ref_ft_face(tf);
reed@google.comb4162b12013-07-02 16:32:29 +0000395 }
396
397 ~AutoFTAccess() {
398 if (fFace) {
399 unref_ft_face(fFace);
400 }
bungeman9dc24682014-12-01 14:01:32 -0800401 unref_ft_library();
reed@google.comb4162b12013-07-02 16:32:29 +0000402 gFTMutex.release();
403 }
404
reed@google.comb4162b12013-07-02 16:32:29 +0000405 FT_Face face() { return fFace; }
406
407private:
reed@google.comb4162b12013-07-02 16:32:29 +0000408 FT_Face fFace;
409};
410
reed@android.com8a1c16f2008-12-17 15:59:43 +0000411///////////////////////////////////////////////////////////////////////////
412
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000413static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000414 FT_UShort fsType = FT_Get_FSType_Flags(face);
415 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
416 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000417}
418
vandebo0f9bad02014-06-19 11:05:39 -0700419static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700420 FT_UShort fsType = FT_Get_FSType_Flags(face);
421 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700422}
423
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000424static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
425 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
426 if (!glyph_id)
427 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000428 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
429 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000430 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
431 return true;
432}
433
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000434static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000435 FT_Fixed advance = 0;
bungeman5ec443c2014-11-21 13:18:34 -0800436 if (FT_Get_Advances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000437 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000438 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000439 SkASSERT(data);
440 *data = advance;
441 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000442}
443
bungeman5ec443c2014-11-21 13:18:34 -0800444static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
bungeman726cf902015-06-05 13:38:12 -0700445 glyphToUnicode->setCount(face->num_glyphs);
446 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * face->num_glyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000447
bungeman726cf902015-06-05 13:38:12 -0700448 FT_UInt glyphIndex;
449 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
450 while (glyphIndex) {
451 (*glyphToUnicode)[glyphIndex] = charCode;
452 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000453 }
454}
455
reed@google.com2689f612013-03-20 20:01:47 +0000456SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700457 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000458 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000459 uint32_t glyphIDsCount) const {
djsollen@google.comda957722011-11-16 17:00:46 +0000460#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000461 return NULL;
462#else
reed@google.comb4162b12013-07-02 16:32:29 +0000463 AutoFTAccess fta(this);
464 FT_Face face = fta.face();
465 if (!face) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000466 return NULL;
reed@google.comb4162b12013-07-02 16:32:29 +0000467 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000468
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000469 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
470 info->fFontName.set(FT_Get_Postscript_Name(face));
vandebo0f9bad02014-06-19 11:05:39 -0700471 info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag;
472 if (FT_HAS_MULTIPLE_MASTERS(face)) {
473 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
474 info->fFlags, SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag);
475 }
476 if (!canEmbed(face)) {
477 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
478 info->fFlags,
479 SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag);
480 }
481 if (!canSubset(face)) {
482 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
483 info->fFlags,
484 SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag);
485 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000486 info->fLastGlyphID = face->num_glyphs - 1;
487 info->fEmSize = 1000;
488
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000489 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000490 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000491 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000492 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000493 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000494 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000495 cid = true;
496 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000497 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000498 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000499 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000500 cid = true;
501 TT_Header* ttHeader;
502 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
503 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000504 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000505 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000506 } else {
507 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000508 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000509
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000510 info->fStyle = 0;
511 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000512 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000513 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000514 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000515
516 PS_FontInfoRec ps_info;
517 TT_Postscript* tt_info;
518 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
519 info->fItalicAngle = ps_info.italic_angle;
520 } else if ((tt_info =
521 (TT_Postscript*)FT_Get_Sfnt_Table(face,
522 ft_sfnt_post)) != NULL) {
523 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
524 } else {
525 info->fItalicAngle = 0;
526 }
527
528 info->fAscent = face->ascender;
529 info->fDescent = face->descender;
530
531 // Figure out a good guess for StemV - Min width of i, I, !, 1.
532 // This probably isn't very good with an italic font.
533 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000534 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000535 char stem_chars[] = {'i', 'I', '!', '1'};
536 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
537 FT_BBox bbox;
538 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
539 int16_t width = bbox.xMax - bbox.xMin;
540 if (width > 0 && width < min_width) {
541 min_width = width;
542 info->fStemV = min_width;
543 }
544 }
545 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000546
547 TT_PCLT* pclt_info;
548 TT_OS2* os2_table;
549 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
550 info->fCapHeight = pclt_info->CapHeight;
551 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
552 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000553 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000554 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000555 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000556 } else if (((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) &&
557 // sCapHeight is available only when version 2 or later.
558 os2_table->version != 0xFFFF &&
559 os2_table->version >= 2) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000560 info->fCapHeight = os2_table->sCapHeight;
561 } else {
562 // Figure out a good guess for CapHeight: average the height of M and X.
563 FT_BBox m_bbox, x_bbox;
564 bool got_m, got_x;
565 got_m = GetLetterCBox(face, 'M', &m_bbox);
566 got_x = GetLetterCBox(face, 'X', &x_bbox);
567 if (got_m && got_x) {
568 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
569 x_bbox.yMin) / 2;
570 } else if (got_m && !got_x) {
571 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
572 } else if (!got_m && got_x) {
573 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000574 } else {
575 // Last resort, use the ascent.
576 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000577 }
578 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000579
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000580 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
581 face->bbox.xMax, face->bbox.yMin);
582
vandebo0f9bad02014-06-19 11:05:39 -0700583 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700584 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000585 }
586
reed39a9a502015-05-12 09:50:04 -0700587 if (perGlyphInfo & kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000588 if (FT_IS_FIXED_WIDTH(face)) {
589 appendRange(&info->fGlyphWidths, 0);
590 int16_t advance = face->max_advance_width;
591 info->fGlyphWidths->fAdvance.append(1, &advance);
592 finishRange(info->fGlyphWidths.get(), 0,
593 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000594 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000595 appendRange(&info->fGlyphWidths, 0);
596 // So as to not blow out the stack, get advances in batches.
597 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
598 FT_Fixed advances[128];
599 int advanceCount = 128;
bungeman5ec443c2014-11-21 13:18:34 -0800600 if (gID + advanceCount > face->num_glyphs) {
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000601 advanceCount = face->num_glyphs - gID;
bungeman5ec443c2014-11-21 13:18:34 -0800602 }
603 FT_Get_Advances(face, gID, advanceCount, FT_LOAD_NO_SCALE, advances);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000604 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000605 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000606 info->fGlyphWidths->fAdvance.append(1, &advance);
607 }
608 }
609 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
610 SkAdvancedTypefaceMetrics::WidthRange::kRange);
611 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000612 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000613 getAdvanceData(face,
614 face->num_glyphs,
615 glyphIDs,
616 glyphIDsCount,
617 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000618 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000619 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000620
reed39a9a502015-05-12 09:50:04 -0700621 if (perGlyphInfo & kVAdvance_PerGlyphInfo &&
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000622 FT_HAS_VERTICAL(face)) {
623 SkASSERT(false); // Not implemented yet.
624 }
625
reed39a9a502015-05-12 09:50:04 -0700626 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000627 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
628 // Postscript fonts may contain more than 255 glyphs, so we end up
629 // using multiple font descriptions with a glyph ordering. Record
630 // the name of each glyph.
631 info->fGlyphNames.reset(
632 new SkAutoTArray<SkString>(face->num_glyphs));
633 for (int gID = 0; gID < face->num_glyphs; gID++) {
634 char glyphName[128]; // PS limit for names is 127 bytes.
635 FT_Get_Glyph_Name(face, gID, glyphName, 128);
636 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000637 }
638 }
639
reed39a9a502015-05-12 09:50:04 -0700640 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000641 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
642 face->num_charmaps) {
643 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
644 }
645
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000646 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000647#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000648}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000649
reed@google.com618ef5e2011-01-26 22:10:41 +0000650///////////////////////////////////////////////////////////////////////////
651
reed@google.com8ed436c2011-07-21 14:12:36 +0000652static bool bothZero(SkScalar a, SkScalar b) {
653 return 0 == a && 0 == b;
654}
655
656// returns false if there is any non-90-rotation or skew
657static bool isAxisAligned(const SkScalerContext::Rec& rec) {
658 return 0 == rec.fPreSkewX &&
659 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
660 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
661}
662
reed@google.com0da48612013-03-19 16:06:52 +0000663SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
664 const SkDescriptor* desc) const {
665 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
666 (const_cast<SkTypeface_FreeType*>(this),
667 desc));
668 if (!c->success()) {
669 SkDELETE(c);
670 c = NULL;
671 }
672 return c;
673}
674
675void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000676 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
677 //Cap the requested size as larger sizes give bogus values.
678 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000679 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000680 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000681 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000682
bungemanec7e12f2015-01-21 11:55:16 -0800683 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800684 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
685 SkAutoMutexAcquire ama(gFTMutex);
686 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800687 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800688 // If the runtime Freetype library doesn't support LCD, disable it here.
689 rec->fMaskFormat = SkMask::kA8_Format;
690 }
691 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000692 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000693
reed@google.com618ef5e2011-01-26 22:10:41 +0000694 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000695 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000696 // collapse full->normal hinting if we're not doing LCD
697 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000698 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000699 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000700 if (SkPaint::kNo_Hinting != h) {
701 h = SkPaint::kSlight_Hinting;
702 }
703 }
704
reed@google.com8ed436c2011-07-21 14:12:36 +0000705 // rotated text looks bad with hinting, so we disable it as needed
706 if (!isAxisAligned(*rec)) {
707 h = SkPaint::kNo_Hinting;
708 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000709 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000710
bungeman@google.com97efada2012-07-30 20:40:50 +0000711#ifndef SK_GAMMA_APPLY_TO_A8
712 if (!isLCD(*rec)) {
713 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000714 }
reed@google.com1ac83502012-02-28 17:06:02 +0000715#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000716}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000717
reed@google.com38c37dd2013-03-21 15:36:26 +0000718int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000719 AutoFTAccess fta(this);
720 FT_Face face = fta.face();
721 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000722}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000723
reed@google.com35fe7372013-10-30 15:07:03 +0000724bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
725 int count, int32_t adjustments[]) const {
726 AutoFTAccess fta(this);
727 FT_Face face = fta.face();
728 if (!face || !FT_HAS_KERNING(face)) {
729 return false;
730 }
731
732 for (int i = 0; i < count - 1; ++i) {
733 FT_Vector delta;
734 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
735 FT_KERNING_UNSCALED, &delta);
736 if (err) {
737 return false;
738 }
739 adjustments[i] = delta.x;
740 }
741 return true;
742}
743
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000744static FT_Int chooseBitmapStrike(FT_Face face, SkFixed scaleY) {
745 // early out if face is bad
746 if (face == NULL) {
747 SkDEBUGF(("chooseBitmapStrike aborted due to NULL face\n"));
748 return -1;
749 }
750 // determine target ppem
751 FT_Pos targetPPEM = SkFixedToFDot6(scaleY);
752 // find a bitmap strike equal to or just larger than the requested size
753 FT_Int chosenStrikeIndex = -1;
754 FT_Pos chosenPPEM = 0;
755 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
756 FT_Pos thisPPEM = face->available_sizes[strikeIndex].y_ppem;
757 if (thisPPEM == targetPPEM) {
758 // exact match - our search stops here
759 chosenPPEM = thisPPEM;
760 chosenStrikeIndex = strikeIndex;
761 break;
762 } else if (chosenPPEM < targetPPEM) {
763 // attempt to increase chosenPPEM
764 if (thisPPEM > chosenPPEM) {
765 chosenPPEM = thisPPEM;
766 chosenStrikeIndex = strikeIndex;
767 }
768 } else {
769 // attempt to decrease chosenPPEM, but not below targetPPEM
770 if (thisPPEM < chosenPPEM && thisPPEM > targetPPEM) {
771 chosenPPEM = thisPPEM;
772 chosenStrikeIndex = strikeIndex;
773 }
774 }
775 }
776 if (chosenStrikeIndex != -1) {
777 // use the chosen strike
778 FT_Error err = FT_Select_Size(face, chosenStrikeIndex);
779 if (err != 0) {
780 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x\n", face->family_name,
781 chosenStrikeIndex, err));
782 chosenStrikeIndex = -1;
783 }
784 }
785 return chosenStrikeIndex;
786}
787
bungeman13a007d2015-06-19 05:09:39 -0700788SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface, const SkDescriptor* desc)
789 : SkScalerContext_FreeType_Base(typeface, desc)
790{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000791 SkAutoMutexAcquire ac(gFTMutex);
792
bungeman9dc24682014-12-01 14:01:32 -0800793 if (!ref_ft_library()) {
794 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000795 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000796
797 // load the font file
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000798 fStrikeIndex = -1;
reed@android.com62900b42009-02-11 15:07:19 +0000799 fFTSize = NULL;
bungeman13a007d2015-06-19 05:09:39 -0700800 fFace = ref_ft_face(typeface);
801 if (NULL == fFace) {
reed@android.com62900b42009-02-11 15:07:19 +0000802 return;
803 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000804
bungeman5f14c5e2014-12-05 12:26:44 -0800805 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
806 fMatrix22Scalar.setSkewX(-fMatrix22Scalar.getSkewX());
807 fMatrix22Scalar.setSkewY(-fMatrix22Scalar.getSkewY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000808
bungeman5f14c5e2014-12-05 12:26:44 -0800809 fScaleX = SkScalarToFixed(fScale.fX);
810 fScaleY = SkScalarToFixed(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000811 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
812 fMatrix22.xy = SkScalarToFixed(fMatrix22Scalar.getSkewX());
813 fMatrix22.yx = SkScalarToFixed(fMatrix22Scalar.getSkewY());
814 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000815
reed@google.coma1bfa212012-03-08 21:57:12 +0000816 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
817
reed@android.com8a1c16f2008-12-17 15:59:43 +0000818 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000819 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000821 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822
agl@chromium.org70a303f2010-05-10 14:15:50 +0000823 if (SkMask::kBW_Format == fRec.fMaskFormat) {
824 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
825 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000826 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000827 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000828 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000829 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000830 } else {
831 switch (fRec.getHinting()) {
832 case SkPaint::kNo_Hinting:
833 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000834 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000835 break;
836 case SkPaint::kSlight_Hinting:
837 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
838 break;
839 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000840 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000841 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700842#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
843 } else {
844 loadFlags = FT_LOAD_NO_AUTOHINT;
845#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000846 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000847 break;
848 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000849 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000850 loadFlags = FT_LOAD_FORCE_AUTOHINT;
851 break;
852 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000853 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000854 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000855 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000856 loadFlags = FT_LOAD_TARGET_LCD_V;
857 } else {
858 loadFlags = FT_LOAD_TARGET_LCD;
859 }
reed@google.comea2333d2011-03-14 16:44:56 +0000860 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000861 break;
862 default:
863 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
864 break;
865 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000866 }
867
reed@google.comeffc5012011-06-27 16:44:46 +0000868 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000869 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000870 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000871
reed@google.com96a9f792011-05-06 11:49:30 +0000872 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
873 // advances, as fontconfig and cairo do.
874 // See http://code.google.com/p/skia/issues/detail?id=222.
875 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
876
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000877 // Use vertical layout if requested.
878 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
879 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
880 }
881
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000882 loadFlags |= FT_LOAD_COLOR;
883
reed@android.come4d0bc02009-07-24 19:53:20 +0000884 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000885 }
886
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000887 FT_Error err = FT_New_Size(fFace, &fFTSize);
888 if (err != 0) {
889 SkDEBUGF(("FT_New_Size returned %x for face %s\n", err, fFace->family_name));
890 fFace = NULL;
891 return;
892 }
893 err = FT_Activate_Size(fFTSize);
894 if (err != 0) {
895 SkDEBUGF(("FT_Activate_Size(%08x, 0x%x, 0x%x) returned 0x%x\n", fFace, fScaleX, fScaleY,
896 err));
897 fFTSize = NULL;
898 return;
899 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000900
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000901 if (FT_IS_SCALABLE(fFace)) {
902 err = FT_Set_Char_Size(fFace, SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000903 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000904 SkDEBUGF(("FT_Set_CharSize(%08x, 0x%x, 0x%x) returned 0x%x\n",
905 fFace, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000906 fFace = NULL;
907 return;
908 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000909 FT_Set_Transform(fFace, &fMatrix22, NULL);
910 } else if (FT_HAS_FIXED_SIZES(fFace)) {
911 fStrikeIndex = chooseBitmapStrike(fFace, fScaleY);
912 if (fStrikeIndex == -1) {
913 SkDEBUGF(("no glyphs for font \"%s\" size %f?\n",
914 fFace->family_name, SkFixedToScalar(fScaleY)));
915 } else {
916 // FreeType does no provide linear metrics for bitmap fonts.
917 linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000918
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000919 // FreeType documentation says:
920 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
921 // Bitmap-only fonts ignore this flag.
922 //
923 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
924 // Force this flag off for bitmap only fonts.
925 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000926 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000927 } else {
928 SkDEBUGF(("unknown kind of font \"%s\" size %f?\n",
929 fFace->family_name, SkFixedToScalar(fScaleY)));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000930 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000931
932 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000933}
934
935SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000936 SkAutoMutexAcquire ac(gFTMutex);
937
reed@android.com8a1c16f2008-12-17 15:59:43 +0000938 if (fFTSize != NULL) {
939 FT_Done_Size(fFTSize);
940 }
941
reed@android.com8a1c16f2008-12-17 15:59:43 +0000942 if (fFace != NULL) {
943 unref_ft_face(fFace);
944 }
bungeman9dc24682014-12-01 14:01:32 -0800945
946 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000947}
948
949/* We call this before each use of the fFace, since we may be sharing
950 this face with other context (at different sizes).
951*/
952FT_Error SkScalerContext_FreeType::setupSize() {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000953 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000954 if (err != 0) {
bungeman13a007d2015-06-19 05:09:39 -0700955 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%s %s, 0x%x, 0x%x) returned 0x%x\n",
956 fFace->family_name, fFace->style_name, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000957 fFTSize = NULL;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000958 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000959 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000960
961 // seems we need to reset this every time (not sure why, but without it
962 // I get random italics from some other fFTSize)
963 FT_Set_Transform(fFace, &fMatrix22, NULL);
964 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000965}
966
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000967unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000968 return fFace->num_glyphs;
969}
970
971uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
972 return SkToU16(FT_Get_Char_Index( fFace, uni ));
973}
974
reed@android.com9d3a9852010-01-08 14:07:42 +0000975SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
976 // iterate through each cmap entry, looking for matching glyph indices
977 FT_UInt glyphIndex;
978 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
979
980 while (glyphIndex != 0) {
981 if (glyphIndex == glyph) {
982 return charCode;
983 }
984 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
985 }
986
987 return 0;
988}
989
reed@android.com8a1c16f2008-12-17 15:59:43 +0000990void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000991 /* unhinted and light hinted text have linearly scaled advances
992 * which are very cheap to compute with some font formats...
993 */
reed@google.combdc99882011-11-21 14:36:57 +0000994 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000995 SkAutoMutexAcquire ac(gFTMutex);
996
997 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000998 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000999 return;
1000 }
1001
1002 FT_Error error;
1003 FT_Fixed advance;
1004
djsollen1b277042014-08-06 06:58:06 -07001005 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1007 &advance );
1008 if (0 == error) {
1009 glyph->fRsbDelta = 0;
1010 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +00001011 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1012 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 return;
1014 }
1015 }
bungeman5ec443c2014-11-21 13:18:34 -08001016
reed@android.com8a1c16f2008-12-17 15:59:43 +00001017 /* otherwise, we need to load/hint the glyph, which is slower */
1018 this->generateMetrics(glyph);
1019 return;
1020}
1021
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001022void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1023 FT_BBox* bbox,
1024 bool snapToPixelBoundary) {
1025
1026 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1027
1028 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001029 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1030 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001031 // negate dy since freetype-y-goes-up and skia-y-goes-down
1032 bbox->xMin += dx;
1033 bbox->yMin -= dy;
1034 bbox->xMax += dx;
1035 bbox->yMax -= dy;
1036 }
1037
1038 // outset the box to integral boundaries
1039 if (snapToPixelBoundary) {
1040 bbox->xMin &= ~63;
1041 bbox->yMin &= ~63;
1042 bbox->xMax = (bbox->xMax + 63) & ~63;
1043 bbox->yMax = (bbox->yMax + 63) & ~63;
1044 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001045
1046 // Must come after snapToPixelBoundary so that the width and height are
1047 // consistent. Otherwise asserts will fire later on when generating the
1048 // glyph image.
1049 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1050 FT_Vector vector;
1051 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1052 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1053 FT_Vector_Transform(&vector, &fMatrix22);
1054 bbox->xMin += vector.x;
1055 bbox->xMax += vector.x;
1056 bbox->yMin += vector.y;
1057 bbox->yMax += vector.y;
1058 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001059}
1060
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001061bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1062 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001063 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001064 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001065 }
1066 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001067 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001068 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001069 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001070 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1071 return true;
1072}
1073
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001074void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1075 if (isLCD(fRec)) {
1076 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001077 glyph->fHeight += gFTLibrary->lcdExtra();
1078 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001079 } else {
bungeman9dc24682014-12-01 14:01:32 -08001080 glyph->fWidth += gFTLibrary->lcdExtra();
1081 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001082 }
1083 }
1084}
1085
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001086inline void scaleGlyphMetrics(SkGlyph& glyph, SkScalar scale) {
1087 glyph.fWidth *= scale;
1088 glyph.fHeight *= scale;
1089 glyph.fTop *= scale;
1090 glyph.fLeft *= scale;
1091
1092 SkFixed fixedScale = SkScalarToFixed(scale);
1093 glyph.fAdvanceX = SkFixedMul(glyph.fAdvanceX, fixedScale);
1094 glyph.fAdvanceY = SkFixedMul(glyph.fAdvanceY, fixedScale);
1095}
1096
reed@android.com8a1c16f2008-12-17 15:59:43 +00001097void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1098 SkAutoMutexAcquire ac(gFTMutex);
1099
1100 glyph->fRsbDelta = 0;
1101 glyph->fLsbDelta = 0;
1102
1103 FT_Error err;
1104
1105 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001106 glyph->zeroMetrics();
1107 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001108 }
1109
djsollen1b277042014-08-06 06:58:06 -07001110 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001111 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001112 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001113 return;
1114 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001115 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001116
1117 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001118 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001119 if (0 == fFace->glyph->outline.n_contours) {
1120 glyph->fWidth = 0;
1121 glyph->fHeight = 0;
1122 glyph->fTop = 0;
1123 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001124 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001125 FT_BBox bbox;
1126 getBBoxForCurrentGlyph(glyph, &bbox, true);
1127
1128 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1129 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1130 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1131 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1132
1133 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001134 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001135 break;
1136
1137 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001138 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1139 FT_Vector vector;
1140 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1141 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1142 FT_Vector_Transform(&vector, &fMatrix22);
1143 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1144 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1145 }
1146
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001147 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1148 glyph->fMaskFormat = SkMask::kARGB32_Format;
1149 }
1150
reed@android.com8a1c16f2008-12-17 15:59:43 +00001151 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1152 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1153 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1154 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1155 break;
1156
1157 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001158 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001159 glyph->zeroMetrics();
1160 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001161 }
1162
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001163 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1164 if (fDoLinearMetrics) {
1165 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1166 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1167 } else {
1168 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1169 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1170 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001171 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001172 if (fDoLinearMetrics) {
1173 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1174 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1175 } else {
1176 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1177 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001178
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001179 if (fRec.fFlags & kDevKernText_Flag) {
1180 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1181 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001182 }
1183 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001184 }
1185
bungemana85511a2014-09-22 12:24:41 -07001186 // If the font isn't scalable, scale the metrics from the non-scalable strike.
1187 // This means do not try to scale embedded bitmaps; only scale bitmaps in bitmap only fonts.
1188 if (!FT_IS_SCALABLE(fFace) && fScaleY && fFace->size->metrics.y_ppem) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001189 // NOTE: both dimensions are scaled by y_ppem. this is WAI.
reed80ea19c2015-05-12 10:37:34 -07001190 scaleGlyphMetrics(*glyph, SkFixedToScalar(fScaleY) / fFace->size->metrics.y_ppem);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001191 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001192
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193#ifdef ENABLE_GLYPH_SPEW
1194 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
djsollen1b277042014-08-06 06:58:06 -07001195 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001196#endif
1197}
1198
bungeman5ec443c2014-11-21 13:18:34 -08001199static void clear_glyph_image(const SkGlyph& glyph) {
1200 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1201}
reed@google.comea2333d2011-03-14 16:44:56 +00001202
bungeman@google.coma76de722012-10-26 19:35:54 +00001203void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001204 SkAutoMutexAcquire ac(gFTMutex);
1205
reed@android.com8a1c16f2008-12-17 15:59:43 +00001206 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001207 clear_glyph_image(glyph);
1208 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001209 }
1210
bungeman5ec443c2014-11-21 13:18:34 -08001211 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001212 if (err != 0) {
1213 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 -08001214 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1215 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001216 return;
1217 }
1218
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001219 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.coma76de722012-10-26 19:35:54 +00001220 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001221}
1222
reed@android.com8a1c16f2008-12-17 15:59:43 +00001223
bungeman5ec443c2014-11-21 13:18:34 -08001224void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001225 SkAutoMutexAcquire ac(gFTMutex);
1226
caryclarka10742c2014-09-18 11:00:40 -07001227 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001228
1229 if (this->setupSize()) {
1230 path->reset();
1231 return;
1232 }
1233
1234 uint32_t flags = fLoadGlyphFlags;
1235 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1236 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1237
djsollen1b277042014-08-06 06:58:06 -07001238 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001239
1240 if (err != 0) {
1241 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001242 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001243 path->reset();
1244 return;
1245 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001246 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001247
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001248 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001249
1250 // The path's origin from FreeType is always the horizontal layout origin.
1251 // Offset the path so that it is relative to the vertical origin if needed.
1252 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1253 FT_Vector vector;
1254 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1255 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1256 FT_Vector_Transform(&vector, &fMatrix22);
1257 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1258 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001259}
1260
bungeman41078062014-07-07 08:16:37 -07001261void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
1262 if (NULL == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001263 return;
1264 }
1265
bungeman41078062014-07-07 08:16:37 -07001266 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001267
1268 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001269 ERROR:
bungeman41078062014-07-07 08:16:37 -07001270 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001271 return;
1272 }
1273
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001274 FT_Face face = fFace;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001275 SkScalar scaleX = fScale.x();
reed@google.comf073b332013-05-06 12:21:16 +00001276 SkScalar scaleY = fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001277 SkScalar mxy = fMatrix22Scalar.getSkewX() * scaleY;
1278 SkScalar myy = fMatrix22Scalar.getScaleY() * scaleY;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001279
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001280 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1281 SkScalar upem = SkIntToScalar(face->units_per_EM);
1282 if (!upem) {
1283 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1284 if (ttHeader) {
1285 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001286 }
1287 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001288
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001289 // use the os/2 table as a source of reasonable defaults.
1290 SkScalar x_height = 0.0f;
1291 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001292 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001293 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1294 if (os2) {
1295 x_height = scaleX * SkIntToScalar(os2->sxHeight) / upem;
1296 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001297 if (os2->version != 0xFFFF && os2->version >= 2) {
1298 cap_height = scaleX * SkIntToScalar(os2->sCapHeight) / upem;
1299 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001300 }
1301
1302 // pull from format-specific metrics as needed
1303 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001304 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001305 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001306 // FreeType will always use HHEA metrics if they're not zero.
1307 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1308 // It also ignores the VDMX tables, which are also of interest here
1309 // (and override everything else when they apply).
1310 static const int kUseTypoMetricsMask = (1 << 7);
1311 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1312 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1313 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1314 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1315 } else {
1316 ascent = -SkIntToScalar(face->ascender) / upem;
1317 descent = -SkIntToScalar(face->descender) / upem;
1318 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1319 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001320 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1321 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1322 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1323 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001324 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001325 underlinePosition = -SkIntToScalar(face->underline_position +
1326 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001327
bungeman41078062014-07-07 08:16:37 -07001328 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1329 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1330
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001331 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001332 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001333 FT_BBox bbox;
1334 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001335 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1336 }
1337 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001338 if (!cap_height) {
1339 FT_BBox bbox;
1340 if (getCBoxForLetter('H', &bbox)) {
1341 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1342 }
1343 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001344 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1345 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1346 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1347 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1348 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1349 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f))
1350 + ascent - descent;
1351 xmin = 0.0f;
1352 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1353 ymin = descent + leading;
1354 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001355 underlineThickness = 0;
1356 underlinePosition = 0;
1357
bungeman41078062014-07-07 08:16:37 -07001358 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1359 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001360 } else {
1361 goto ERROR;
1362 }
1363
1364 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1365 if (!x_height) {
1366 x_height = -ascent;
1367 }
1368 if (!avgCharWidth) {
1369 avgCharWidth = xmax - xmin;
1370 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001371 if (!cap_height) {
1372 cap_height = -ascent;
1373 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001374
1375 // disallow negative linespacing
1376 if (leading < 0.0f) {
1377 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001378 }
1379
bungeman41078062014-07-07 08:16:37 -07001380 SkScalar scale = myy;
1381 if (this->isVertical()) {
1382 scale = mxy;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001383 }
bungeman41078062014-07-07 08:16:37 -07001384 metrics->fTop = ymax * scale;
1385 metrics->fAscent = ascent * scale;
1386 metrics->fDescent = descent * scale;
1387 metrics->fBottom = ymin * scale;
1388 metrics->fLeading = leading * scale;
1389 metrics->fAvgCharWidth = avgCharWidth * scale;
reedc17c6582014-10-31 08:20:46 -07001390 metrics->fXMin = xmin * scale;
1391 metrics->fXMax = xmax * scale;
bungeman7316b102014-10-29 12:46:52 -07001392 metrics->fXHeight = x_height;
1393 metrics->fCapHeight = cap_height;
bungeman41078062014-07-07 08:16:37 -07001394 metrics->fUnderlineThickness = underlineThickness * scale;
1395 metrics->fUnderlinePosition = underlinePosition * scale;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001396}
1397
djsollenfcfea992015-01-09 08:18:13 -08001398///////////////////////////////////////////////////////////////////////////////
1399
1400// hand-tuned value to reduce outline embolden strength
1401#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1402 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1403 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1404 #else
1405 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1406 #endif
1407#endif
1408
1409///////////////////////////////////////////////////////////////////////////////
1410
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001411void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1412{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001413 // check to see if the embolden bit is set
1414 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1415 return;
1416 }
1417
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001418 switch (glyph->format) {
1419 case FT_GLYPH_FORMAT_OUTLINE:
1420 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001421 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1422 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001423 FT_Outline_Embolden(&glyph->outline, strength);
1424 break;
1425 case FT_GLYPH_FORMAT_BITMAP:
1426 FT_GlyphSlot_Own_Bitmap(glyph);
1427 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1428 break;
1429 default:
1430 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001431 }
1432}
1433
reed@google.comb4162b12013-07-02 16:32:29 +00001434///////////////////////////////////////////////////////////////////////////////
1435
1436#include "SkUtils.h"
1437
1438static SkUnichar next_utf8(const void** chars) {
1439 return SkUTF8_NextUnichar((const char**)chars);
1440}
1441
1442static SkUnichar next_utf16(const void** chars) {
1443 return SkUTF16_NextUnichar((const uint16_t**)chars);
1444}
1445
1446static SkUnichar next_utf32(const void** chars) {
1447 const SkUnichar** uniChars = (const SkUnichar**)chars;
1448 SkUnichar uni = **uniChars;
1449 *uniChars += 1;
1450 return uni;
1451}
1452
1453typedef SkUnichar (*EncodingProc)(const void**);
1454
1455static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1456 static const EncodingProc gProcs[] = {
1457 next_utf8, next_utf16, next_utf32
1458 };
1459 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1460 return gProcs[enc];
1461}
1462
1463int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001464 uint16_t glyphs[], int glyphCount) const
1465{
reed@google.comb4162b12013-07-02 16:32:29 +00001466 AutoFTAccess fta(this);
1467 FT_Face face = fta.face();
1468 if (!face) {
1469 if (glyphs) {
1470 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1471 }
1472 return 0;
1473 }
1474
1475 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1476
1477 if (NULL == glyphs) {
1478 for (int i = 0; i < glyphCount; ++i) {
1479 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1480 return i;
1481 }
1482 }
1483 return glyphCount;
1484 } else {
1485 int first = glyphCount;
1486 for (int i = 0; i < glyphCount; ++i) {
1487 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1488 glyphs[i] = SkToU16(id);
1489 if (0 == id && i < first) {
1490 first = i;
1491 }
1492 }
1493 return first;
1494 }
1495}
1496
1497int SkTypeface_FreeType::onCountGlyphs() const {
1498 // we cache this value, using -1 as a sentinel for "not computed"
1499 if (fGlyphCount < 0) {
1500 AutoFTAccess fta(this);
1501 FT_Face face = fta.face();
1502 // if the face failed, we still assign a non-negative value
1503 fGlyphCount = face ? face->num_glyphs : 0;
1504 }
1505 return fGlyphCount;
1506}
1507
bungeman@google.com839702b2013-08-07 17:09:22 +00001508SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001509 SkTypeface::LocalizedStrings* nameIter =
1510 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1511 if (NULL == nameIter) {
1512 SkString familyName;
1513 this->getFamilyName(&familyName);
1514 SkString language("und"); //undetermined
1515 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1516 }
1517 return nameIter;
1518}
1519
bungeman@google.comddc218e2013-08-01 22:29:43 +00001520int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1521 AutoFTAccess fta(this);
1522 FT_Face face = fta.face();
1523
1524 FT_ULong tableCount = 0;
1525 FT_Error error;
1526
1527 // When 'tag' is NULL, returns number of tables in 'length'.
1528 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1529 if (error) {
1530 return 0;
1531 }
1532
1533 if (tags) {
1534 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1535 FT_ULong tableTag;
1536 FT_ULong tablelength;
1537 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1538 if (error) {
1539 return 0;
1540 }
1541 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1542 }
1543 }
1544 return tableCount;
1545}
1546
1547size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1548 size_t length, void* data) const
1549{
1550 AutoFTAccess fta(this);
1551 FT_Face face = fta.face();
1552
1553 FT_ULong tableLength = 0;
1554 FT_Error error;
1555
1556 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1557 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1558 if (error) {
1559 return 0;
1560 }
1561
1562 if (offset > tableLength) {
1563 return 0;
1564 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001565 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001566 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001567 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1568 if (error) {
1569 return 0;
1570 }
1571 }
1572
1573 return size;
1574}
1575
reed@google.comb4162b12013-07-02 16:32:29 +00001576///////////////////////////////////////////////////////////////////////////////
1577///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001578
bungeman9dc24682014-12-01 14:01:32 -08001579SkTypeface_FreeType::Scanner::Scanner() : fLibrary(NULL) {
1580 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1581 return;
bungeman14df8332014-10-28 15:07:23 -07001582 }
bungeman9dc24682014-12-01 14:01:32 -08001583 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001584}
1585SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001586 if (fLibrary) {
1587 FT_Done_Library(fLibrary);
1588 }
bungeman14df8332014-10-28 15:07:23 -07001589}
1590
1591FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1592 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001593{
bungeman14df8332014-10-28 15:07:23 -07001594 if (fLibrary == NULL) {
1595 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001596 }
1597
bungeman14df8332014-10-28 15:07:23 -07001598 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001599 memset(&args, 0, sizeof(args));
1600
1601 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001602
bsalomon49f085d2014-09-05 13:34:00 -07001603 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001604 args.flags = FT_OPEN_MEMORY;
1605 args.memory_base = (const FT_Byte*)memoryBase;
1606 args.memory_size = stream->getLength();
1607 } else {
bungeman14df8332014-10-28 15:07:23 -07001608 memset(ftStream, 0, sizeof(*ftStream));
1609 ftStream->size = stream->getLength();
1610 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001611 ftStream->read = sk_ft_stream_io;
1612 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001613
1614 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001615 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001616 }
1617
1618 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001619 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
1620 return NULL;
1621 }
1622 return face;
1623}
1624
1625bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1626 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1627
1628 FT_StreamRec streamRec;
1629 FT_Face face = this->openFace(stream, -1, &streamRec);
1630 if (NULL == face) {
1631 return false;
1632 }
1633
1634 *numFaces = face->num_faces;
1635
1636 FT_Done_Face(face);
1637 return true;
1638}
1639
1640#include "SkTSearch.h"
1641bool SkTypeface_FreeType::Scanner::scanFont(
bungeman41868fe2015-05-20 09:21:04 -07001642 SkStream* stream, int ttcIndex,
1643 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001644{
1645 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1646
1647 FT_StreamRec streamRec;
1648 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
1649 if (NULL == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001650 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001651 }
1652
bungemana4c4a2d2014-10-20 13:33:19 -07001653 int weight = SkFontStyle::kNormal_Weight;
1654 int width = SkFontStyle::kNormal_Width;
1655 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001656 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001657 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001658 }
1659 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001660 slant = SkFontStyle::kItalic_Slant;
1661 }
1662
1663 PS_FontInfoRec psFontInfo;
1664 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1665 if (os2 && os2->version != 0xffff) {
1666 weight = os2->usWeightClass;
1667 width = os2->usWidthClass;
1668 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1669 static const struct {
1670 char const * const name;
1671 int const weight;
1672 } commonWeights [] = {
1673 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001674 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001675 { "black", SkFontStyle::kBlack_Weight },
1676 { "bold", SkFontStyle::kBold_Weight },
1677 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1678 { "demi", SkFontStyle::kSemiBold_Weight },
1679 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001680 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001681 { "extrabold", SkFontStyle::kExtraBold_Weight },
1682 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001683 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001684 { "heavy", SkFontStyle::kBlack_Weight },
1685 { "light", SkFontStyle::kLight_Weight },
1686 { "medium", SkFontStyle::kMedium_Weight },
1687 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001688 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001689 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001690 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001691 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001692 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001693 { "thin", SkFontStyle::kThin_Weight },
1694 { "ultra", SkFontStyle::kExtraBold_Weight },
1695 { "ultrablack", 1000 },
1696 { "ultrabold", SkFontStyle::kExtraBold_Weight },
1697 { "ultraheavy", 1000 },
1698 { "ultralight", SkFontStyle::kExtraLight_Weight },
1699 };
1700 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001701 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001702 if (index >= 0) {
1703 weight = commonWeights[index].weight;
1704 } else {
bungeman14df8332014-10-28 15:07:23 -07001705 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001706 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001707 }
1708
1709 if (name) {
1710 name->set(face->family_name);
1711 }
1712 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001713 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001714 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001715 if (isFixedPitch) {
1716 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001717 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001718
bungeman41868fe2015-05-20 09:21:04 -07001719 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
1720 FT_MM_Var* variations = NULL;
1721 FT_Error err = FT_Get_MM_Var(face, &variations);
1722 if (err) {
1723 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1724 face->family_name));
1725 return false;
1726 }
1727 SkAutoFree autoFreeVariations(variations);
1728
1729 axes->reset(variations->num_axis);
1730 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1731 const FT_Var_Axis& ftAxis = variations->axis[i];
1732 (*axes)[i].fTag = ftAxis.tag;
1733 (*axes)[i].fMinimum = ftAxis.minimum;
1734 (*axes)[i].fDefault = ftAxis.def;
1735 (*axes)[i].fMaximum = ftAxis.maximum;
1736 }
1737 }
bungeman41868fe2015-05-20 09:21:04 -07001738
reed@android.com8a1c16f2008-12-17 15:59:43 +00001739 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001740 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001741}