blob: eb2f28a59dd8567f0fc71e970cc80620ed6830ba [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 }
519 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000520
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521 info->fStyle = 0;
522 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000523 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000524 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000525 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000526
527 PS_FontInfoRec ps_info;
528 TT_Postscript* tt_info;
529 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
530 info->fItalicAngle = ps_info.italic_angle;
531 } else if ((tt_info =
532 (TT_Postscript*)FT_Get_Sfnt_Table(face,
533 ft_sfnt_post)) != NULL) {
534 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
535 } else {
536 info->fItalicAngle = 0;
537 }
538
539 info->fAscent = face->ascender;
540 info->fDescent = face->descender;
541
542 // Figure out a good guess for StemV - Min width of i, I, !, 1.
543 // This probably isn't very good with an italic font.
544 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000545 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000546 char stem_chars[] = {'i', 'I', '!', '1'};
547 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
548 FT_BBox bbox;
549 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
550 int16_t width = bbox.xMax - bbox.xMin;
551 if (width > 0 && width < min_width) {
552 min_width = width;
553 info->fStemV = min_width;
554 }
555 }
556 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000557
558 TT_PCLT* pclt_info;
559 TT_OS2* os2_table;
560 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
561 info->fCapHeight = pclt_info->CapHeight;
562 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
563 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000564 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000565 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000566 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000567 } else if ((os2_table =
568 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
569 info->fCapHeight = os2_table->sCapHeight;
570 } else {
571 // Figure out a good guess for CapHeight: average the height of M and X.
572 FT_BBox m_bbox, x_bbox;
573 bool got_m, got_x;
574 got_m = GetLetterCBox(face, 'M', &m_bbox);
575 got_x = GetLetterCBox(face, 'X', &x_bbox);
576 if (got_m && got_x) {
577 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
578 x_bbox.yMin) / 2;
579 } else if (got_m && !got_x) {
580 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
581 } else if (!got_m && got_x) {
582 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
583 }
584 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000585
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000586 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
587 face->bbox.xMax, face->bbox.yMin);
588
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000589 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000590 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
591 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
592 }
593
594 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000595 if (FT_IS_FIXED_WIDTH(face)) {
596 appendRange(&info->fGlyphWidths, 0);
597 int16_t advance = face->max_advance_width;
598 info->fGlyphWidths->fAdvance.append(1, &advance);
599 finishRange(info->fGlyphWidths.get(), 0,
600 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000601 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000602 appendRange(&info->fGlyphWidths, 0);
603 // So as to not blow out the stack, get advances in batches.
604 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
605 FT_Fixed advances[128];
606 int advanceCount = 128;
607 if (gID + advanceCount > face->num_glyphs)
bungeman@google.comb8aa4dd2013-10-15 18:50:00 +0000608 advanceCount = face->num_glyphs - gID;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000609 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
610 advances);
611 for (int i = 0; i < advanceCount; i++) {
vandebo@chromium.orgce8a1952012-10-22 20:09:31 +0000612 int16_t advance = advances[i];
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000613 info->fGlyphWidths->fAdvance.append(1, &advance);
614 }
615 }
616 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
617 SkAdvancedTypefaceMetrics::WidthRange::kRange);
618 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000619 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000620 getAdvanceData(face,
621 face->num_glyphs,
622 glyphIDs,
623 glyphIDsCount,
624 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000625 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000626 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000627
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000628 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
629 FT_HAS_VERTICAL(face)) {
630 SkASSERT(false); // Not implemented yet.
631 }
632
633 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
634 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
635 // Postscript fonts may contain more than 255 glyphs, so we end up
636 // using multiple font descriptions with a glyph ordering. Record
637 // the name of each glyph.
638 info->fGlyphNames.reset(
639 new SkAutoTArray<SkString>(face->num_glyphs));
640 for (int gID = 0; gID < face->num_glyphs; gID++) {
641 char glyphName[128]; // PS limit for names is 127 bytes.
642 FT_Get_Glyph_Name(face, gID, glyphName, 128);
643 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000644 }
645 }
646
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000647 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
648 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
649 face->num_charmaps) {
650 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
651 }
652
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000653 if (!canEmbed(face))
654 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
655
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000656 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000657#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000658}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000659
reed@google.com618ef5e2011-01-26 22:10:41 +0000660///////////////////////////////////////////////////////////////////////////
661
reed@google.comffe49f52011-11-22 19:42:41 +0000662#define BLACK_LUMINANCE_LIMIT 0x40
663#define WHITE_LUMINANCE_LIMIT 0xA0
664
reed@google.com8ed436c2011-07-21 14:12:36 +0000665static bool bothZero(SkScalar a, SkScalar b) {
666 return 0 == a && 0 == b;
667}
668
669// returns false if there is any non-90-rotation or skew
670static bool isAxisAligned(const SkScalerContext::Rec& rec) {
671 return 0 == rec.fPreSkewX &&
672 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
673 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
674}
675
reed@google.com0da48612013-03-19 16:06:52 +0000676SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
677 const SkDescriptor* desc) const {
678 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
679 (const_cast<SkTypeface_FreeType*>(this),
680 desc));
681 if (!c->success()) {
682 SkDELETE(c);
683 c = NULL;
684 }
685 return c;
686}
687
688void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000689 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
690 //Cap the requested size as larger sizes give bogus values.
691 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungeman@google.com5582e632012-04-02 14:51:54 +0000692 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000693 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000694 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000695
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000696 if (!is_lcd_supported() && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000697 // If the runtime Freetype library doesn't support LCD mode, we disable
698 // it here.
699 rec->fMaskFormat = SkMask::kA8_Format;
700 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000701
reed@google.com618ef5e2011-01-26 22:10:41 +0000702 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000703 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000704 // collapse full->normal hinting if we're not doing LCD
705 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000706 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000707 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000708 if (SkPaint::kNo_Hinting != h) {
709 h = SkPaint::kSlight_Hinting;
710 }
711 }
712
reed@google.com8ed436c2011-07-21 14:12:36 +0000713 // rotated text looks bad with hinting, so we disable it as needed
714 if (!isAxisAligned(*rec)) {
715 h = SkPaint::kNo_Hinting;
716 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000717 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000718
bungeman@google.com97efada2012-07-30 20:40:50 +0000719#ifndef SK_GAMMA_APPLY_TO_A8
720 if (!isLCD(*rec)) {
721 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000722 }
reed@google.com1ac83502012-02-28 17:06:02 +0000723#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000724}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000725
reed@google.com38c37dd2013-03-21 15:36:26 +0000726int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000727 AutoFTAccess fta(this);
728 FT_Face face = fta.face();
729 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000730}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000731
reed@google.com0da48612013-03-19 16:06:52 +0000732SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
733 const SkDescriptor* desc)
734 : SkScalerContext_FreeType_Base(typeface, desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000735 SkAutoMutexAcquire ac(gFTMutex);
736
reed@android.com8a1c16f2008-12-17 15:59:43 +0000737 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000738 if (!InitFreetype()) {
739 sk_throw();
740 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000741 }
742 ++gFTCount;
743
744 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000745 fFTSize = NULL;
746 fFace = NULL;
reed@google.com2cdc6712013-03-21 18:22:00 +0000747 fFaceRec = ref_ft_face(typeface);
reed@android.com62900b42009-02-11 15:07:19 +0000748 if (NULL == fFaceRec) {
749 return;
750 }
751 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000752
753 // compute our factors from the record
754
755 SkMatrix m;
756
757 fRec.getSingleMatrix(&m);
758
759#ifdef DUMP_STRIKE_CREATION
760 SkString keyString;
761 SkFontHost::GetDescriptorKeyString(desc, &keyString);
762 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
763 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
764 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
765 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000766 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000767#endif
768
769 // now compute our scale factors
770 SkScalar sx = m.getScaleX();
771 SkScalar sy = m.getScaleY();
772
reed@google.comf073b332013-05-06 12:21:16 +0000773 fMatrix22Scalar.reset();
774
reed@android.com8a1c16f2008-12-17 15:59:43 +0000775 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
776 // sort of give up on hinting
777 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
778 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
779 sx = sy = SkScalarAve(sx, sy);
780
781 SkScalar inv = SkScalarInvert(sx);
782
783 // flip the skew elements to go from our Y-down system to FreeType's
784 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
785 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
786 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
787 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
skia.committer@gmail.come944de72013-05-07 07:01:03 +0000788
reed@google.comf073b332013-05-06 12:21:16 +0000789 fMatrix22Scalar.setScaleX(SkScalarMul(m.getScaleX(), inv));
790 fMatrix22Scalar.setSkewX(-SkScalarMul(m.getSkewX(), inv));
791 fMatrix22Scalar.setSkewY(-SkScalarMul(m.getSkewY(), inv));
792 fMatrix22Scalar.setScaleY(SkScalarMul(m.getScaleY(), inv));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000793 } else {
794 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
795 fMatrix22.xy = fMatrix22.yx = 0;
796 }
reed@google.comf073b332013-05-06 12:21:16 +0000797 fScale.set(sx, sy);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000798 fScaleX = SkScalarToFixed(sx);
799 fScaleY = SkScalarToFixed(sy);
800
reed@google.coma1bfa212012-03-08 21:57:12 +0000801 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
802
reed@android.com8a1c16f2008-12-17 15:59:43 +0000803 // compute the flags we send to Load_Glyph
804 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000805 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
bungeman@google.com34f10262012-03-23 18:11:47 +0000806 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000807
agl@chromium.org70a303f2010-05-10 14:15:50 +0000808 if (SkMask::kBW_Format == fRec.fMaskFormat) {
809 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
810 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000811 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000812 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000813 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000814 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000815 } else {
816 switch (fRec.getHinting()) {
817 case SkPaint::kNo_Hinting:
818 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000819 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000820 break;
821 case SkPaint::kSlight_Hinting:
822 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
823 break;
824 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000825 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
826 loadFlags = FT_LOAD_FORCE_AUTOHINT;
827 else
828 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000829 break;
830 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000831 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
832 loadFlags = FT_LOAD_FORCE_AUTOHINT;
833 break;
834 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000835 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000836 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000837 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000838 loadFlags = FT_LOAD_TARGET_LCD_V;
839 } else {
840 loadFlags = FT_LOAD_TARGET_LCD;
841 }
reed@google.comea2333d2011-03-14 16:44:56 +0000842 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000843 break;
844 default:
845 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
846 break;
847 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000848 }
849
reed@google.comeffc5012011-06-27 16:44:46 +0000850 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000851 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000852 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000853
reed@google.com96a9f7912011-05-06 11:49:30 +0000854 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
855 // advances, as fontconfig and cairo do.
856 // See http://code.google.com/p/skia/issues/detail?id=222.
857 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
858
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000859 // Use vertical layout if requested.
860 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
861 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
862 }
863
reed@android.come4d0bc02009-07-24 19:53:20 +0000864 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000865 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000866 }
867
868 // now create the FT_Size
869
870 {
871 FT_Error err;
872
873 err = FT_New_Size(fFace, &fFTSize);
874 if (err != 0) {
875 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
876 fFaceRec->fFontID, fScaleX, fScaleY, err));
877 fFace = NULL;
878 return;
879 }
880
881 err = FT_Activate_Size(fFTSize);
882 if (err != 0) {
883 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
884 fFaceRec->fFontID, fScaleX, fScaleY, err));
885 fFTSize = NULL;
886 }
887
888 err = FT_Set_Char_Size( fFace,
889 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
890 72, 72);
891 if (err != 0) {
892 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
893 fFaceRec->fFontID, fScaleX, fScaleY, err));
894 fFace = NULL;
895 return;
896 }
897
898 FT_Set_Transform( fFace, &fMatrix22, NULL);
899 }
900}
901
902SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000903 SkAutoMutexAcquire ac(gFTMutex);
904
reed@android.com8a1c16f2008-12-17 15:59:43 +0000905 if (fFTSize != NULL) {
906 FT_Done_Size(fFTSize);
907 }
908
reed@android.com8a1c16f2008-12-17 15:59:43 +0000909 if (fFace != NULL) {
910 unref_ft_face(fFace);
911 }
912 if (--gFTCount == 0) {
913// SkDEBUGF(("FT_Done_FreeType\n"));
914 FT_Done_FreeType(gFTLibrary);
915 SkDEBUGCODE(gFTLibrary = NULL;)
916 }
917}
918
919/* We call this before each use of the fFace, since we may be sharing
920 this face with other context (at different sizes).
921*/
922FT_Error SkScalerContext_FreeType::setupSize() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000923 FT_Error err = FT_Activate_Size(fFTSize);
924
925 if (err != 0) {
926 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
927 fFaceRec->fFontID, fScaleX, fScaleY, err));
928 fFTSize = NULL;
929 } else {
930 // seems we need to reset this every time (not sure why, but without it
931 // I get random italics from some other fFTSize)
932 FT_Set_Transform( fFace, &fMatrix22, NULL);
933 }
934 return err;
935}
936
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000937unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000938 return fFace->num_glyphs;
939}
940
941uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
942 return SkToU16(FT_Get_Char_Index( fFace, uni ));
943}
944
reed@android.com9d3a9852010-01-08 14:07:42 +0000945SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
946 // iterate through each cmap entry, looking for matching glyph indices
947 FT_UInt glyphIndex;
948 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
949
950 while (glyphIndex != 0) {
951 if (glyphIndex == glyph) {
952 return charCode;
953 }
954 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
955 }
956
957 return 0;
958}
959
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
961#ifdef FT_ADVANCES_H
962 /* unhinted and light hinted text have linearly scaled advances
963 * which are very cheap to compute with some font formats...
964 */
reed@google.combdc99882011-11-21 14:36:57 +0000965 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000966 SkAutoMutexAcquire ac(gFTMutex);
967
968 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000969 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000970 return;
971 }
972
973 FT_Error error;
974 FT_Fixed advance;
975
976 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
977 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
978 &advance );
979 if (0 == error) {
980 glyph->fRsbDelta = 0;
981 glyph->fLsbDelta = 0;
reed@google.comd074c372012-07-18 13:45:58 +0000982 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
983 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000984 return;
985 }
986 }
987#endif /* FT_ADVANCES_H */
988 /* otherwise, we need to load/hint the glyph, which is slower */
989 this->generateMetrics(glyph);
990 return;
991}
992
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000993void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
994 FT_BBox* bbox,
995 bool snapToPixelBoundary) {
996
997 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
998
999 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001000 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1001 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001002 // negate dy since freetype-y-goes-up and skia-y-goes-down
1003 bbox->xMin += dx;
1004 bbox->yMin -= dy;
1005 bbox->xMax += dx;
1006 bbox->yMax -= dy;
1007 }
1008
1009 // outset the box to integral boundaries
1010 if (snapToPixelBoundary) {
1011 bbox->xMin &= ~63;
1012 bbox->yMin &= ~63;
1013 bbox->xMax = (bbox->xMax + 63) & ~63;
1014 bbox->yMax = (bbox->yMax + 63) & ~63;
1015 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001016
1017 // Must come after snapToPixelBoundary so that the width and height are
1018 // consistent. Otherwise asserts will fire later on when generating the
1019 // glyph image.
1020 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1021 FT_Vector vector;
1022 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1023 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1024 FT_Vector_Transform(&vector, &fMatrix22);
1025 bbox->xMin += vector.x;
1026 bbox->xMax += vector.x;
1027 bbox->yMin += vector.y;
1028 bbox->yMax += vector.y;
1029 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001030}
1031
1032void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1033 if (isLCD(fRec)) {
1034 if (fLCDIsVert) {
1035 glyph->fHeight += gLCDExtra;
1036 glyph->fTop -= gLCDExtra >> 1;
1037 } else {
1038 glyph->fWidth += gLCDExtra;
1039 glyph->fLeft -= gLCDExtra >> 1;
1040 }
1041 }
1042}
1043
reed@android.com8a1c16f2008-12-17 15:59:43 +00001044void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1045 SkAutoMutexAcquire ac(gFTMutex);
1046
1047 glyph->fRsbDelta = 0;
1048 glyph->fLsbDelta = 0;
1049
1050 FT_Error err;
1051
1052 if (this->setupSize()) {
1053 goto ERROR;
1054 }
1055
1056 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1057 if (err != 0) {
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001058#if 0
1059 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%x) returned 0x%x\n",
reed@android.com8a1c16f2008-12-17 15:59:43 +00001060 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
mike@reedtribe.org7a722f02012-11-15 02:12:14 +00001061#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001062 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +00001063 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001064 return;
1065 }
1066
1067 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +00001068 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001069 FT_BBox bbox;
1070
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001071 if (0 == fFace->glyph->outline.n_contours) {
1072 glyph->fWidth = 0;
1073 glyph->fHeight = 0;
1074 glyph->fTop = 0;
1075 glyph->fLeft = 0;
1076 break;
1077 }
1078
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001079 if (fRec.fFlags & kEmbolden_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001080 emboldenOutline(fFace, &fFace->glyph->outline);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001081 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001082
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001083 getBBoxForCurrentGlyph(glyph, &bbox, true);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001084
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001085 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1086 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1087 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1088 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001089
1090 updateGlyphIfLCD(glyph);
1091
reed@android.com8a1c16f2008-12-17 15:59:43 +00001092 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001093 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001094
1095 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001096 if (fRec.fFlags & kEmbolden_Flag) {
1097 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1098 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1099 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001100
1101 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1102 FT_Vector vector;
1103 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1104 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1105 FT_Vector_Transform(&vector, &fMatrix22);
1106 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1107 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1108 }
1109
reed@android.com8a1c16f2008-12-17 15:59:43 +00001110 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1111 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1112 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1113 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1114 break;
1115
1116 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001117 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001118 goto ERROR;
1119 }
1120
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001121 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1122 if (fDoLinearMetrics) {
1123 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1124 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1125 } else {
1126 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1127 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1128 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001129 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001130 if (fDoLinearMetrics) {
1131 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1132 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1133 } else {
1134 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1135 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001136
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001137 if (fRec.fFlags & kDevKernText_Flag) {
1138 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1139 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001140 }
1141 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001142 }
1143
1144
reed@android.com8a1c16f2008-12-17 15:59:43 +00001145#ifdef ENABLE_GLYPH_SPEW
1146 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1147 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1148#endif
1149}
1150
reed@google.comea2333d2011-03-14 16:44:56 +00001151
bungeman@google.coma76de722012-10-26 19:35:54 +00001152void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001153 SkAutoMutexAcquire ac(gFTMutex);
1154
1155 FT_Error err;
1156
1157 if (this->setupSize()) {
1158 goto ERROR;
1159 }
1160
1161 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1162 if (err != 0) {
1163 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1164 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1165 ERROR:
1166 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1167 return;
1168 }
1169
bungeman@google.coma76de722012-10-26 19:35:54 +00001170 generateGlyphImage(fFace, glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001171}
1172
reed@android.com8a1c16f2008-12-17 15:59:43 +00001173
1174void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1175 SkPath* path) {
1176 SkAutoMutexAcquire ac(gFTMutex);
1177
1178 SkASSERT(&glyph && path);
1179
1180 if (this->setupSize()) {
1181 path->reset();
1182 return;
1183 }
1184
1185 uint32_t flags = fLoadGlyphFlags;
1186 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1187 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1188
1189 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1190
1191 if (err != 0) {
1192 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1193 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1194 path->reset();
1195 return;
1196 }
1197
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001198 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001199
1200 // The path's origin from FreeType is always the horizontal layout origin.
1201 // Offset the path so that it is relative to the vertical origin if needed.
1202 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1203 FT_Vector vector;
1204 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1205 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1206 FT_Vector_Transform(&vector, &fMatrix22);
1207 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1208 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001209}
1210
1211void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1212 SkPaint::FontMetrics* my) {
1213 if (NULL == mx && NULL == my) {
1214 return;
1215 }
1216
1217 SkAutoMutexAcquire ac(gFTMutex);
1218
1219 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001220 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001221 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001222 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001223 }
1224 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001225 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001226 }
1227 return;
1228 }
1229
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001230 FT_Face face = fFace;
1231 int upem = face->units_per_EM;
1232 if (upem <= 0) {
1233 goto ERROR;
1234 }
1235
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001236 SkPoint pts[6];
1237 SkFixed ys[6];
reed@google.comf073b332013-05-06 12:21:16 +00001238 SkScalar scaleY = fScale.y();
1239 SkScalar mxy = fMatrix22Scalar.getSkewX();
1240 SkScalar myy = fMatrix22Scalar.getScaleY();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001241 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1242 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001243
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001244 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001245 if (leading < 0) {
1246 leading = 0;
1247 }
1248
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001249 // Try to get the OS/2 table from the font. This contains the specific
1250 // average font width metrics which Windows uses.
1251 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1252
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253 ys[0] = -face->bbox.yMax;
1254 ys[1] = -face->ascender;
1255 ys[2] = -face->descender;
1256 ys[3] = -face->bbox.yMin;
1257 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001258 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1259
1260 SkScalar x_height;
1261 if (os2 && os2->sxHeight) {
reed@google.comf073b332013-05-06 12:21:16 +00001262 x_height = fScale.x() * os2->sxHeight / upem;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001263 } else {
1264 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1265 if (x_glyph) {
1266 FT_BBox bbox;
1267 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001268 if (fRec.fFlags & kEmbolden_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001269 emboldenOutline(fFace, &fFace->glyph->outline);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001270 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001271 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
reed@google.comf073b332013-05-06 12:21:16 +00001272 x_height = bbox.yMax / 64.0f;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001273 } else {
1274 x_height = 0;
1275 }
1276 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001277
1278 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001279 for (int i = 0; i < 6; i++) {
reed@google.comf073b332013-05-06 12:21:16 +00001280 SkScalar y = scaleY * ys[i] / upem;
1281 pts[i].set(y * mxy, y * myy);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001282 }
1283
1284 if (mx) {
1285 mx->fTop = pts[0].fX;
1286 mx->fAscent = pts[1].fX;
1287 mx->fDescent = pts[2].fX;
1288 mx->fBottom = pts[3].fX;
1289 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001290 mx->fAvgCharWidth = pts[5].fX;
1291 mx->fXMin = xmin;
1292 mx->fXMax = xmax;
1293 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001294 }
1295 if (my) {
1296 my->fTop = pts[0].fY;
1297 my->fAscent = pts[1].fY;
1298 my->fDescent = pts[2].fY;
1299 my->fBottom = pts[3].fY;
1300 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001301 my->fAvgCharWidth = pts[5].fY;
1302 my->fXMin = xmin;
1303 my->fXMax = xmax;
1304 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001305 }
1306}
1307
reed@google.comb4162b12013-07-02 16:32:29 +00001308///////////////////////////////////////////////////////////////////////////////
1309
1310#include "SkUtils.h"
1311
1312static SkUnichar next_utf8(const void** chars) {
1313 return SkUTF8_NextUnichar((const char**)chars);
1314}
1315
1316static SkUnichar next_utf16(const void** chars) {
1317 return SkUTF16_NextUnichar((const uint16_t**)chars);
1318}
1319
1320static SkUnichar next_utf32(const void** chars) {
1321 const SkUnichar** uniChars = (const SkUnichar**)chars;
1322 SkUnichar uni = **uniChars;
1323 *uniChars += 1;
1324 return uni;
1325}
1326
1327typedef SkUnichar (*EncodingProc)(const void**);
1328
1329static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1330 static const EncodingProc gProcs[] = {
1331 next_utf8, next_utf16, next_utf32
1332 };
1333 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1334 return gProcs[enc];
1335}
1336
1337int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1338 uint16_t glyphs[], int glyphCount) const {
1339 AutoFTAccess fta(this);
1340 FT_Face face = fta.face();
1341 if (!face) {
1342 if (glyphs) {
1343 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1344 }
1345 return 0;
1346 }
1347
1348 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1349
1350 if (NULL == glyphs) {
1351 for (int i = 0; i < glyphCount; ++i) {
1352 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1353 return i;
1354 }
1355 }
1356 return glyphCount;
1357 } else {
1358 int first = glyphCount;
1359 for (int i = 0; i < glyphCount; ++i) {
1360 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1361 glyphs[i] = SkToU16(id);
1362 if (0 == id && i < first) {
1363 first = i;
1364 }
1365 }
1366 return first;
1367 }
1368}
1369
1370int SkTypeface_FreeType::onCountGlyphs() const {
1371 // we cache this value, using -1 as a sentinel for "not computed"
1372 if (fGlyphCount < 0) {
1373 AutoFTAccess fta(this);
1374 FT_Face face = fta.face();
1375 // if the face failed, we still assign a non-negative value
1376 fGlyphCount = face ? face->num_glyphs : 0;
1377 }
1378 return fGlyphCount;
1379}
1380
bungeman@google.com839702b2013-08-07 17:09:22 +00001381SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001382 SkTypeface::LocalizedStrings* nameIter =
1383 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1384 if (NULL == nameIter) {
1385 SkString familyName;
1386 this->getFamilyName(&familyName);
1387 SkString language("und"); //undetermined
1388 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1389 }
1390 return nameIter;
1391}
1392
bungeman@google.comddc218e2013-08-01 22:29:43 +00001393int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1394 AutoFTAccess fta(this);
1395 FT_Face face = fta.face();
1396
1397 FT_ULong tableCount = 0;
1398 FT_Error error;
1399
1400 // When 'tag' is NULL, returns number of tables in 'length'.
1401 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1402 if (error) {
1403 return 0;
1404 }
1405
1406 if (tags) {
1407 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1408 FT_ULong tableTag;
1409 FT_ULong tablelength;
1410 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1411 if (error) {
1412 return 0;
1413 }
1414 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1415 }
1416 }
1417 return tableCount;
1418}
1419
1420size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1421 size_t length, void* data) const
1422{
1423 AutoFTAccess fta(this);
1424 FT_Face face = fta.face();
1425
1426 FT_ULong tableLength = 0;
1427 FT_Error error;
1428
1429 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1430 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1431 if (error) {
1432 return 0;
1433 }
1434
1435 if (offset > tableLength) {
1436 return 0;
1437 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001438 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001439 if (NULL != data) {
1440 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1441 if (error) {
1442 return 0;
1443 }
1444 }
1445
1446 return size;
1447}
1448
reed@google.comb4162b12013-07-02 16:32:29 +00001449///////////////////////////////////////////////////////////////////////////////
1450///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001451
reed@android.com8a1c16f2008-12-17 15:59:43 +00001452/* Export this so that other parts of our FonttHost port can make use of our
1453 ability to extract the name+style from a stream, using FreeType's api.
1454*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001455bool find_name_and_attributes(SkStream* stream, SkString* name,
bungeman@google.comfe747652013-03-25 19:36:11 +00001456 SkTypeface::Style* style, bool* isFixedPitch) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001457 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001458 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001459 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001460 }
1461
1462 FT_Open_Args args;
1463 memset(&args, 0, sizeof(args));
1464
1465 const void* memoryBase = stream->getMemoryBase();
1466 FT_StreamRec streamRec;
1467
1468 if (NULL != memoryBase) {
1469 args.flags = FT_OPEN_MEMORY;
1470 args.memory_base = (const FT_Byte*)memoryBase;
1471 args.memory_size = stream->getLength();
1472 } else {
1473 memset(&streamRec, 0, sizeof(streamRec));
djsollen@google.com5dd45022013-03-21 13:30:54 +00001474 streamRec.size = stream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001475 streamRec.descriptor.pointer = stream;
1476 streamRec.read = sk_stream_read;
1477 streamRec.close = sk_stream_close;
1478
1479 args.flags = FT_OPEN_STREAM;
1480 args.stream = &streamRec;
1481 }
1482
1483 FT_Face face;
1484 if (FT_Open_Face(library, &args, 0, &face)) {
1485 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001486 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001487 }
1488
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001489 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001490 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001491 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001492 }
1493 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001494 tempStyle |= SkTypeface::kItalic;
1495 }
1496
1497 if (name) {
1498 name->set(face->family_name);
1499 }
1500 if (style) {
1501 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001502 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001503 if (isFixedPitch) {
1504 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001505 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001506
1507 FT_Done_Face(face);
1508 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001509 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001510}