blob: cb7ce8028dccd4e92d81b1e8ce63fc3b08c4b438 [file] [log] [blame]
bungeman@google.comfe755b42014-01-28 20:33:09 +00001
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +00009#include "SkAdvancedTypefaceMetrics.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000010#include "SkBitmap.h"
11#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000012#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000013#include "SkDescriptor.h"
14#include "SkFDot6.h"
bungeman@google.com3aacb412012-03-13 14:55:12 +000015#include "SkFloatingPoint.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000016#include "SkFontHost.h"
george@mozilla.comc59b5da2012-08-23 00:39:08 +000017#include "SkFontHost_FreeType_common.h"
bungeman@google.combbe50132012-07-24 20:33:21 +000018#include "SkGlyph.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000019#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000020#include "SkMaskGamma.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000021#include "SkOTUtils.h"
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +000022#include "SkOnce.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"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000027#include "SkThread.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>
33#include FT_FREETYPE_H
34#include FT_OUTLINE_H
35#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000036#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000037#include FT_TYPE1_TABLES_H
agl@chromium.orge76073b2010-06-04 20:31:17 +000038#include FT_BITMAP_H
agl@chromium.org36bb6972010-06-04 20:57:16 +000039// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
40#include FT_SYNTHESIS_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000041#include FT_XFREE86_H
epoger@google.com5070d792011-06-29 20:43:14 +000042#ifdef FT_LCD_FILTER_H
agl@chromium.org309485b2009-07-21 17:41:32 +000043#include FT_LCD_FILTER_H
epoger@google.com5070d792011-06-29 20:43:14 +000044#endif
agl@chromium.org309485b2009-07-21 17:41:32 +000045
reed@android.com8a1c16f2008-12-17 15:59:43 +000046#ifdef FT_ADVANCES_H
47#include FT_ADVANCES_H
48#endif
49
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000050#if 0
51// Also include the files by name for build tools which require this.
52#include <freetype/freetype.h>
53#include <freetype/ftoutln.h>
54#include <freetype/ftsizes.h>
55#include <freetype/tttables.h>
56#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000057#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000058#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000059#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000060#endif
61
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000062// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
63// were introduced in FreeType 2.5.0.
64// The following may be removed once FreeType 2.5.0 is required to build.
65#ifndef FT_LOAD_COLOR
66# define FT_LOAD_COLOR ( 1L << 20 )
67# define FT_PIXEL_MODE_BGRA 7
68#endif
69
70// FT_HAS_COLOR and the corresponding FT_FACE_FLAG_COLOR
71// were introduced in FreeType 2.5.1
72// The following may be removed once FreeType 2.5.1 is required to build.
73#ifndef FT_HAS_COLOR
74# define FT_HAS_COLOR(face) false
75#endif
76
reed@android.com8a1c16f2008-12-17 15:59:43 +000077//#define ENABLE_GLYPH_SPEW // for tracing calls
78//#define DUMP_STRIKE_CREATION
79
reed@google.com1ac83502012-02-28 17:06:02 +000080//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000081
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000082using namespace skia_advanced_typeface_metrics_utils;
83
reed@google.comeffc5012011-06-27 16:44:46 +000084static bool isLCD(const SkScalerContext::Rec& rec) {
85 switch (rec.fMaskFormat) {
86 case SkMask::kLCD16_Format:
87 case SkMask::kLCD32_Format:
88 return true;
89 default:
90 return false;
91 }
92}
93
reed@android.com8a1c16f2008-12-17 15:59:43 +000094//////////////////////////////////////////////////////////////////////////
95
96struct SkFaceRec;
97
digit@google.com1771cbf2012-01-26 21:26:40 +000098SK_DECLARE_STATIC_MUTEX(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +000099static int gFTCount;
100static FT_Library gFTLibrary;
101static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000102static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
103static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@google.coma1c32562012-03-01 19:38:23 +0000104static int gLCDExtra; // number of extra pixels for filtering.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000105
bungeman@google.com62566f32012-10-13 03:21:53 +0000106/////////////////////////////////////////////////////////////////////////
107
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000108// FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
109// The following platforms provide FreeType of at least 2.4.0.
110// Ubuntu >= 11.04 (previous deprecated April 2013)
111// Debian >= 6.0 (good)
112// OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
113// Fedora >= 14 (good)
114// Android >= Gingerbread (good)
115typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
116
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000117// Caller must lock gFTMutex before calling this function.
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000118static bool InitFreetype() {
agl@chromium.org309485b2009-07-21 17:41:32 +0000119 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000120 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000121 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000122 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000123
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000124 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
epoger@google.comb371ed12011-06-29 21:20:52 +0000125#ifdef FT_LCD_FILTER_H
bungeman@google.com62566f32012-10-13 03:21:53 +0000126 // Use default { 0x10, 0x40, 0x70, 0x40, 0x10 }, as it adds up to 0x110, simulating ink spread.
127 // SetLcdFilter must be called before SetLcdFilterWeights.
128 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000129 if (0 == err) {
130 gLCDSupport = true;
131 gLCDExtra = 2; //Using a filter adds one full pixel to each side.
132
bungeman@google.com62566f32012-10-13 03:21:53 +0000133#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
134 // This also adds to 0x110 simulating ink spread, but provides better results than default.
135 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000136
137#if defined(SK_FONTHOST_FREETYPE_RUNTIME_VERSION) && \
138 SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
bungeman@google.com62566f32012-10-13 03:21:53 +0000139 err = FT_Library_SetLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000140#elif defined(SK_CAN_USE_DLOPEN) && SK_CAN_USE_DLOPEN == 1
141 //The FreeType library is already loaded, so symbols are available in process.
142 void* self = dlopen(NULL, RTLD_LAZY);
143 if (NULL != self) {
144 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
145 //The following cast is non-standard, but safe for POSIX.
146 *reinterpret_cast<void**>(&setLcdFilterWeights) = dlsym(self, "FT_Library_SetLcdFilterWeights");
147 dlclose(self);
148
149 if (NULL != setLcdFilterWeights) {
bungeman@google.com62566f32012-10-13 03:21:53 +0000150 err = setLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000151 }
152 }
153#endif
bungeman@google.com62566f32012-10-13 03:21:53 +0000154#endif
reed@google.coma1c32562012-03-01 19:38:23 +0000155 }
epoger@google.com5070d792011-06-29 20:43:14 +0000156#else
157 gLCDSupport = false;
158#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000159 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000160
161 return true;
162}
163
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000164// Called while holding gFTMutex.
165static void determine_lcd_support(bool* lcdSupported) {
166 if (!gLCDSupportValid) {
167 // This will determine LCD support as a side effect.
168 InitFreetype();
169 FT_Done_FreeType(gFTLibrary);
170 }
171 SkASSERT(gLCDSupportValid);
172 *lcdSupported = gLCDSupport;
173}
174
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000175// Lazy, once, wrapper to ask the FreeType Library if it can support LCD text
176static bool is_lcd_supported() {
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000177 static bool lcdSupported = false;
178 SkOnce(&gLCDSupportValid, &gFTMutex, determine_lcd_support, &lcdSupported);
179 return lcdSupported;
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000180}
181
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000182class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000183public:
reed@google.com0da48612013-03-19 16:06:52 +0000184 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000185 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000186
reed@android.com62900b42009-02-11 15:07:19 +0000187 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000188 return fFaceRec != NULL &&
189 fFTSize != NULL &&
190 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000191 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000192
193protected:
bungeman@google.coma76de722012-10-26 19:35:54 +0000194 virtual unsigned generateGlyphCount() SK_OVERRIDE;
195 virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE;
196 virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE;
197 virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE;
198 virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE;
199 virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000200 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
bungeman@google.coma76de722012-10-26 19:35:54 +0000201 SkPaint::FontMetrics* my) SK_OVERRIDE;
202 virtual SkUnichar generateGlyphToChar(uint16_t glyph) SK_OVERRIDE;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000203
204private:
205 SkFaceRec* fFaceRec;
206 FT_Face fFace; // reference to shared face in gFaceRecHead
207 FT_Size fFTSize; // our own copy
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000208 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000209 SkFixed fScaleX, fScaleY;
210 FT_Matrix fMatrix22;
211 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000212 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000213 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000214
reed@google.comf073b332013-05-06 12:21:16 +0000215 // Need scalar versions for generateFontMetrics
216 SkVector fScale;
217 SkMatrix fMatrix22Scalar;
218
reed@android.com8a1c16f2008-12-17 15:59:43 +0000219 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000220 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
221 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000222 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000223 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000224 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000225 // Caller must lock gFTMutex before calling this function.
226 // update FreeType2 glyph slot with glyph emboldened
227 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000228};
229
230///////////////////////////////////////////////////////////////////////////
231///////////////////////////////////////////////////////////////////////////
232
reed@android.com8a1c16f2008-12-17 15:59:43 +0000233struct SkFaceRec {
234 SkFaceRec* fNext;
235 FT_Face fFace;
236 FT_StreamRec fFTStream;
237 SkStream* fSkStream;
238 uint32_t fRefCnt;
239 uint32_t fFontID;
240
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000241 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000242 SkFaceRec(SkStream* strm, uint32_t fontID);
243 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000244 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000245 }
246};
247
248extern "C" {
249 static unsigned long sk_stream_read(FT_Stream stream,
250 unsigned long offset,
251 unsigned char* buffer,
252 unsigned long count ) {
253 SkStream* str = (SkStream*)stream->descriptor.pointer;
254
255 if (count) {
256 if (!str->rewind()) {
257 return 0;
258 } else {
259 unsigned long ret;
260 if (offset) {
261 ret = str->read(NULL, offset);
262 if (ret != offset) {
263 return 0;
264 }
265 }
266 ret = str->read(buffer, count);
267 if (ret != count) {
268 return 0;
269 }
270 count = ret;
271 }
272 }
273 return count;
274 }
275
sugoi@google.com66a58ac2013-03-05 20:40:52 +0000276 static void sk_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000277}
278
279SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
vandebo@chromium.org9af25f32012-03-28 21:24:27 +0000280 : fNext(NULL), fSkStream(strm), fRefCnt(1), fFontID(fontID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000281// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
282
reed@android.com4516f472009-06-29 16:25:36 +0000283 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000284 fFTStream.size = fSkStream->getLength();
285 fFTStream.descriptor.pointer = fSkStream;
286 fFTStream.read = sk_stream_read;
287 fFTStream.close = sk_stream_close;
288}
289
reed@android.com62900b42009-02-11 15:07:19 +0000290// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000291// Caller must lock gFTMutex before calling this function.
reed@google.com2cdc6712013-03-21 18:22:00 +0000292static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
293 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000294 SkFaceRec* rec = gFaceRecHead;
295 while (rec) {
296 if (rec->fFontID == fontID) {
297 SkASSERT(rec->fFace);
298 rec->fRefCnt += 1;
299 return rec;
300 }
301 rec = rec->fNext;
302 }
303
reed@google.com2cdc6712013-03-21 18:22:00 +0000304 int face_index;
305 SkStream* strm = typeface->openStream(&face_index);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306 if (NULL == strm) {
reed@google.com2cdc6712013-03-21 18:22:00 +0000307 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000308 }
309
310 // this passes ownership of strm to the rec
311 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
312
313 FT_Open_Args args;
314 memset(&args, 0, sizeof(args));
315 const void* memoryBase = strm->getMemoryBase();
316
317 if (NULL != memoryBase) {
318//printf("mmap(%s)\n", keyString.c_str());
319 args.flags = FT_OPEN_MEMORY;
320 args.memory_base = (const FT_Byte*)memoryBase;
321 args.memory_size = strm->getLength();
322 } else {
323//printf("fopen(%s)\n", keyString.c_str());
324 args.flags = FT_OPEN_STREAM;
325 args.stream = &rec->fFTStream;
326 }
327
reed@google.com2cdc6712013-03-21 18:22:00 +0000328 FT_Error err = FT_Open_Face(gFTLibrary, &args, face_index, &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000329 if (err) { // bad filename, try the default font
330 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
331 SkDELETE(rec);
reed@google.com2cdc6712013-03-21 18:22:00 +0000332 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000333 } else {
334 SkASSERT(rec->fFace);
335 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
336 rec->fNext = gFaceRecHead;
337 gFaceRecHead = rec;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338 return rec;
339 }
340}
341
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000342// Caller must lock gFTMutex before calling this function.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000343static void unref_ft_face(FT_Face face) {
344 SkFaceRec* rec = gFaceRecHead;
345 SkFaceRec* prev = NULL;
346 while (rec) {
347 SkFaceRec* next = rec->fNext;
348 if (rec->fFace == face) {
349 if (--rec->fRefCnt == 0) {
350 if (prev) {
351 prev->fNext = next;
352 } else {
353 gFaceRecHead = next;
354 }
355 FT_Done_Face(face);
356 SkDELETE(rec);
357 }
358 return;
359 }
360 prev = rec;
361 rec = next;
362 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000363 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000364}
365
reed@google.comb4162b12013-07-02 16:32:29 +0000366class AutoFTAccess {
367public:
368 AutoFTAccess(const SkTypeface* tf) : fRec(NULL), fFace(NULL) {
369 gFTMutex.acquire();
370 if (1 == ++gFTCount) {
371 if (!InitFreetype()) {
372 sk_throw();
373 }
374 }
375 fRec = ref_ft_face(tf);
376 if (fRec) {
377 fFace = fRec->fFace;
378 }
379 }
380
381 ~AutoFTAccess() {
382 if (fFace) {
383 unref_ft_face(fFace);
384 }
385 if (0 == --gFTCount) {
386 FT_Done_FreeType(gFTLibrary);
387 }
388 gFTMutex.release();
389 }
390
391 SkFaceRec* rec() { return fRec; }
392 FT_Face face() { return fFace; }
393
394private:
395 SkFaceRec* fRec;
396 FT_Face fFace;
397};
398
reed@android.com8a1c16f2008-12-17 15:59:43 +0000399///////////////////////////////////////////////////////////////////////////
400
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000401// Work around for old versions of freetype.
402static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
403 FT_Int32 loadFlags, FT_Fixed* advances) {
404#ifdef FT_ADVANCES_H
405 return FT_Get_Advances(face, start, count, loadFlags, advances);
406#else
407 if (!face || start >= face->num_glyphs ||
408 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
409 return 6; // "Invalid argument."
410 }
411 if (count == 0)
412 return 0;
413
414 for (int i = 0; i < count; i++) {
415 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
416 if (err)
417 return err;
418 advances[i] = face->glyph->advance.x;
419 }
420
421 return 0;
422#endif
423}
424
425static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000426#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000427 FT_UShort fsType = FT_Get_FSType_Flags(face);
428 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
429 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
430#else
431 // No embedding is 0x2 and bitmap embedding only is 0x200.
432 TT_OS2* os2_table;
433 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
434 return (os2_table->fsType & 0x202) == 0;
435 }
436 return false; // We tried, fail safe.
437#endif
438}
439
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000440static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
441 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
442 if (!glyph_id)
443 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000444 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
445 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000446 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
447 return true;
448}
449
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000450static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000451 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000452 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
453 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000455 SkASSERT(data);
456 *data = advance;
457 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000458}
459
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000460static void populate_glyph_to_unicode(FT_Face& face,
461 SkTDArray<SkUnichar>* glyphToUnicode) {
462 // Check and see if we have Unicode cmaps.
463 for (int i = 0; i < face->num_charmaps; ++i) {
464 // CMaps known to support Unicode:
465 // Platform ID Encoding ID Name
466 // ----------- ----------- -----------------------------------
467 // 0 0,1 Apple Unicode
468 // 0 3 Apple Unicode 2.0 (preferred)
469 // 3 1 Microsoft Unicode UCS-2
470 // 3 10 Microsoft Unicode UCS-4 (preferred)
471 //
472 // See Apple TrueType Reference Manual
473 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
474 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
475 // Microsoft OpenType Specification
476 // http://www.microsoft.com/typography/otspec/cmap.htm
477
478 FT_UShort platformId = face->charmaps[i]->platform_id;
479 FT_UShort encodingId = face->charmaps[i]->encoding_id;
480
481 if (platformId != 0 && platformId != 3) {
482 continue;
483 }
484 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
485 continue;
486 }
487 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
488 (platformId == 0 && encodingId == 3));
489
490 FT_Set_Charmap(face, face->charmaps[i]);
491 if (glyphToUnicode->isEmpty()) {
492 glyphToUnicode->setCount(face->num_glyphs);
493 memset(glyphToUnicode->begin(), 0,
494 sizeof(SkUnichar) * face->num_glyphs);
495 }
496
497 // Iterate through each cmap entry.
498 FT_UInt glyphIndex;
499 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
500 glyphIndex != 0;
501 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
502 if (charCode &&
503 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
504 (*glyphToUnicode)[glyphIndex] = charCode;
505 }
506 }
507 }
508}
509
reed@google.com2689f612013-03-20 20:01:47 +0000510SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000511 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
512 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000513 uint32_t glyphIDsCount) const {
djsollen@google.comda957722011-11-16 17:00:46 +0000514#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000515 return NULL;
516#else
reed@google.comb4162b12013-07-02 16:32:29 +0000517 AutoFTAccess fta(this);
518 FT_Face face = fta.face();
519 if (!face) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000520 return NULL;
reed@google.comb4162b12013-07-02 16:32:29 +0000521 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000522
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000523 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
524 info->fFontName.set(FT_Get_Postscript_Name(face));
vandebo@chromium.org5f209e62013-12-10 17:22:41 +0000525 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000526 info->fLastGlyphID = face->num_glyphs - 1;
527 info->fEmSize = 1000;
528
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000529 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000530 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000531 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000532 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000533 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000534 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000535 cid = true;
536 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000537 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000538 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000539 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000540 cid = true;
541 TT_Header* ttHeader;
542 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
543 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000544 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000545 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000546 } else {
547 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000548 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000549
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000550 info->fStyle = 0;
551 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000552 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000553 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000554 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000555
556 PS_FontInfoRec ps_info;
557 TT_Postscript* tt_info;
558 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
559 info->fItalicAngle = ps_info.italic_angle;
560 } else if ((tt_info =
561 (TT_Postscript*)FT_Get_Sfnt_Table(face,
562 ft_sfnt_post)) != NULL) {
563 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
564 } else {
565 info->fItalicAngle = 0;
566 }
567
568 info->fAscent = face->ascender;
569 info->fDescent = face->descender;
570
571 // Figure out a good guess for StemV - Min width of i, I, !, 1.
572 // This probably isn't very good with an italic font.
573 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000574 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000575 char stem_chars[] = {'i', 'I', '!', '1'};
576 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
577 FT_BBox bbox;
578 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
579 int16_t width = bbox.xMax - bbox.xMin;
580 if (width > 0 && width < min_width) {
581 min_width = width;
582 info->fStemV = min_width;
583 }
584 }
585 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000586
587 TT_PCLT* pclt_info;
588 TT_OS2* os2_table;
589 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
590 info->fCapHeight = pclt_info->CapHeight;
591 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
592 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000593 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000594 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000595 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000596 } else if (((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) &&
597 // sCapHeight is available only when version 2 or later.
598 os2_table->version != 0xFFFF &&
599 os2_table->version >= 2) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000600 info->fCapHeight = os2_table->sCapHeight;
601 } else {
602 // Figure out a good guess for CapHeight: average the height of M and X.
603 FT_BBox m_bbox, x_bbox;
604 bool got_m, got_x;
605 got_m = GetLetterCBox(face, 'M', &m_bbox);
606 got_x = GetLetterCBox(face, 'X', &x_bbox);
607 if (got_m && got_x) {
608 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
609 x_bbox.yMin) / 2;
610 } else if (got_m && !got_x) {
611 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
612 } else if (!got_m && got_x) {
613 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000614 } else {
615 // Last resort, use the ascent.
616 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000617 }
618 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000619
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000620 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
621 face->bbox.xMax, face->bbox.yMin);
622
vandebo@chromium.org5f209e62013-12-10 17:22:41 +0000623 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
624 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000625 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
626 }
627
628 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000629 if (FT_IS_FIXED_WIDTH(face)) {
630 appendRange(&info->fGlyphWidths, 0);
631 int16_t advance = face->max_advance_width;
632 info->fGlyphWidths->fAdvance.append(1, &advance);
633 finishRange(info->fGlyphWidths.get(), 0,
634 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000635 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000636 appendRange(&info->fGlyphWidths, 0);
637 // So as to not blow out the stack, get advances in batches.
638 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
639 FT_Fixed advances[128];
640 int advanceCount = 128;
641 if (gID + advanceCount > face->num_glyphs)
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000642 advanceCount = face->num_glyphs - gID;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000643 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
644 advances);
645 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000646 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000647 info->fGlyphWidths->fAdvance.append(1, &advance);
648 }
649 }
650 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
651 SkAdvancedTypefaceMetrics::WidthRange::kRange);
652 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000653 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000654 getAdvanceData(face,
655 face->num_glyphs,
656 glyphIDs,
657 glyphIDsCount,
658 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000659 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000660 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000661
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000662 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
663 FT_HAS_VERTICAL(face)) {
664 SkASSERT(false); // Not implemented yet.
665 }
666
667 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
668 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
669 // Postscript fonts may contain more than 255 glyphs, so we end up
670 // using multiple font descriptions with a glyph ordering. Record
671 // the name of each glyph.
672 info->fGlyphNames.reset(
673 new SkAutoTArray<SkString>(face->num_glyphs));
674 for (int gID = 0; gID < face->num_glyphs; gID++) {
675 char glyphName[128]; // PS limit for names is 127 bytes.
676 FT_Get_Glyph_Name(face, gID, glyphName, 128);
677 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000678 }
679 }
680
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000681 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
682 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
683 face->num_charmaps) {
684 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
685 }
686
vandebo@chromium.org5f209e62013-12-10 17:22:41 +0000687 if (!canEmbed(face))
688 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
689
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000690 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000691#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000692}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000693
reed@google.com618ef5e2011-01-26 22:10:41 +0000694///////////////////////////////////////////////////////////////////////////
695
reed@google.comffe49f52011-11-22 19:42:41 +0000696#define BLACK_LUMINANCE_LIMIT 0x40
697#define WHITE_LUMINANCE_LIMIT 0xA0
698
reed@google.com8ed436c2011-07-21 14:12:36 +0000699static bool bothZero(SkScalar a, SkScalar b) {
700 return 0 == a && 0 == b;
701}
702
703// returns false if there is any non-90-rotation or skew
704static bool isAxisAligned(const SkScalerContext::Rec& rec) {
705 return 0 == rec.fPreSkewX &&
706 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
707 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
708}
709
reed@google.com0da48612013-03-19 16:06:52 +0000710SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
711 const SkDescriptor* desc) const {
712 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
713 (const_cast<SkTypeface_FreeType*>(this),
714 desc));
715 if (!c->success()) {
716 SkDELETE(c);
717 c = NULL;
718 }
719 return c;
720}
721
722void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000723 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
724 //Cap the requested size as larger sizes give bogus values.
725 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000726 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000727 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000728 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000729
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000730 if (!is_lcd_supported() && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000731 // If the runtime Freetype library doesn't support LCD mode, we disable
732 // it here.
733 rec->fMaskFormat = SkMask::kA8_Format;
734 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000735
reed@google.com618ef5e2011-01-26 22:10:41 +0000736 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000737 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000738 // collapse full->normal hinting if we're not doing LCD
739 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000740 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000741 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000742 if (SkPaint::kNo_Hinting != h) {
743 h = SkPaint::kSlight_Hinting;
744 }
745 }
746
reed@google.com8ed436c2011-07-21 14:12:36 +0000747 // rotated text looks bad with hinting, so we disable it as needed
748 if (!isAxisAligned(*rec)) {
749 h = SkPaint::kNo_Hinting;
750 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000751 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000752
bungeman@google.com97efada2012-07-30 20:40:50 +0000753#ifndef SK_GAMMA_APPLY_TO_A8
754 if (!isLCD(*rec)) {
755 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000756 }
reed@google.com1ac83502012-02-28 17:06:02 +0000757#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000758}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000759
reed@google.com38c37dd2013-03-21 15:36:26 +0000760int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000761 AutoFTAccess fta(this);
762 FT_Face face = fta.face();
763 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000764}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000765
reed@google.com35fe7372013-10-30 15:07:03 +0000766bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
767 int count, int32_t adjustments[]) const {
768 AutoFTAccess fta(this);
769 FT_Face face = fta.face();
770 if (!face || !FT_HAS_KERNING(face)) {
771 return false;
772 }
773
774 for (int i = 0; i < count - 1; ++i) {
775 FT_Vector delta;
776 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
777 FT_KERNING_UNSCALED, &delta);
778 if (err) {
779 return false;
780 }
781 adjustments[i] = delta.x;
782 }
783 return true;
784}
785
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000786static FT_Int chooseBitmapStrike(FT_Face face, SkFixed scaleY) {
787 // early out if face is bad
788 if (face == NULL) {
789 SkDEBUGF(("chooseBitmapStrike aborted due to NULL face\n"));
790 return -1;
791 }
792 // determine target ppem
793 FT_Pos targetPPEM = SkFixedToFDot6(scaleY);
794 // find a bitmap strike equal to or just larger than the requested size
795 FT_Int chosenStrikeIndex = -1;
796 FT_Pos chosenPPEM = 0;
797 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
798 FT_Pos thisPPEM = face->available_sizes[strikeIndex].y_ppem;
799 if (thisPPEM == targetPPEM) {
800 // exact match - our search stops here
801 chosenPPEM = thisPPEM;
802 chosenStrikeIndex = strikeIndex;
803 break;
804 } else if (chosenPPEM < targetPPEM) {
805 // attempt to increase chosenPPEM
806 if (thisPPEM > chosenPPEM) {
807 chosenPPEM = thisPPEM;
808 chosenStrikeIndex = strikeIndex;
809 }
810 } else {
811 // attempt to decrease chosenPPEM, but not below targetPPEM
812 if (thisPPEM < chosenPPEM && thisPPEM > targetPPEM) {
813 chosenPPEM = thisPPEM;
814 chosenStrikeIndex = strikeIndex;
815 }
816 }
817 }
818 if (chosenStrikeIndex != -1) {
819 // use the chosen strike
820 FT_Error err = FT_Select_Size(face, chosenStrikeIndex);
821 if (err != 0) {
822 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x\n", face->family_name,
823 chosenStrikeIndex, err));
824 chosenStrikeIndex = -1;
825 }
826 }
827 return chosenStrikeIndex;
828}
829
reed@google.com0da48612013-03-19 16:06:52 +0000830SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
831 const SkDescriptor* desc)
832 : SkScalerContext_FreeType_Base(typeface, desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000833 SkAutoMutexAcquire ac(gFTMutex);
834
reed@android.com8a1c16f2008-12-17 15:59:43 +0000835 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000836 if (!InitFreetype()) {
837 sk_throw();
838 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000839 }
840 ++gFTCount;
841
842 // load the font file
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000843 fStrikeIndex = -1;
reed@android.com62900b42009-02-11 15:07:19 +0000844 fFTSize = NULL;
845 fFace = NULL;
reed@google.com2cdc6712013-03-21 18:22:00 +0000846 fFaceRec = ref_ft_face(typeface);
reed@android.com62900b42009-02-11 15:07:19 +0000847 if (NULL == fFaceRec) {
848 return;
849 }
850 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000851
852 // compute our factors from the record
853
854 SkMatrix m;
855
856 fRec.getSingleMatrix(&m);
857
858#ifdef DUMP_STRIKE_CREATION
859 SkString keyString;
860 SkFontHost::GetDescriptorKeyString(desc, &keyString);
861 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
862 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
863 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
864 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000865 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000866#endif
867
868 // now compute our scale factors
869 SkScalar sx = m.getScaleX();
870 SkScalar sy = m.getScaleY();
871
reed@google.comf073b332013-05-06 12:21:16 +0000872 fMatrix22Scalar.reset();
873
reed@android.com8a1c16f2008-12-17 15:59:43 +0000874 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
875 // sort of give up on hinting
876 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
877 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
878 sx = sy = SkScalarAve(sx, sy);
879
880 SkScalar inv = SkScalarInvert(sx);
881
882 // flip the skew elements to go from our Y-down system to FreeType's
883 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
884 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
885 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
886 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
skia.committer@gmail.come944de72013-05-07 07:01:03 +0000887
reed@google.comf073b332013-05-06 12:21:16 +0000888 fMatrix22Scalar.setScaleX(SkScalarMul(m.getScaleX(), inv));
889 fMatrix22Scalar.setSkewX(-SkScalarMul(m.getSkewX(), inv));
890 fMatrix22Scalar.setSkewY(-SkScalarMul(m.getSkewY(), inv));
891 fMatrix22Scalar.setScaleY(SkScalarMul(m.getScaleY(), inv));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000892 } else {
893 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
894 fMatrix22.xy = fMatrix22.yx = 0;
895 }
reed@google.comf073b332013-05-06 12:21:16 +0000896 fScale.set(sx, sy);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000897 fScaleX = SkScalarToFixed(sx);
898 fScaleY = SkScalarToFixed(sy);
899
reed@google.coma1bfa212012-03-08 21:57:12 +0000900 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
901
reed@android.com8a1c16f2008-12-17 15:59:43 +0000902 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000903 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000904 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000905 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000906
agl@chromium.org70a303f2010-05-10 14:15:50 +0000907 if (SkMask::kBW_Format == fRec.fMaskFormat) {
908 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
909 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000910 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000911 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000912 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000913 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000914 } else {
915 switch (fRec.getHinting()) {
916 case SkPaint::kNo_Hinting:
917 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000918 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000919 break;
920 case SkPaint::kSlight_Hinting:
921 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
922 break;
923 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000924 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000925 loadFlags = FT_LOAD_FORCE_AUTOHINT;
bungeman@google.comf6f56872014-01-23 19:01:36 +0000926 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000927 break;
928 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000929 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000930 loadFlags = FT_LOAD_FORCE_AUTOHINT;
931 break;
932 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000933 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000934 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000935 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000936 loadFlags = FT_LOAD_TARGET_LCD_V;
937 } else {
938 loadFlags = FT_LOAD_TARGET_LCD;
939 }
reed@google.comea2333d2011-03-14 16:44:56 +0000940 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000941 break;
942 default:
943 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
944 break;
945 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000946 }
947
reed@google.comeffc5012011-06-27 16:44:46 +0000948 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000949 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000950 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000951
reed@google.com96a9f7912011-05-06 11:49:30 +0000952 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
953 // advances, as fontconfig and cairo do.
954 // See http://code.google.com/p/skia/issues/detail?id=222.
955 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
956
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000957 // Use vertical layout if requested.
958 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
959 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
960 }
961
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000962 loadFlags |= FT_LOAD_COLOR;
963
reed@android.come4d0bc02009-07-24 19:53:20 +0000964 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000965 }
966
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000967 FT_Error err = FT_New_Size(fFace, &fFTSize);
968 if (err != 0) {
969 SkDEBUGF(("FT_New_Size returned %x for face %s\n", err, fFace->family_name));
970 fFace = NULL;
971 return;
972 }
973 err = FT_Activate_Size(fFTSize);
974 if (err != 0) {
975 SkDEBUGF(("FT_Activate_Size(%08x, 0x%x, 0x%x) returned 0x%x\n", fFace, fScaleX, fScaleY,
976 err));
977 fFTSize = NULL;
978 return;
979 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000980
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000981 if (FT_IS_SCALABLE(fFace)) {
982 err = FT_Set_Char_Size(fFace, SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000984 SkDEBUGF(("FT_Set_CharSize(%08x, 0x%x, 0x%x) returned 0x%x\n",
985 fFace, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000986 fFace = NULL;
987 return;
988 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000989 FT_Set_Transform(fFace, &fMatrix22, NULL);
990 } else if (FT_HAS_FIXED_SIZES(fFace)) {
991 fStrikeIndex = chooseBitmapStrike(fFace, fScaleY);
992 if (fStrikeIndex == -1) {
993 SkDEBUGF(("no glyphs for font \"%s\" size %f?\n",
994 fFace->family_name, SkFixedToScalar(fScaleY)));
995 } else {
996 // FreeType does no provide linear metrics for bitmap fonts.
997 linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000998
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000999 // FreeType documentation says:
1000 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
1001 // Bitmap-only fonts ignore this flag.
1002 //
1003 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
1004 // Force this flag off for bitmap only fonts.
1005 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001007 } else {
1008 SkDEBUGF(("unknown kind of font \"%s\" size %f?\n",
1009 fFace->family_name, SkFixedToScalar(fScaleY)));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001010 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001011
1012 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013}
1014
1015SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +00001016 SkAutoMutexAcquire ac(gFTMutex);
1017
reed@android.com8a1c16f2008-12-17 15:59:43 +00001018 if (fFTSize != NULL) {
1019 FT_Done_Size(fFTSize);
1020 }
1021
reed@android.com8a1c16f2008-12-17 15:59:43 +00001022 if (fFace != NULL) {
1023 unref_ft_face(fFace);
1024 }
1025 if (--gFTCount == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001026 FT_Done_FreeType(gFTLibrary);
1027 SkDEBUGCODE(gFTLibrary = NULL;)
1028 }
1029}
1030
1031/* We call this before each use of the fFace, since we may be sharing
1032 this face with other context (at different sizes).
1033*/
1034FT_Error SkScalerContext_FreeType::setupSize() {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001035 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001036 if (err != 0) {
1037 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001038 fFaceRec->fFontID, fScaleX, fScaleY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001039 fFTSize = NULL;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001040 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001041 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001042
1043 // seems we need to reset this every time (not sure why, but without it
1044 // I get random italics from some other fFTSize)
1045 FT_Set_Transform(fFace, &fMatrix22, NULL);
1046 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001047}
1048
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +00001049unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001050 return fFace->num_glyphs;
1051}
1052
1053uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
1054 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1055}
1056
reed@android.com9d3a9852010-01-08 14:07:42 +00001057SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
1058 // iterate through each cmap entry, looking for matching glyph indices
1059 FT_UInt glyphIndex;
1060 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1061
1062 while (glyphIndex != 0) {
1063 if (glyphIndex == glyph) {
1064 return charCode;
1065 }
1066 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1067 }
1068
1069 return 0;
1070}
1071
reed@android.com8a1c16f2008-12-17 15:59:43 +00001072void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
1073#ifdef FT_ADVANCES_H
1074 /* unhinted and light hinted text have linearly scaled advances
1075 * which are very cheap to compute with some font formats...
1076 */
reed@google.combdc99882011-11-21 14:36:57 +00001077 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001078 SkAutoMutexAcquire ac(gFTMutex);
1079
1080 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +00001081 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001082 return;
1083 }
1084
1085 FT_Error error;
1086 FT_Fixed advance;
1087
1088 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
1089 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1090 &advance );
1091 if (0 == error) {
1092 glyph->fRsbDelta = 0;
1093 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +00001094 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1095 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001096 return;
1097 }
1098 }
1099#endif /* FT_ADVANCES_H */
1100 /* otherwise, we need to load/hint the glyph, which is slower */
1101 this->generateMetrics(glyph);
1102 return;
1103}
1104
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001105void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1106 FT_BBox* bbox,
1107 bool snapToPixelBoundary) {
1108
1109 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1110
1111 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001112 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1113 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001114 // negate dy since freetype-y-goes-up and skia-y-goes-down
1115 bbox->xMin += dx;
1116 bbox->yMin -= dy;
1117 bbox->xMax += dx;
1118 bbox->yMax -= dy;
1119 }
1120
1121 // outset the box to integral boundaries
1122 if (snapToPixelBoundary) {
1123 bbox->xMin &= ~63;
1124 bbox->yMin &= ~63;
1125 bbox->xMax = (bbox->xMax + 63) & ~63;
1126 bbox->yMax = (bbox->yMax + 63) & ~63;
1127 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001128
1129 // Must come after snapToPixelBoundary so that the width and height are
1130 // consistent. Otherwise asserts will fire later on when generating the
1131 // glyph image.
1132 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1133 FT_Vector vector;
1134 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1135 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1136 FT_Vector_Transform(&vector, &fMatrix22);
1137 bbox->xMin += vector.x;
1138 bbox->xMax += vector.x;
1139 bbox->yMin += vector.y;
1140 bbox->yMax += vector.y;
1141 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001142}
1143
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001144bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1145 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
1146 if (!glyph_id)
1147 return false;
1148 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0)
1149 return false;
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001150 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001151 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1152 return true;
1153}
1154
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001155void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1156 if (isLCD(fRec)) {
1157 if (fLCDIsVert) {
1158 glyph->fHeight += gLCDExtra;
1159 glyph->fTop -= gLCDExtra >> 1;
1160 } else {
1161 glyph->fWidth += gLCDExtra;
1162 glyph->fLeft -= gLCDExtra >> 1;
1163 }
1164 }
1165}
1166
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001167inline void scaleGlyphMetrics(SkGlyph& glyph, SkScalar scale) {
1168 glyph.fWidth *= scale;
1169 glyph.fHeight *= scale;
1170 glyph.fTop *= scale;
1171 glyph.fLeft *= scale;
1172
1173 SkFixed fixedScale = SkScalarToFixed(scale);
1174 glyph.fAdvanceX = SkFixedMul(glyph.fAdvanceX, fixedScale);
1175 glyph.fAdvanceY = SkFixedMul(glyph.fAdvanceY, fixedScale);
1176}
1177
reed@android.com8a1c16f2008-12-17 15:59:43 +00001178void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1179 SkAutoMutexAcquire ac(gFTMutex);
1180
1181 glyph->fRsbDelta = 0;
1182 glyph->fLsbDelta = 0;
1183
1184 FT_Error err;
1185
1186 if (this->setupSize()) {
1187 goto ERROR;
1188 }
1189
1190 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1191 if (err != 0) {
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001192#if 0
1193 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%x) returned 0x%x\n",
reed@android.com8a1c16f2008-12-17 15:59:43 +00001194 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001195#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001196 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +00001197 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001198 return;
1199 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001200 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001201
1202 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001203 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001204 if (0 == fFace->glyph->outline.n_contours) {
1205 glyph->fWidth = 0;
1206 glyph->fHeight = 0;
1207 glyph->fTop = 0;
1208 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001209 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001210 FT_BBox bbox;
1211 getBBoxForCurrentGlyph(glyph, &bbox, true);
1212
1213 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1214 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1215 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1216 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1217
1218 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001219 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001220 break;
1221
1222 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001223 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1224 FT_Vector vector;
1225 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1226 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1227 FT_Vector_Transform(&vector, &fMatrix22);
1228 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1229 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1230 }
1231
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001232 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1233 glyph->fMaskFormat = SkMask::kARGB32_Format;
1234 }
1235
reed@android.com8a1c16f2008-12-17 15:59:43 +00001236 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1237 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1238 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1239 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1240 break;
1241
1242 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001243 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001244 goto ERROR;
1245 }
1246
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001247 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1248 if (fDoLinearMetrics) {
1249 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1250 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1251 } else {
1252 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1253 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1254 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001255 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001256 if (fDoLinearMetrics) {
1257 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1258 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1259 } else {
1260 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1261 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001262
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001263 if (fRec.fFlags & kDevKernText_Flag) {
1264 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1265 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001266 }
1267 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001268 }
1269
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001270 if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP && fScaleY && fFace->size->metrics.y_ppem) {
1271 // NOTE: both dimensions are scaled by y_ppem. this is WAI.
1272 scaleGlyphMetrics(*glyph, SkScalarDiv(SkFixedToScalar(fScaleY),
1273 SkIntToScalar(fFace->size->metrics.y_ppem)));
1274 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001275
reed@android.com8a1c16f2008-12-17 15:59:43 +00001276#ifdef ENABLE_GLYPH_SPEW
1277 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1278 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1279#endif
1280}
1281
reed@google.comea2333d2011-03-14 16:44:56 +00001282
bungeman@google.coma76de722012-10-26 19:35:54 +00001283void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001284 SkAutoMutexAcquire ac(gFTMutex);
1285
1286 FT_Error err;
1287
1288 if (this->setupSize()) {
1289 goto ERROR;
1290 }
1291
1292 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1293 if (err != 0) {
1294 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1295 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1296 ERROR:
1297 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1298 return;
1299 }
1300
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001301 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.coma76de722012-10-26 19:35:54 +00001302 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001303}
1304
reed@android.com8a1c16f2008-12-17 15:59:43 +00001305
1306void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1307 SkPath* path) {
1308 SkAutoMutexAcquire ac(gFTMutex);
1309
1310 SkASSERT(&glyph && path);
1311
1312 if (this->setupSize()) {
1313 path->reset();
1314 return;
1315 }
1316
1317 uint32_t flags = fLoadGlyphFlags;
1318 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1319 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1320
1321 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1322
1323 if (err != 0) {
1324 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1325 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1326 path->reset();
1327 return;
1328 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001329 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001331 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001332
1333 // The path's origin from FreeType is always the horizontal layout origin.
1334 // Offset the path so that it is relative to the vertical origin if needed.
1335 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1336 FT_Vector vector;
1337 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1338 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1339 FT_Vector_Transform(&vector, &fMatrix22);
1340 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1341 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001342}
1343
1344void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1345 SkPaint::FontMetrics* my) {
1346 if (NULL == mx && NULL == my) {
1347 return;
1348 }
1349
1350 SkAutoMutexAcquire ac(gFTMutex);
1351
1352 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001353 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001354 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001355 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001356 }
1357 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001358 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001359 }
1360 return;
1361 }
1362
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001363 FT_Face face = fFace;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001364 SkScalar scaleX = fScale.x();
reed@google.comf073b332013-05-06 12:21:16 +00001365 SkScalar scaleY = fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001366 SkScalar mxy = fMatrix22Scalar.getSkewX() * scaleY;
1367 SkScalar myy = fMatrix22Scalar.getScaleY() * scaleY;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001368
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001369 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1370 SkScalar upem = SkIntToScalar(face->units_per_EM);
1371 if (!upem) {
1372 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1373 if (ttHeader) {
1374 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001375 }
1376 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001378 // use the os/2 table as a source of reasonable defaults.
1379 SkScalar x_height = 0.0f;
1380 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001381 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001382 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1383 if (os2) {
1384 x_height = scaleX * SkIntToScalar(os2->sxHeight) / upem;
1385 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001386 if (os2->version != 0xFFFF && os2->version >= 2) {
1387 cap_height = scaleX * SkIntToScalar(os2->sCapHeight) / upem;
1388 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001389 }
1390
1391 // pull from format-specific metrics as needed
1392 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
1393 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
1394 ascent = -SkIntToScalar(face->ascender) / upem;
1395 descent = -SkIntToScalar(face->descender) / upem;
1396 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1397 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1398 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1399 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1400 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001401 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001402 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001403 FT_BBox bbox;
1404 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001405 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1406 }
1407 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001408 if (!cap_height) {
1409 FT_BBox bbox;
1410 if (getCBoxForLetter('H', &bbox)) {
1411 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1412 }
1413 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001414 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1415 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1416 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1417 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1418 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1419 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f))
1420 + ascent - descent;
1421 xmin = 0.0f;
1422 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1423 ymin = descent + leading;
1424 ymax = ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001425 } else {
1426 goto ERROR;
1427 }
1428
1429 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1430 if (!x_height) {
1431 x_height = -ascent;
1432 }
1433 if (!avgCharWidth) {
1434 avgCharWidth = xmax - xmin;
1435 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001436 if (!cap_height) {
1437 cap_height = -ascent;
1438 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001439
1440 // disallow negative linespacing
1441 if (leading < 0.0f) {
1442 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001443 }
1444
1445 if (mx) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001446 mx->fTop = ymax * mxy;
1447 mx->fAscent = ascent * mxy;
1448 mx->fDescent = descent * mxy;
1449 mx->fBottom = ymin * mxy;
1450 mx->fLeading = leading * mxy;
1451 mx->fAvgCharWidth = avgCharWidth * mxy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001452 mx->fXMin = xmin;
1453 mx->fXMax = xmax;
1454 mx->fXHeight = x_height;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001455 mx->fCapHeight = cap_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001456 }
1457 if (my) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001458 my->fTop = ymax * myy;
1459 my->fAscent = ascent * myy;
1460 my->fDescent = descent * myy;
1461 my->fBottom = ymin * myy;
1462 my->fLeading = leading * myy;
1463 my->fAvgCharWidth = avgCharWidth * myy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001464 my->fXMin = xmin;
1465 my->fXMax = xmax;
1466 my->fXHeight = x_height;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001467 my->fCapHeight = cap_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001468 }
1469}
1470
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001471void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1472{
1473 if (fRec.fFlags & SkScalerContext::kEmbolden_Flag) {
1474 switch ( glyph->format ) {
1475 case FT_GLYPH_FORMAT_OUTLINE:
1476 FT_Pos strength;
1477 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale) / 24;
1478 FT_Outline_Embolden(&glyph->outline, strength);
1479 break;
1480 case FT_GLYPH_FORMAT_BITMAP:
1481 FT_GlyphSlot_Own_Bitmap(glyph);
1482 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1483 break;
1484 default:
1485 SkDEBUGFAIL("unknown glyph format");
1486 }
1487 }
1488}
1489
reed@google.comb4162b12013-07-02 16:32:29 +00001490///////////////////////////////////////////////////////////////////////////////
1491
1492#include "SkUtils.h"
1493
1494static SkUnichar next_utf8(const void** chars) {
1495 return SkUTF8_NextUnichar((const char**)chars);
1496}
1497
1498static SkUnichar next_utf16(const void** chars) {
1499 return SkUTF16_NextUnichar((const uint16_t**)chars);
1500}
1501
1502static SkUnichar next_utf32(const void** chars) {
1503 const SkUnichar** uniChars = (const SkUnichar**)chars;
1504 SkUnichar uni = **uniChars;
1505 *uniChars += 1;
1506 return uni;
1507}
1508
1509typedef SkUnichar (*EncodingProc)(const void**);
1510
1511static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1512 static const EncodingProc gProcs[] = {
1513 next_utf8, next_utf16, next_utf32
1514 };
1515 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1516 return gProcs[enc];
1517}
1518
1519int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1520 uint16_t glyphs[], int glyphCount) const {
1521 AutoFTAccess fta(this);
1522 FT_Face face = fta.face();
1523 if (!face) {
1524 if (glyphs) {
1525 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1526 }
1527 return 0;
1528 }
1529
1530 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1531
1532 if (NULL == glyphs) {
1533 for (int i = 0; i < glyphCount; ++i) {
1534 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1535 return i;
1536 }
1537 }
1538 return glyphCount;
1539 } else {
1540 int first = glyphCount;
1541 for (int i = 0; i < glyphCount; ++i) {
1542 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1543 glyphs[i] = SkToU16(id);
1544 if (0 == id && i < first) {
1545 first = i;
1546 }
1547 }
1548 return first;
1549 }
1550}
1551
1552int SkTypeface_FreeType::onCountGlyphs() const {
1553 // we cache this value, using -1 as a sentinel for "not computed"
1554 if (fGlyphCount < 0) {
1555 AutoFTAccess fta(this);
1556 FT_Face face = fta.face();
1557 // if the face failed, we still assign a non-negative value
1558 fGlyphCount = face ? face->num_glyphs : 0;
1559 }
1560 return fGlyphCount;
1561}
1562
bungeman@google.com839702b2013-08-07 17:09:22 +00001563SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001564 SkTypeface::LocalizedStrings* nameIter =
1565 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1566 if (NULL == nameIter) {
1567 SkString familyName;
1568 this->getFamilyName(&familyName);
1569 SkString language("und"); //undetermined
1570 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1571 }
1572 return nameIter;
1573}
1574
bungeman@google.comddc218e2013-08-01 22:29:43 +00001575int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1576 AutoFTAccess fta(this);
1577 FT_Face face = fta.face();
1578
1579 FT_ULong tableCount = 0;
1580 FT_Error error;
1581
1582 // When 'tag' is NULL, returns number of tables in 'length'.
1583 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1584 if (error) {
1585 return 0;
1586 }
1587
1588 if (tags) {
1589 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1590 FT_ULong tableTag;
1591 FT_ULong tablelength;
1592 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1593 if (error) {
1594 return 0;
1595 }
1596 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1597 }
1598 }
1599 return tableCount;
1600}
1601
1602size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1603 size_t length, void* data) const
1604{
1605 AutoFTAccess fta(this);
1606 FT_Face face = fta.face();
1607
1608 FT_ULong tableLength = 0;
1609 FT_Error error;
1610
1611 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1612 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1613 if (error) {
1614 return 0;
1615 }
1616
1617 if (offset > tableLength) {
1618 return 0;
1619 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001620 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001621 if (NULL != data) {
1622 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1623 if (error) {
1624 return 0;
1625 }
1626 }
1627
1628 return size;
1629}
1630
reed@google.comb4162b12013-07-02 16:32:29 +00001631///////////////////////////////////////////////////////////////////////////////
1632///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001633
reed@android.com8a1c16f2008-12-17 15:59:43 +00001634/* Export this so that other parts of our FonttHost port can make use of our
1635 ability to extract the name+style from a stream, using FreeType's api.
1636*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001637bool find_name_and_attributes(SkStream* stream, SkString* name,
bungeman@google.comfe747652013-03-25 19:36:11 +00001638 SkTypeface::Style* style, bool* isFixedPitch) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001639 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001640 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001641 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001642 }
1643
1644 FT_Open_Args args;
1645 memset(&args, 0, sizeof(args));
1646
1647 const void* memoryBase = stream->getMemoryBase();
1648 FT_StreamRec streamRec;
1649
1650 if (NULL != memoryBase) {
1651 args.flags = FT_OPEN_MEMORY;
1652 args.memory_base = (const FT_Byte*)memoryBase;
1653 args.memory_size = stream->getLength();
1654 } else {
1655 memset(&streamRec, 0, sizeof(streamRec));
djsollen@google.com5dd45022013-03-21 13:30:54 +00001656 streamRec.size = stream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001657 streamRec.descriptor.pointer = stream;
1658 streamRec.read = sk_stream_read;
1659 streamRec.close = sk_stream_close;
1660
1661 args.flags = FT_OPEN_STREAM;
1662 args.stream = &streamRec;
1663 }
1664
1665 FT_Face face;
1666 if (FT_Open_Face(library, &args, 0, &face)) {
1667 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001668 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001669 }
1670
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001671 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001672 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001673 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001674 }
1675 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001676 tempStyle |= SkTypeface::kItalic;
1677 }
1678
1679 if (name) {
1680 name->set(face->family_name);
1681 }
1682 if (style) {
1683 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001684 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001685 if (isFixedPitch) {
1686 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001687 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001688
1689 FT_Done_Face(face);
1690 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001691 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001692}