blob: fd87a66dc6a8f8d9da40fb993c459e8d4e52a966 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
2/*
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
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"
bungeman@google.com3aacb412012-03-13 14:55:12 +000014#include "SkFloatingPoint.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000015#include "SkFontHost.h"
george@mozilla.comc59b5da2012-08-23 00:39:08 +000016#include "SkFontHost_FreeType_common.h"
bungeman@google.combbe50132012-07-24 20:33:21 +000017#include "SkGlyph.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000018#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000019#include "SkMaskGamma.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000020#include "SkOTUtils.h"
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +000021#include "SkAdvancedTypefaceMetrics.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000022#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000023#include "SkStream.h"
24#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000025#include "SkTemplates.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000026#include "SkThread.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027
bungeman@google.comfd668cf2012-08-24 17:46:11 +000028#if defined(SK_CAN_USE_DLOPEN)
29#include <dlfcn.h>
30#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000031#include <ft2build.h>
32#include FT_FREETYPE_H
33#include FT_OUTLINE_H
34#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000035#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000036#include FT_TYPE1_TABLES_H
agl@chromium.orge76073b2010-06-04 20:31:17 +000037#include FT_BITMAP_H
agl@chromium.org36bb6972010-06-04 20:57:16 +000038// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
39#include FT_SYNTHESIS_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000040#include FT_XFREE86_H
epoger@google.com5070d792011-06-29 20:43:14 +000041#ifdef FT_LCD_FILTER_H
agl@chromium.org309485b2009-07-21 17:41:32 +000042#include FT_LCD_FILTER_H
epoger@google.com5070d792011-06-29 20:43:14 +000043#endif
agl@chromium.org309485b2009-07-21 17:41:32 +000044
reed@android.com8a1c16f2008-12-17 15:59:43 +000045#ifdef FT_ADVANCES_H
46#include FT_ADVANCES_H
47#endif
48
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000049#if 0
50// Also include the files by name for build tools which require this.
51#include <freetype/freetype.h>
52#include <freetype/ftoutln.h>
53#include <freetype/ftsizes.h>
54#include <freetype/tttables.h>
55#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000056#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000057#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000058#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000059#endif
60
reed@android.com8a1c16f2008-12-17 15:59:43 +000061//#define ENABLE_GLYPH_SPEW // for tracing calls
62//#define DUMP_STRIKE_CREATION
63
reed@google.com1ac83502012-02-28 17:06:02 +000064//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000065
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000066using namespace skia_advanced_typeface_metrics_utils;
67
reed@google.comeffc5012011-06-27 16:44:46 +000068static bool isLCD(const SkScalerContext::Rec& rec) {
69 switch (rec.fMaskFormat) {
70 case SkMask::kLCD16_Format:
71 case SkMask::kLCD32_Format:
72 return true;
73 default:
74 return false;
75 }
76}
77
reed@android.com8a1c16f2008-12-17 15:59:43 +000078//////////////////////////////////////////////////////////////////////////
79
80struct SkFaceRec;
81
digit@google.com1771cbf2012-01-26 21:26:40 +000082SK_DECLARE_STATIC_MUTEX(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +000083static int gFTCount;
84static FT_Library gFTLibrary;
85static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000086static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
87static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@google.coma1c32562012-03-01 19:38:23 +000088static int gLCDExtra; // number of extra pixels for filtering.
reed@android.com8a1c16f2008-12-17 15:59:43 +000089
bungeman@google.com62566f32012-10-13 03:21:53 +000090/////////////////////////////////////////////////////////////////////////
91
bungeman@google.comfd668cf2012-08-24 17:46:11 +000092// FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
93// The following platforms provide FreeType of at least 2.4.0.
94// Ubuntu >= 11.04 (previous deprecated April 2013)
95// Debian >= 6.0 (good)
96// OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
97// Fedora >= 14 (good)
98// Android >= Gingerbread (good)
99typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
100
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000101// Caller must lock gFTMutex before calling this function.
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000102static bool InitFreetype() {
agl@chromium.org309485b2009-07-21 17:41:32 +0000103 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000104 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000105 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000106 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000107
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000108 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
epoger@google.comb371ed12011-06-29 21:20:52 +0000109#ifdef FT_LCD_FILTER_H
bungeman@google.com62566f32012-10-13 03:21:53 +0000110 // Use default { 0x10, 0x40, 0x70, 0x40, 0x10 }, as it adds up to 0x110, simulating ink spread.
111 // SetLcdFilter must be called before SetLcdFilterWeights.
112 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000113 if (0 == err) {
114 gLCDSupport = true;
115 gLCDExtra = 2; //Using a filter adds one full pixel to each side.
116
bungeman@google.com62566f32012-10-13 03:21:53 +0000117#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
118 // This also adds to 0x110 simulating ink spread, but provides better results than default.
119 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000120
121#if defined(SK_FONTHOST_FREETYPE_RUNTIME_VERSION) && \
122 SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
bungeman@google.com62566f32012-10-13 03:21:53 +0000123 err = FT_Library_SetLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000124#elif defined(SK_CAN_USE_DLOPEN) && SK_CAN_USE_DLOPEN == 1
125 //The FreeType library is already loaded, so symbols are available in process.
126 void* self = dlopen(NULL, RTLD_LAZY);
127 if (NULL != self) {
128 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
129 //The following cast is non-standard, but safe for POSIX.
130 *reinterpret_cast<void**>(&setLcdFilterWeights) = dlsym(self, "FT_Library_SetLcdFilterWeights");
131 dlclose(self);
132
133 if (NULL != setLcdFilterWeights) {
bungeman@google.com62566f32012-10-13 03:21:53 +0000134 err = setLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000135 }
136 }
137#endif
bungeman@google.com62566f32012-10-13 03:21:53 +0000138#endif
reed@google.coma1c32562012-03-01 19:38:23 +0000139 }
epoger@google.com5070d792011-06-29 20:43:14 +0000140#else
141 gLCDSupport = false;
142#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000143 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000144
145 return true;
146}
147
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000148// Lazy, once, wrapper to ask the FreeType Library if it can support LCD text
149static bool is_lcd_supported() {
150 if (!gLCDSupportValid) {
151 SkAutoMutexAcquire ac(gFTMutex);
152
153 if (!gLCDSupportValid) {
154 InitFreetype();
155 FT_Done_FreeType(gFTLibrary);
156 }
157 }
158 return gLCDSupport;
159}
160
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000161class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000162public:
reed@google.com0da48612013-03-19 16:06:52 +0000163 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000164 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000165
reed@android.com62900b42009-02-11 15:07:19 +0000166 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000167 return fFaceRec != NULL &&
168 fFTSize != NULL &&
169 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000170 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000171
172protected:
bungeman@google.coma76de722012-10-26 19:35:54 +0000173 virtual unsigned generateGlyphCount() SK_OVERRIDE;
174 virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE;
175 virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE;
176 virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE;
177 virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE;
178 virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000179 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
bungeman@google.coma76de722012-10-26 19:35:54 +0000180 SkPaint::FontMetrics* my) SK_OVERRIDE;
181 virtual SkUnichar generateGlyphToChar(uint16_t glyph) SK_OVERRIDE;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182
183private:
184 SkFaceRec* fFaceRec;
185 FT_Face fFace; // reference to shared face in gFaceRecHead
186 FT_Size fFTSize; // our own copy
187 SkFixed fScaleX, fScaleY;
188 FT_Matrix fMatrix22;
189 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000190 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000191 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000192
reed@google.comf073b332013-05-06 12:21:16 +0000193 // Need scalar versions for generateFontMetrics
194 SkVector fScale;
195 SkMatrix fMatrix22Scalar;
196
reed@android.com8a1c16f2008-12-17 15:59:43 +0000197 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000198 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
199 bool snapToPixelBoundary = false);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000200 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000201 void updateGlyphIfLCD(SkGlyph* glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000202};
203
204///////////////////////////////////////////////////////////////////////////
205///////////////////////////////////////////////////////////////////////////
206
reed@android.com8a1c16f2008-12-17 15:59:43 +0000207struct SkFaceRec {
208 SkFaceRec* fNext;
209 FT_Face fFace;
210 FT_StreamRec fFTStream;
211 SkStream* fSkStream;
212 uint32_t fRefCnt;
213 uint32_t fFontID;
214
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000215 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000216 SkFaceRec(SkStream* strm, uint32_t fontID);
217 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000218 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000219 }
220};
221
222extern "C" {
223 static unsigned long sk_stream_read(FT_Stream stream,
224 unsigned long offset,
225 unsigned char* buffer,
226 unsigned long count ) {
227 SkStream* str = (SkStream*)stream->descriptor.pointer;
228
229 if (count) {
230 if (!str->rewind()) {
231 return 0;
232 } else {
233 unsigned long ret;
234 if (offset) {
235 ret = str->read(NULL, offset);
236 if (ret != offset) {
237 return 0;
238 }
239 }
240 ret = str->read(buffer, count);
241 if (ret != count) {
242 return 0;
243 }
244 count = ret;
245 }
246 }
247 return count;
248 }
249
sugoi@google.com66a58ac2013-03-05 20:40:52 +0000250 static void sk_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000251}
252
253SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
vandebo@chromium.org9af25f32012-03-28 21:24:27 +0000254 : fNext(NULL), fSkStream(strm), fRefCnt(1), fFontID(fontID) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000255// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
256
reed@android.com4516f472009-06-29 16:25:36 +0000257 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000258 fFTStream.size = fSkStream->getLength();
259 fFTStream.descriptor.pointer = fSkStream;
260 fFTStream.read = sk_stream_read;
261 fFTStream.close = sk_stream_close;
262}
263
reed@android.com62900b42009-02-11 15:07:19 +0000264// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000265// Caller must lock gFTMutex before calling this function.
reed@google.com2cdc6712013-03-21 18:22:00 +0000266static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
267 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000268 SkFaceRec* rec = gFaceRecHead;
269 while (rec) {
270 if (rec->fFontID == fontID) {
271 SkASSERT(rec->fFace);
272 rec->fRefCnt += 1;
273 return rec;
274 }
275 rec = rec->fNext;
276 }
277
reed@google.com2cdc6712013-03-21 18:22:00 +0000278 int face_index;
279 SkStream* strm = typeface->openStream(&face_index);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000280 if (NULL == strm) {
reed@google.com2cdc6712013-03-21 18:22:00 +0000281 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000282 }
283
284 // this passes ownership of strm to the rec
285 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
286
287 FT_Open_Args args;
288 memset(&args, 0, sizeof(args));
289 const void* memoryBase = strm->getMemoryBase();
290
291 if (NULL != memoryBase) {
292//printf("mmap(%s)\n", keyString.c_str());
293 args.flags = FT_OPEN_MEMORY;
294 args.memory_base = (const FT_Byte*)memoryBase;
295 args.memory_size = strm->getLength();
296 } else {
297//printf("fopen(%s)\n", keyString.c_str());
298 args.flags = FT_OPEN_STREAM;
299 args.stream = &rec->fFTStream;
300 }
301
reed@google.com2cdc6712013-03-21 18:22:00 +0000302 FT_Error err = FT_Open_Face(gFTLibrary, &args, face_index, &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000303 if (err) { // bad filename, try the default font
304 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
305 SkDELETE(rec);
reed@google.com2cdc6712013-03-21 18:22:00 +0000306 return NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000307 } else {
308 SkASSERT(rec->fFace);
309 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
310 rec->fNext = gFaceRecHead;
311 gFaceRecHead = rec;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000312 return rec;
313 }
314}
315
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000316// Caller must lock gFTMutex before calling this function.
reed@android.com8a1c16f2008-12-17 15:59:43 +0000317static void unref_ft_face(FT_Face face) {
318 SkFaceRec* rec = gFaceRecHead;
319 SkFaceRec* prev = NULL;
320 while (rec) {
321 SkFaceRec* next = rec->fNext;
322 if (rec->fFace == face) {
323 if (--rec->fRefCnt == 0) {
324 if (prev) {
325 prev->fNext = next;
326 } else {
327 gFaceRecHead = next;
328 }
329 FT_Done_Face(face);
330 SkDELETE(rec);
331 }
332 return;
333 }
334 prev = rec;
335 rec = next;
336 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000337 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338}
339
reed@google.comb4162b12013-07-02 16:32:29 +0000340class AutoFTAccess {
341public:
342 AutoFTAccess(const SkTypeface* tf) : fRec(NULL), fFace(NULL) {
343 gFTMutex.acquire();
344 if (1 == ++gFTCount) {
345 if (!InitFreetype()) {
346 sk_throw();
347 }
348 }
349 fRec = ref_ft_face(tf);
350 if (fRec) {
351 fFace = fRec->fFace;
352 }
353 }
354
355 ~AutoFTAccess() {
356 if (fFace) {
357 unref_ft_face(fFace);
358 }
359 if (0 == --gFTCount) {
360 FT_Done_FreeType(gFTLibrary);
361 }
362 gFTMutex.release();
363 }
364
365 SkFaceRec* rec() { return fRec; }
366 FT_Face face() { return fFace; }
367
368private:
369 SkFaceRec* fRec;
370 FT_Face fFace;
371};
372
reed@android.com8a1c16f2008-12-17 15:59:43 +0000373///////////////////////////////////////////////////////////////////////////
374
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000375// Work around for old versions of freetype.
376static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
377 FT_Int32 loadFlags, FT_Fixed* advances) {
378#ifdef FT_ADVANCES_H
379 return FT_Get_Advances(face, start, count, loadFlags, advances);
380#else
381 if (!face || start >= face->num_glyphs ||
382 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
383 return 6; // "Invalid argument."
384 }
385 if (count == 0)
386 return 0;
387
388 for (int i = 0; i < count; i++) {
389 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
390 if (err)
391 return err;
392 advances[i] = face->glyph->advance.x;
393 }
394
395 return 0;
396#endif
397}
398
399static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000400#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000401 FT_UShort fsType = FT_Get_FSType_Flags(face);
402 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
403 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
404#else
405 // No embedding is 0x2 and bitmap embedding only is 0x200.
406 TT_OS2* os2_table;
407 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
408 return (os2_table->fsType & 0x202) == 0;
409 }
410 return false; // We tried, fail safe.
411#endif
412}
413
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000414static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
415 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
416 if (!glyph_id)
417 return false;
418 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
419 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
420 return true;
421}
422
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000423static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000424 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000425 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
426 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000427 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000428 SkASSERT(data);
429 *data = advance;
430 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000431}
432
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000433static void populate_glyph_to_unicode(FT_Face& face,
434 SkTDArray<SkUnichar>* glyphToUnicode) {
435 // Check and see if we have Unicode cmaps.
436 for (int i = 0; i < face->num_charmaps; ++i) {
437 // CMaps known to support Unicode:
438 // Platform ID Encoding ID Name
439 // ----------- ----------- -----------------------------------
440 // 0 0,1 Apple Unicode
441 // 0 3 Apple Unicode 2.0 (preferred)
442 // 3 1 Microsoft Unicode UCS-2
443 // 3 10 Microsoft Unicode UCS-4 (preferred)
444 //
445 // See Apple TrueType Reference Manual
446 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
447 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
448 // Microsoft OpenType Specification
449 // http://www.microsoft.com/typography/otspec/cmap.htm
450
451 FT_UShort platformId = face->charmaps[i]->platform_id;
452 FT_UShort encodingId = face->charmaps[i]->encoding_id;
453
454 if (platformId != 0 && platformId != 3) {
455 continue;
456 }
457 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
458 continue;
459 }
460 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
461 (platformId == 0 && encodingId == 3));
462
463 FT_Set_Charmap(face, face->charmaps[i]);
464 if (glyphToUnicode->isEmpty()) {
465 glyphToUnicode->setCount(face->num_glyphs);
466 memset(glyphToUnicode->begin(), 0,
467 sizeof(SkUnichar) * face->num_glyphs);
468 }
469
470 // Iterate through each cmap entry.
471 FT_UInt glyphIndex;
472 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
473 glyphIndex != 0;
474 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
475 if (charCode &&
476 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
477 (*glyphToUnicode)[glyphIndex] = charCode;
478 }
479 }
480 }
481}
482
reed@google.com2689f612013-03-20 20:01:47 +0000483SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000484 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
485 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000486 uint32_t glyphIDsCount) const {
djsollen@google.comda957722011-11-16 17:00:46 +0000487#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000488 return NULL;
489#else
reed@google.comb4162b12013-07-02 16:32:29 +0000490 AutoFTAccess fta(this);
491 FT_Face face = fta.face();
492 if (!face) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000493 return NULL;
reed@google.comb4162b12013-07-02 16:32:29 +0000494 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000495
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000496 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
497 info->fFontName.set(FT_Get_Postscript_Name(face));
498 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
499 info->fLastGlyphID = face->num_glyphs - 1;
500 info->fEmSize = 1000;
501
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000502 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000503 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000504 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000505 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000506 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000507 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000508 cid = true;
509 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000510 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000511 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000512 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000513 cid = true;
514 TT_Header* ttHeader;
515 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
516 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000517 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000518 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000519 } else {
520 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000522
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000523 info->fStyle = 0;
524 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000525 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000526 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000527 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000528
529 PS_FontInfoRec ps_info;
530 TT_Postscript* tt_info;
531 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
532 info->fItalicAngle = ps_info.italic_angle;
533 } else if ((tt_info =
534 (TT_Postscript*)FT_Get_Sfnt_Table(face,
535 ft_sfnt_post)) != NULL) {
536 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
537 } else {
538 info->fItalicAngle = 0;
539 }
540
541 info->fAscent = face->ascender;
542 info->fDescent = face->descender;
543
544 // Figure out a good guess for StemV - Min width of i, I, !, 1.
545 // This probably isn't very good with an italic font.
546 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000547 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000548 char stem_chars[] = {'i', 'I', '!', '1'};
549 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
550 FT_BBox bbox;
551 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
552 int16_t width = bbox.xMax - bbox.xMin;
553 if (width > 0 && width < min_width) {
554 min_width = width;
555 info->fStemV = min_width;
556 }
557 }
558 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000559
560 TT_PCLT* pclt_info;
561 TT_OS2* os2_table;
562 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
563 info->fCapHeight = pclt_info->CapHeight;
564 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
565 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000566 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000567 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000568 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000569 } else if ((os2_table =
570 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
571 info->fCapHeight = os2_table->sCapHeight;
572 } else {
573 // Figure out a good guess for CapHeight: average the height of M and X.
574 FT_BBox m_bbox, x_bbox;
575 bool got_m, got_x;
576 got_m = GetLetterCBox(face, 'M', &m_bbox);
577 got_x = GetLetterCBox(face, 'X', &x_bbox);
578 if (got_m && got_x) {
579 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
580 x_bbox.yMin) / 2;
581 } else if (got_m && !got_x) {
582 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
583 } else if (!got_m && got_x) {
584 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
585 }
586 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000587
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000588 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
589 face->bbox.xMax, face->bbox.yMin);
590
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000591 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000592 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
593 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
594 }
595
596 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000597 if (FT_IS_FIXED_WIDTH(face)) {
598 appendRange(&info->fGlyphWidths, 0);
599 int16_t advance = face->max_advance_width;
600 info->fGlyphWidths->fAdvance.append(1, &advance);
601 finishRange(info->fGlyphWidths.get(), 0,
602 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000603 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000604 appendRange(&info->fGlyphWidths, 0);
605 // So as to not blow out the stack, get advances in batches.
606 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
607 FT_Fixed advances[128];
608 int advanceCount = 128;
609 if (gID + advanceCount > face->num_glyphs)
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000610 advanceCount = face->num_glyphs - gID;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000611 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
612 advances);
613 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000614 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000615 info->fGlyphWidths->fAdvance.append(1, &advance);
616 }
617 }
618 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
619 SkAdvancedTypefaceMetrics::WidthRange::kRange);
620 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000621 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000622 getAdvanceData(face,
623 face->num_glyphs,
624 glyphIDs,
625 glyphIDsCount,
626 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000627 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000628 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000629
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000630 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
631 FT_HAS_VERTICAL(face)) {
632 SkASSERT(false); // Not implemented yet.
633 }
634
635 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
636 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
637 // Postscript fonts may contain more than 255 glyphs, so we end up
638 // using multiple font descriptions with a glyph ordering. Record
639 // the name of each glyph.
640 info->fGlyphNames.reset(
641 new SkAutoTArray<SkString>(face->num_glyphs));
642 for (int gID = 0; gID < face->num_glyphs; gID++) {
643 char glyphName[128]; // PS limit for names is 127 bytes.
644 FT_Get_Glyph_Name(face, gID, glyphName, 128);
645 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000646 }
647 }
648
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000649 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
650 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
651 face->num_charmaps) {
652 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
653 }
654
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000655 if (!canEmbed(face))
656 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
657
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000658 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000659#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000660}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000661
reed@google.com618ef5e2011-01-26 22:10:41 +0000662///////////////////////////////////////////////////////////////////////////
663
reed@google.comffe49f52011-11-22 19:42:41 +0000664#define BLACK_LUMINANCE_LIMIT 0x40
665#define WHITE_LUMINANCE_LIMIT 0xA0
666
reed@google.com8ed436c2011-07-21 14:12:36 +0000667static bool bothZero(SkScalar a, SkScalar b) {
668 return 0 == a && 0 == b;
669}
670
671// returns false if there is any non-90-rotation or skew
672static bool isAxisAligned(const SkScalerContext::Rec& rec) {
673 return 0 == rec.fPreSkewX &&
674 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
675 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
676}
677
reed@google.com0da48612013-03-19 16:06:52 +0000678SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
679 const SkDescriptor* desc) const {
680 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
681 (const_cast<SkTypeface_FreeType*>(this),
682 desc));
683 if (!c->success()) {
684 SkDELETE(c);
685 c = NULL;
686 }
687 return c;
688}
689
690void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000691 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
692 //Cap the requested size as larger sizes give bogus values.
693 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000694 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000695 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000696 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000697
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000698 if (!is_lcd_supported() && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000699 // If the runtime Freetype library doesn't support LCD mode, we disable
700 // it here.
701 rec->fMaskFormat = SkMask::kA8_Format;
702 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000703
reed@google.com618ef5e2011-01-26 22:10:41 +0000704 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000705 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000706 // collapse full->normal hinting if we're not doing LCD
707 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000708 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000709 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000710 if (SkPaint::kNo_Hinting != h) {
711 h = SkPaint::kSlight_Hinting;
712 }
713 }
714
reed@google.com8ed436c2011-07-21 14:12:36 +0000715 // rotated text looks bad with hinting, so we disable it as needed
716 if (!isAxisAligned(*rec)) {
717 h = SkPaint::kNo_Hinting;
718 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000719 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000720
bungeman@google.com97efada2012-07-30 20:40:50 +0000721#ifndef SK_GAMMA_APPLY_TO_A8
722 if (!isLCD(*rec)) {
723 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000724 }
reed@google.com1ac83502012-02-28 17:06:02 +0000725#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000726}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000727
reed@google.com38c37dd2013-03-21 15:36:26 +0000728int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000729 AutoFTAccess fta(this);
730 FT_Face face = fta.face();
731 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000732}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000733
reed@google.com35fe7372013-10-30 15:07:03 +0000734bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
735 int count, int32_t adjustments[]) const {
736 AutoFTAccess fta(this);
737 FT_Face face = fta.face();
738 if (!face || !FT_HAS_KERNING(face)) {
739 return false;
740 }
741
742 for (int i = 0; i < count - 1; ++i) {
743 FT_Vector delta;
744 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
745 FT_KERNING_UNSCALED, &delta);
746 if (err) {
747 return false;
748 }
749 adjustments[i] = delta.x;
750 }
751 return true;
752}
753
reed@google.com0da48612013-03-19 16:06:52 +0000754SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
755 const SkDescriptor* desc)
756 : SkScalerContext_FreeType_Base(typeface, desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000757 SkAutoMutexAcquire ac(gFTMutex);
758
reed@android.com8a1c16f2008-12-17 15:59:43 +0000759 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000760 if (!InitFreetype()) {
761 sk_throw();
762 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000763 }
764 ++gFTCount;
765
766 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000767 fFTSize = NULL;
768 fFace = NULL;
reed@google.com2cdc6712013-03-21 18:22:00 +0000769 fFaceRec = ref_ft_face(typeface);
reed@android.com62900b42009-02-11 15:07:19 +0000770 if (NULL == fFaceRec) {
771 return;
772 }
773 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000774
775 // compute our factors from the record
776
777 SkMatrix m;
778
779 fRec.getSingleMatrix(&m);
780
781#ifdef DUMP_STRIKE_CREATION
782 SkString keyString;
783 SkFontHost::GetDescriptorKeyString(desc, &keyString);
784 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
785 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
786 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
787 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000788 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000789#endif
790
791 // now compute our scale factors
792 SkScalar sx = m.getScaleX();
793 SkScalar sy = m.getScaleY();
794
reed@google.comf073b332013-05-06 12:21:16 +0000795 fMatrix22Scalar.reset();
796
reed@android.com8a1c16f2008-12-17 15:59:43 +0000797 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
798 // sort of give up on hinting
799 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
800 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
801 sx = sy = SkScalarAve(sx, sy);
802
803 SkScalar inv = SkScalarInvert(sx);
804
805 // flip the skew elements to go from our Y-down system to FreeType's
806 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
807 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
808 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
809 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
skia.committer@gmail.come944de72013-05-07 07:01:03 +0000810
reed@google.comf073b332013-05-06 12:21:16 +0000811 fMatrix22Scalar.setScaleX(SkScalarMul(m.getScaleX(), inv));
812 fMatrix22Scalar.setSkewX(-SkScalarMul(m.getSkewX(), inv));
813 fMatrix22Scalar.setSkewY(-SkScalarMul(m.getSkewY(), inv));
814 fMatrix22Scalar.setScaleY(SkScalarMul(m.getScaleY(), inv));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000815 } else {
816 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
817 fMatrix22.xy = fMatrix22.yx = 0;
818 }
reed@google.comf073b332013-05-06 12:21:16 +0000819 fScale.set(sx, sy);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820 fScaleX = SkScalarToFixed(sx);
821 fScaleY = SkScalarToFixed(sy);
822
reed@google.coma1bfa212012-03-08 21:57:12 +0000823 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
824
reed@android.com8a1c16f2008-12-17 15:59:43 +0000825 // compute the flags we send to Load_Glyph
826 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000827 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
bungeman@google.com34f10262012-03-23 18:11:47 +0000828 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000829
agl@chromium.org70a303f2010-05-10 14:15:50 +0000830 if (SkMask::kBW_Format == fRec.fMaskFormat) {
831 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
832 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000833 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000834 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000835 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000836 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000837 } else {
838 switch (fRec.getHinting()) {
839 case SkPaint::kNo_Hinting:
840 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000841 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000842 break;
843 case SkPaint::kSlight_Hinting:
844 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
845 break;
846 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000847 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
848 loadFlags = FT_LOAD_FORCE_AUTOHINT;
849 else
850 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000851 break;
852 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000853 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
854 loadFlags = FT_LOAD_FORCE_AUTOHINT;
855 break;
856 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000857 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000858 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000859 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000860 loadFlags = FT_LOAD_TARGET_LCD_V;
861 } else {
862 loadFlags = FT_LOAD_TARGET_LCD;
863 }
reed@google.comea2333d2011-03-14 16:44:56 +0000864 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000865 break;
866 default:
867 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
868 break;
869 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000870 }
871
reed@google.comeffc5012011-06-27 16:44:46 +0000872 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000873 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000874 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000875
reed@google.com96a9f7912011-05-06 11:49:30 +0000876 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
877 // advances, as fontconfig and cairo do.
878 // See http://code.google.com/p/skia/issues/detail?id=222.
879 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
880
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000881 // Use vertical layout if requested.
882 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
883 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
884 }
885
reed@android.come4d0bc02009-07-24 19:53:20 +0000886 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000887 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000888 }
889
890 // now create the FT_Size
891
892 {
893 FT_Error err;
894
895 err = FT_New_Size(fFace, &fFTSize);
896 if (err != 0) {
897 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
898 fFaceRec->fFontID, fScaleX, fScaleY, err));
899 fFace = NULL;
900 return;
901 }
902
903 err = FT_Activate_Size(fFTSize);
904 if (err != 0) {
905 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
906 fFaceRec->fFontID, fScaleX, fScaleY, err));
907 fFTSize = NULL;
908 }
909
910 err = FT_Set_Char_Size( fFace,
911 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
912 72, 72);
913 if (err != 0) {
914 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
915 fFaceRec->fFontID, fScaleX, fScaleY, err));
916 fFace = NULL;
917 return;
918 }
919
920 FT_Set_Transform( fFace, &fMatrix22, NULL);
921 }
922}
923
924SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000925 SkAutoMutexAcquire ac(gFTMutex);
926
reed@android.com8a1c16f2008-12-17 15:59:43 +0000927 if (fFTSize != NULL) {
928 FT_Done_Size(fFTSize);
929 }
930
reed@android.com8a1c16f2008-12-17 15:59:43 +0000931 if (fFace != NULL) {
932 unref_ft_face(fFace);
933 }
934 if (--gFTCount == 0) {
935// SkDEBUGF(("FT_Done_FreeType\n"));
936 FT_Done_FreeType(gFTLibrary);
937 SkDEBUGCODE(gFTLibrary = NULL;)
938 }
939}
940
941/* We call this before each use of the fFace, since we may be sharing
942 this face with other context (at different sizes).
943*/
944FT_Error SkScalerContext_FreeType::setupSize() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000945 FT_Error err = FT_Activate_Size(fFTSize);
946
947 if (err != 0) {
948 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
949 fFaceRec->fFontID, fScaleX, fScaleY, err));
950 fFTSize = NULL;
951 } else {
952 // seems we need to reset this every time (not sure why, but without it
953 // I get random italics from some other fFTSize)
954 FT_Set_Transform( fFace, &fMatrix22, NULL);
955 }
956 return err;
957}
958
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000959unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960 return fFace->num_glyphs;
961}
962
963uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
964 return SkToU16(FT_Get_Char_Index( fFace, uni ));
965}
966
reed@android.com9d3a9852010-01-08 14:07:42 +0000967SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
968 // iterate through each cmap entry, looking for matching glyph indices
969 FT_UInt glyphIndex;
970 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
971
972 while (glyphIndex != 0) {
973 if (glyphIndex == glyph) {
974 return charCode;
975 }
976 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
977 }
978
979 return 0;
980}
981
reed@android.com8a1c16f2008-12-17 15:59:43 +0000982void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
983#ifdef FT_ADVANCES_H
984 /* unhinted and light hinted text have linearly scaled advances
985 * which are very cheap to compute with some font formats...
986 */
reed@google.combdc99882011-11-21 14:36:57 +0000987 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000988 SkAutoMutexAcquire ac(gFTMutex);
989
990 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000991 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000992 return;
993 }
994
995 FT_Error error;
996 FT_Fixed advance;
997
998 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
999 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1000 &advance );
1001 if (0 == error) {
1002 glyph->fRsbDelta = 0;
1003 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +00001004 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1005 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006 return;
1007 }
1008 }
1009#endif /* FT_ADVANCES_H */
1010 /* otherwise, we need to load/hint the glyph, which is slower */
1011 this->generateMetrics(glyph);
1012 return;
1013}
1014
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001015void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1016 FT_BBox* bbox,
1017 bool snapToPixelBoundary) {
1018
1019 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1020
1021 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001022 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1023 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001024 // negate dy since freetype-y-goes-up and skia-y-goes-down
1025 bbox->xMin += dx;
1026 bbox->yMin -= dy;
1027 bbox->xMax += dx;
1028 bbox->yMax -= dy;
1029 }
1030
1031 // outset the box to integral boundaries
1032 if (snapToPixelBoundary) {
1033 bbox->xMin &= ~63;
1034 bbox->yMin &= ~63;
1035 bbox->xMax = (bbox->xMax + 63) & ~63;
1036 bbox->yMax = (bbox->yMax + 63) & ~63;
1037 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001038
1039 // Must come after snapToPixelBoundary so that the width and height are
1040 // consistent. Otherwise asserts will fire later on when generating the
1041 // glyph image.
1042 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1043 FT_Vector vector;
1044 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1045 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1046 FT_Vector_Transform(&vector, &fMatrix22);
1047 bbox->xMin += vector.x;
1048 bbox->xMax += vector.x;
1049 bbox->yMin += vector.y;
1050 bbox->yMax += vector.y;
1051 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001052}
1053
1054void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1055 if (isLCD(fRec)) {
1056 if (fLCDIsVert) {
1057 glyph->fHeight += gLCDExtra;
1058 glyph->fTop -= gLCDExtra >> 1;
1059 } else {
1060 glyph->fWidth += gLCDExtra;
1061 glyph->fLeft -= gLCDExtra >> 1;
1062 }
1063 }
1064}
1065
reed@android.com8a1c16f2008-12-17 15:59:43 +00001066void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1067 SkAutoMutexAcquire ac(gFTMutex);
1068
1069 glyph->fRsbDelta = 0;
1070 glyph->fLsbDelta = 0;
1071
1072 FT_Error err;
1073
1074 if (this->setupSize()) {
1075 goto ERROR;
1076 }
1077
1078 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1079 if (err != 0) {
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001080#if 0
1081 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%x) returned 0x%x\n",
reed@android.com8a1c16f2008-12-17 15:59:43 +00001082 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001083#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001084 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +00001085 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001086 return;
1087 }
1088
1089 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +00001090 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001091 FT_BBox bbox;
1092
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001093 if (0 == fFace->glyph->outline.n_contours) {
1094 glyph->fWidth = 0;
1095 glyph->fHeight = 0;
1096 glyph->fTop = 0;
1097 glyph->fLeft = 0;
1098 break;
1099 }
1100
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001101 if (fRec.fFlags & kEmbolden_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001102 emboldenOutline(fFace, &fFace->glyph->outline);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001103 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001104
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001105 getBBoxForCurrentGlyph(glyph, &bbox, true);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001106
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001107 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1108 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1109 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1110 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001111
1112 updateGlyphIfLCD(glyph);
1113
reed@android.com8a1c16f2008-12-17 15:59:43 +00001114 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001115 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001116
1117 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001118 if (fRec.fFlags & kEmbolden_Flag) {
1119 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1120 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1121 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001122
1123 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1124 FT_Vector vector;
1125 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1126 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1127 FT_Vector_Transform(&vector, &fMatrix22);
1128 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1129 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1130 }
1131
reed@android.com8a1c16f2008-12-17 15:59:43 +00001132 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1133 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1134 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1135 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1136 break;
1137
1138 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001139 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001140 goto ERROR;
1141 }
1142
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001143 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1144 if (fDoLinearMetrics) {
1145 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1146 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1147 } else {
1148 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1149 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1150 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001151 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001152 if (fDoLinearMetrics) {
1153 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1154 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1155 } else {
1156 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1157 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001158
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001159 if (fRec.fFlags & kDevKernText_Flag) {
1160 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1161 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001162 }
1163 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001164 }
1165
1166
reed@android.com8a1c16f2008-12-17 15:59:43 +00001167#ifdef ENABLE_GLYPH_SPEW
1168 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1169 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1170#endif
1171}
1172
reed@google.comea2333d2011-03-14 16:44:56 +00001173
bungeman@google.coma76de722012-10-26 19:35:54 +00001174void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001175 SkAutoMutexAcquire ac(gFTMutex);
1176
1177 FT_Error err;
1178
1179 if (this->setupSize()) {
1180 goto ERROR;
1181 }
1182
1183 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1184 if (err != 0) {
1185 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1186 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1187 ERROR:
1188 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1189 return;
1190 }
1191
bungeman@google.coma76de722012-10-26 19:35:54 +00001192 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193}
1194
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195
1196void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1197 SkPath* path) {
1198 SkAutoMutexAcquire ac(gFTMutex);
1199
1200 SkASSERT(&glyph && path);
1201
1202 if (this->setupSize()) {
1203 path->reset();
1204 return;
1205 }
1206
1207 uint32_t flags = fLoadGlyphFlags;
1208 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1209 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1210
1211 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1212
1213 if (err != 0) {
1214 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1215 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1216 path->reset();
1217 return;
1218 }
1219
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001220 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001221
1222 // The path's origin from FreeType is always the horizontal layout origin.
1223 // Offset the path so that it is relative to the vertical origin if needed.
1224 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1225 FT_Vector vector;
1226 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1227 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1228 FT_Vector_Transform(&vector, &fMatrix22);
1229 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1230 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001231}
1232
1233void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1234 SkPaint::FontMetrics* my) {
1235 if (NULL == mx && NULL == my) {
1236 return;
1237 }
1238
1239 SkAutoMutexAcquire ac(gFTMutex);
1240
1241 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001242 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001243 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001244 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001245 }
1246 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001247 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001248 }
1249 return;
1250 }
1251
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001252 FT_Face face = fFace;
1253 int upem = face->units_per_EM;
1254 if (upem <= 0) {
1255 goto ERROR;
1256 }
1257
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001258 SkPoint pts[6];
1259 SkFixed ys[6];
reed@google.comf073b332013-05-06 12:21:16 +00001260 SkScalar scaleY = fScale.y();
1261 SkScalar mxy = fMatrix22Scalar.getSkewX();
1262 SkScalar myy = fMatrix22Scalar.getScaleY();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001263 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1264 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001265
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001266 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001267 if (leading < 0) {
1268 leading = 0;
1269 }
1270
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001271 // Try to get the OS/2 table from the font. This contains the specific
1272 // average font width metrics which Windows uses.
1273 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1274
reed@android.com8a1c16f2008-12-17 15:59:43 +00001275 ys[0] = -face->bbox.yMax;
1276 ys[1] = -face->ascender;
1277 ys[2] = -face->descender;
1278 ys[3] = -face->bbox.yMin;
1279 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001280 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1281
1282 SkScalar x_height;
1283 if (os2 && os2->sxHeight) {
reed@google.comf073b332013-05-06 12:21:16 +00001284 x_height = fScale.x() * os2->sxHeight / upem;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001285 } else {
1286 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1287 if (x_glyph) {
1288 FT_BBox bbox;
1289 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001290 if (fRec.fFlags & kEmbolden_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001291 emboldenOutline(fFace, &fFace->glyph->outline);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001292 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001293 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
reed@google.comf073b332013-05-06 12:21:16 +00001294 x_height = bbox.yMax / 64.0f;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001295 } else {
1296 x_height = 0;
1297 }
1298 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001299
1300 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001301 for (int i = 0; i < 6; i++) {
reed@google.comf073b332013-05-06 12:21:16 +00001302 SkScalar y = scaleY * ys[i] / upem;
1303 pts[i].set(y * mxy, y * myy);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001304 }
1305
1306 if (mx) {
1307 mx->fTop = pts[0].fX;
1308 mx->fAscent = pts[1].fX;
1309 mx->fDescent = pts[2].fX;
1310 mx->fBottom = pts[3].fX;
1311 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001312 mx->fAvgCharWidth = pts[5].fX;
1313 mx->fXMin = xmin;
1314 mx->fXMax = xmax;
1315 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001316 }
1317 if (my) {
1318 my->fTop = pts[0].fY;
1319 my->fAscent = pts[1].fY;
1320 my->fDescent = pts[2].fY;
1321 my->fBottom = pts[3].fY;
1322 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001323 my->fAvgCharWidth = pts[5].fY;
1324 my->fXMin = xmin;
1325 my->fXMax = xmax;
1326 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001327 }
1328}
1329
reed@google.comb4162b12013-07-02 16:32:29 +00001330///////////////////////////////////////////////////////////////////////////////
1331
1332#include "SkUtils.h"
1333
1334static SkUnichar next_utf8(const void** chars) {
1335 return SkUTF8_NextUnichar((const char**)chars);
1336}
1337
1338static SkUnichar next_utf16(const void** chars) {
1339 return SkUTF16_NextUnichar((const uint16_t**)chars);
1340}
1341
1342static SkUnichar next_utf32(const void** chars) {
1343 const SkUnichar** uniChars = (const SkUnichar**)chars;
1344 SkUnichar uni = **uniChars;
1345 *uniChars += 1;
1346 return uni;
1347}
1348
1349typedef SkUnichar (*EncodingProc)(const void**);
1350
1351static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1352 static const EncodingProc gProcs[] = {
1353 next_utf8, next_utf16, next_utf32
1354 };
1355 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1356 return gProcs[enc];
1357}
1358
1359int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1360 uint16_t glyphs[], int glyphCount) const {
1361 AutoFTAccess fta(this);
1362 FT_Face face = fta.face();
1363 if (!face) {
1364 if (glyphs) {
1365 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1366 }
1367 return 0;
1368 }
1369
1370 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1371
1372 if (NULL == glyphs) {
1373 for (int i = 0; i < glyphCount; ++i) {
1374 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1375 return i;
1376 }
1377 }
1378 return glyphCount;
1379 } else {
1380 int first = glyphCount;
1381 for (int i = 0; i < glyphCount; ++i) {
1382 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1383 glyphs[i] = SkToU16(id);
1384 if (0 == id && i < first) {
1385 first = i;
1386 }
1387 }
1388 return first;
1389 }
1390}
1391
1392int SkTypeface_FreeType::onCountGlyphs() const {
1393 // we cache this value, using -1 as a sentinel for "not computed"
1394 if (fGlyphCount < 0) {
1395 AutoFTAccess fta(this);
1396 FT_Face face = fta.face();
1397 // if the face failed, we still assign a non-negative value
1398 fGlyphCount = face ? face->num_glyphs : 0;
1399 }
1400 return fGlyphCount;
1401}
1402
bungeman@google.com839702b2013-08-07 17:09:22 +00001403SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001404 SkTypeface::LocalizedStrings* nameIter =
1405 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1406 if (NULL == nameIter) {
1407 SkString familyName;
1408 this->getFamilyName(&familyName);
1409 SkString language("und"); //undetermined
1410 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1411 }
1412 return nameIter;
1413}
1414
bungeman@google.comddc218e2013-08-01 22:29:43 +00001415int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1416 AutoFTAccess fta(this);
1417 FT_Face face = fta.face();
1418
1419 FT_ULong tableCount = 0;
1420 FT_Error error;
1421
1422 // When 'tag' is NULL, returns number of tables in 'length'.
1423 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1424 if (error) {
1425 return 0;
1426 }
1427
1428 if (tags) {
1429 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1430 FT_ULong tableTag;
1431 FT_ULong tablelength;
1432 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1433 if (error) {
1434 return 0;
1435 }
1436 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1437 }
1438 }
1439 return tableCount;
1440}
1441
1442size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1443 size_t length, void* data) const
1444{
1445 AutoFTAccess fta(this);
1446 FT_Face face = fta.face();
1447
1448 FT_ULong tableLength = 0;
1449 FT_Error error;
1450
1451 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1452 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1453 if (error) {
1454 return 0;
1455 }
1456
1457 if (offset > tableLength) {
1458 return 0;
1459 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001460 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001461 if (NULL != data) {
1462 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1463 if (error) {
1464 return 0;
1465 }
1466 }
1467
1468 return size;
1469}
1470
reed@google.comb4162b12013-07-02 16:32:29 +00001471///////////////////////////////////////////////////////////////////////////////
1472///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001473
reed@android.com8a1c16f2008-12-17 15:59:43 +00001474/* Export this so that other parts of our FonttHost port can make use of our
1475 ability to extract the name+style from a stream, using FreeType's api.
1476*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001477bool find_name_and_attributes(SkStream* stream, SkString* name,
bungeman@google.comfe747652013-03-25 19:36:11 +00001478 SkTypeface::Style* style, bool* isFixedPitch) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001479 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001480 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001481 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001482 }
1483
1484 FT_Open_Args args;
1485 memset(&args, 0, sizeof(args));
1486
1487 const void* memoryBase = stream->getMemoryBase();
1488 FT_StreamRec streamRec;
1489
1490 if (NULL != memoryBase) {
1491 args.flags = FT_OPEN_MEMORY;
1492 args.memory_base = (const FT_Byte*)memoryBase;
1493 args.memory_size = stream->getLength();
1494 } else {
1495 memset(&streamRec, 0, sizeof(streamRec));
djsollen@google.com5dd45022013-03-21 13:30:54 +00001496 streamRec.size = stream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001497 streamRec.descriptor.pointer = stream;
1498 streamRec.read = sk_stream_read;
1499 streamRec.close = sk_stream_close;
1500
1501 args.flags = FT_OPEN_STREAM;
1502 args.stream = &streamRec;
1503 }
1504
1505 FT_Face face;
1506 if (FT_Open_Face(library, &args, 0, &face)) {
1507 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001508 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001509 }
1510
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001511 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001512 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001513 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001514 }
1515 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001516 tempStyle |= SkTypeface::kItalic;
1517 }
1518
1519 if (name) {
1520 name->set(face->family_name);
1521 }
1522 if (style) {
1523 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001524 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001525 if (isFixedPitch) {
1526 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001527 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001528
1529 FT_Done_Face(face);
1530 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001531 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001532}