blob: 61efb958ba68a1e090c4de6c3c27286e63318b77 [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
reed@android.com8a1c16f2008-12-17 15:59:43 +000010#include "SkBitmap.h"
11#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000012#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000013#include "SkDescriptor.h"
14#include "SkFDot6.h"
15#include "SkFontHost.h"
16#include "SkMask.h"
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +000017#include "SkAdvancedTypefaceMetrics.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000018#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000019#include "SkStream.h"
20#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000021#include "SkTemplates.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000022#include "SkThread.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000023
24#include <ft2build.h>
25#include FT_FREETYPE_H
26#include FT_OUTLINE_H
27#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000028#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000029#include FT_TYPE1_TABLES_H
agl@chromium.orge76073b2010-06-04 20:31:17 +000030#include FT_BITMAP_H
agl@chromium.org36bb6972010-06-04 20:57:16 +000031// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
32#include FT_SYNTHESIS_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000033#include FT_XFREE86_H
epoger@google.com5070d792011-06-29 20:43:14 +000034#ifdef FT_LCD_FILTER_H
agl@chromium.org309485b2009-07-21 17:41:32 +000035#include FT_LCD_FILTER_H
epoger@google.com5070d792011-06-29 20:43:14 +000036#endif
agl@chromium.org309485b2009-07-21 17:41:32 +000037
reed@android.com8a1c16f2008-12-17 15:59:43 +000038#ifdef FT_ADVANCES_H
39#include FT_ADVANCES_H
40#endif
41
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000042#if 0
43// Also include the files by name for build tools which require this.
44#include <freetype/freetype.h>
45#include <freetype/ftoutln.h>
46#include <freetype/ftsizes.h>
47#include <freetype/tttables.h>
48#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000049#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000050#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000051#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000052#endif
53
reed@android.com8a1c16f2008-12-17 15:59:43 +000054//#define ENABLE_GLYPH_SPEW // for tracing calls
55//#define DUMP_STRIKE_CREATION
56
57#ifdef SK_DEBUG
58 #define SkASSERT_CONTINUE(pred) \
59 do { \
60 if (!(pred)) \
61 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
62 } while (false)
63#else
64 #define SkASSERT_CONTINUE(pred)
65#endif
66
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000067using namespace skia_advanced_typeface_metrics_utils;
68
reed@google.combde3c8e2011-05-18 11:58:10 +000069// SK_FREETYPE_LCD_LERP should be 0...256
70// 0 means no color reduction (e.g. just as returned from FreeType)
71// 256 means 100% color reduction (e.g. gray)
reed@google.comc5181342011-05-17 20:52:46 +000072//
73#ifndef SK_FREETYPE_LCD_LERP
reed@google.combde3c8e2011-05-18 11:58:10 +000074 #define SK_FREETYPE_LCD_LERP 96
reed@google.comc5181342011-05-17 20:52:46 +000075#endif
76
reed@google.comeffc5012011-06-27 16:44:46 +000077static bool isLCD(const SkScalerContext::Rec& rec) {
78 switch (rec.fMaskFormat) {
79 case SkMask::kLCD16_Format:
80 case SkMask::kLCD32_Format:
81 return true;
82 default:
83 return false;
84 }
85}
86
reed@android.com8a1c16f2008-12-17 15:59:43 +000087//////////////////////////////////////////////////////////////////////////
88
89struct SkFaceRec;
90
91static SkMutex gFTMutex;
92static int gFTCount;
93static FT_Library gFTLibrary;
94static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000095static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
96static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000097
reed@google.comffe49f52011-11-22 19:42:41 +000098static const uint8_t* gGammaTables[2];
99
reed@android.com8a1c16f2008-12-17 15:59:43 +0000100/////////////////////////////////////////////////////////////////////////
101
agl@chromium.orge76073b2010-06-04 20:31:17 +0000102// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
103// This value was chosen by eyeballing the result in Firefox and trying to match it.
104static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
105
agl@chromium.org309485b2009-07-21 17:41:32 +0000106static bool
107InitFreetype() {
108 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000109 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000110 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000111 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000112
agl@chromium.org309485b2009-07-21 17:41:32 +0000113 // Setup LCD filtering. This reduces colour fringes for LCD rendered
114 // glyphs.
epoger@google.comb371ed12011-06-29 21:20:52 +0000115#ifdef FT_LCD_FILTER_H
agl@chromium.org309485b2009-07-21 17:41:32 +0000116 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000117 gLCDSupport = err == 0;
epoger@google.com5070d792011-06-29 20:43:14 +0000118#else
119 gLCDSupport = false;
120#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000121 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000122
123 return true;
124}
125
reed@android.com8a1c16f2008-12-17 15:59:43 +0000126class SkScalerContext_FreeType : public SkScalerContext {
127public:
128 SkScalerContext_FreeType(const SkDescriptor* desc);
129 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000130
reed@android.com62900b42009-02-11 15:07:19 +0000131 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000132 return fFaceRec != NULL &&
133 fFTSize != NULL &&
134 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000135 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000136
137protected:
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000138 virtual unsigned generateGlyphCount();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000139 virtual uint16_t generateCharToGlyph(SkUnichar uni);
140 virtual void generateAdvance(SkGlyph* glyph);
141 virtual void generateMetrics(SkGlyph* glyph);
142 virtual void generateImage(const SkGlyph& glyph);
143 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
144 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
145 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000146 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000147
148private:
149 SkFaceRec* fFaceRec;
150 FT_Face fFace; // reference to shared face in gFaceRecHead
151 FT_Size fFTSize; // our own copy
152 SkFixed fScaleX, fScaleY;
153 FT_Matrix fMatrix22;
154 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000155 bool fDoLinearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000156
157 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000158 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000159};
160
161///////////////////////////////////////////////////////////////////////////
162///////////////////////////////////////////////////////////////////////////
163
164#include "SkStream.h"
165
166struct SkFaceRec {
167 SkFaceRec* fNext;
168 FT_Face fFace;
169 FT_StreamRec fFTStream;
170 SkStream* fSkStream;
171 uint32_t fRefCnt;
172 uint32_t fFontID;
173
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000174 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000175 SkFaceRec(SkStream* strm, uint32_t fontID);
176 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000177 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000178 }
179};
180
181extern "C" {
182 static unsigned long sk_stream_read(FT_Stream stream,
183 unsigned long offset,
184 unsigned char* buffer,
185 unsigned long count ) {
186 SkStream* str = (SkStream*)stream->descriptor.pointer;
187
188 if (count) {
189 if (!str->rewind()) {
190 return 0;
191 } else {
192 unsigned long ret;
193 if (offset) {
194 ret = str->read(NULL, offset);
195 if (ret != offset) {
196 return 0;
197 }
198 }
199 ret = str->read(buffer, count);
200 if (ret != count) {
201 return 0;
202 }
203 count = ret;
204 }
205 }
206 return count;
207 }
208
209 static void sk_stream_close( FT_Stream stream) {}
210}
211
212SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
213 : fSkStream(strm), fFontID(fontID) {
214// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
215
reed@android.com4516f472009-06-29 16:25:36 +0000216 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000217 fFTStream.size = fSkStream->getLength();
218 fFTStream.descriptor.pointer = fSkStream;
219 fFTStream.read = sk_stream_read;
220 fFTStream.close = sk_stream_close;
221}
222
reed@android.com62900b42009-02-11 15:07:19 +0000223// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000224static SkFaceRec* ref_ft_face(uint32_t fontID) {
225 SkFaceRec* rec = gFaceRecHead;
226 while (rec) {
227 if (rec->fFontID == fontID) {
228 SkASSERT(rec->fFace);
229 rec->fRefCnt += 1;
230 return rec;
231 }
232 rec = rec->fNext;
233 }
234
235 SkStream* strm = SkFontHost::OpenStream(fontID);
236 if (NULL == strm) {
237 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000238 return 0;
239 }
240
241 // this passes ownership of strm to the rec
242 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
243
244 FT_Open_Args args;
245 memset(&args, 0, sizeof(args));
246 const void* memoryBase = strm->getMemoryBase();
247
248 if (NULL != memoryBase) {
249//printf("mmap(%s)\n", keyString.c_str());
250 args.flags = FT_OPEN_MEMORY;
251 args.memory_base = (const FT_Byte*)memoryBase;
252 args.memory_size = strm->getLength();
253 } else {
254//printf("fopen(%s)\n", keyString.c_str());
255 args.flags = FT_OPEN_STREAM;
256 args.stream = &rec->fFTStream;
257 }
258
agl@chromium.org61a678a2010-08-06 18:08:18 +0000259 int face_index;
260 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
261 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
262 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000263
264 if (err) { // bad filename, try the default font
265 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
266 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000267 return 0;
268 } else {
269 SkASSERT(rec->fFace);
270 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
271 rec->fNext = gFaceRecHead;
272 gFaceRecHead = rec;
273 rec->fRefCnt = 1;
274 return rec;
275 }
276}
277
278static void unref_ft_face(FT_Face face) {
279 SkFaceRec* rec = gFaceRecHead;
280 SkFaceRec* prev = NULL;
281 while (rec) {
282 SkFaceRec* next = rec->fNext;
283 if (rec->fFace == face) {
284 if (--rec->fRefCnt == 0) {
285 if (prev) {
286 prev->fNext = next;
287 } else {
288 gFaceRecHead = next;
289 }
290 FT_Done_Face(face);
291 SkDELETE(rec);
292 }
293 return;
294 }
295 prev = rec;
296 rec = next;
297 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000298 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000299}
300
301///////////////////////////////////////////////////////////////////////////
302
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000303// Work around for old versions of freetype.
304static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
305 FT_Int32 loadFlags, FT_Fixed* advances) {
306#ifdef FT_ADVANCES_H
307 return FT_Get_Advances(face, start, count, loadFlags, advances);
308#else
309 if (!face || start >= face->num_glyphs ||
310 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
311 return 6; // "Invalid argument."
312 }
313 if (count == 0)
314 return 0;
315
316 for (int i = 0; i < count; i++) {
317 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
318 if (err)
319 return err;
320 advances[i] = face->glyph->advance.x;
321 }
322
323 return 0;
324#endif
325}
326
327static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000328#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000329 FT_UShort fsType = FT_Get_FSType_Flags(face);
330 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
331 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
332#else
333 // No embedding is 0x2 and bitmap embedding only is 0x200.
334 TT_OS2* os2_table;
335 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
336 return (os2_table->fsType & 0x202) == 0;
337 }
338 return false; // We tried, fail safe.
339#endif
340}
341
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000342static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
343 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
344 if (!glyph_id)
345 return false;
346 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
347 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
348 return true;
349}
350
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000351static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000352 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000353 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
354 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000355 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000356 SkASSERT(data);
357 *data = advance;
358 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000359}
360
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000361static void populate_glyph_to_unicode(FT_Face& face,
362 SkTDArray<SkUnichar>* glyphToUnicode) {
363 // Check and see if we have Unicode cmaps.
364 for (int i = 0; i < face->num_charmaps; ++i) {
365 // CMaps known to support Unicode:
366 // Platform ID Encoding ID Name
367 // ----------- ----------- -----------------------------------
368 // 0 0,1 Apple Unicode
369 // 0 3 Apple Unicode 2.0 (preferred)
370 // 3 1 Microsoft Unicode UCS-2
371 // 3 10 Microsoft Unicode UCS-4 (preferred)
372 //
373 // See Apple TrueType Reference Manual
374 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
375 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
376 // Microsoft OpenType Specification
377 // http://www.microsoft.com/typography/otspec/cmap.htm
378
379 FT_UShort platformId = face->charmaps[i]->platform_id;
380 FT_UShort encodingId = face->charmaps[i]->encoding_id;
381
382 if (platformId != 0 && platformId != 3) {
383 continue;
384 }
385 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
386 continue;
387 }
388 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
389 (platformId == 0 && encodingId == 3));
390
391 FT_Set_Charmap(face, face->charmaps[i]);
392 if (glyphToUnicode->isEmpty()) {
393 glyphToUnicode->setCount(face->num_glyphs);
394 memset(glyphToUnicode->begin(), 0,
395 sizeof(SkUnichar) * face->num_glyphs);
396 }
397
398 // Iterate through each cmap entry.
399 FT_UInt glyphIndex;
400 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
401 glyphIndex != 0;
402 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
403 if (charCode &&
404 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
405 (*glyphToUnicode)[glyphIndex] = charCode;
406 }
407 }
408 }
409}
410
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000411// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000412SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000413 uint32_t fontID,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000414 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
415 const uint32_t* glyphIDs,
416 uint32_t glyphIDsCount) {
djsollen@google.comda957722011-11-16 17:00:46 +0000417#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000418 return NULL;
419#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000420 SkAutoMutexAcquire ac(gFTMutex);
421 FT_Library libInit = NULL;
422 if (gFTCount == 0) {
423 if (!InitFreetype())
424 sk_throw();
425 libInit = gFTLibrary;
426 }
427 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
428 SkFaceRec* rec = ref_ft_face(fontID);
429 if (NULL == rec)
430 return NULL;
431 FT_Face face = rec->fFace;
432
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000433 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
434 info->fFontName.set(FT_Get_Postscript_Name(face));
435 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
436 info->fLastGlyphID = face->num_glyphs - 1;
437 info->fEmSize = 1000;
438
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000439 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000440 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000441 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000442 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000443 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000444 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000445 cid = true;
446 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000447 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000448 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000449 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000450 cid = true;
451 TT_Header* ttHeader;
452 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
453 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000454 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000455 }
456 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000457
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000458 info->fStyle = 0;
459 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000460 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000461 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000462 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000463 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
464 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000465 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
466
467 PS_FontInfoRec ps_info;
468 TT_Postscript* tt_info;
469 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
470 info->fItalicAngle = ps_info.italic_angle;
471 } else if ((tt_info =
472 (TT_Postscript*)FT_Get_Sfnt_Table(face,
473 ft_sfnt_post)) != NULL) {
474 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
475 } else {
476 info->fItalicAngle = 0;
477 }
478
479 info->fAscent = face->ascender;
480 info->fDescent = face->descender;
481
482 // Figure out a good guess for StemV - Min width of i, I, !, 1.
483 // This probably isn't very good with an italic font.
484 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000485 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000486 char stem_chars[] = {'i', 'I', '!', '1'};
487 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
488 FT_BBox bbox;
489 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
490 int16_t width = bbox.xMax - bbox.xMin;
491 if (width > 0 && width < min_width) {
492 min_width = width;
493 info->fStemV = min_width;
494 }
495 }
496 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000497
498 TT_PCLT* pclt_info;
499 TT_OS2* os2_table;
500 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
501 info->fCapHeight = pclt_info->CapHeight;
502 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
503 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000504 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000505 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000506 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000507 } else if ((os2_table =
508 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
509 info->fCapHeight = os2_table->sCapHeight;
510 } else {
511 // Figure out a good guess for CapHeight: average the height of M and X.
512 FT_BBox m_bbox, x_bbox;
513 bool got_m, got_x;
514 got_m = GetLetterCBox(face, 'M', &m_bbox);
515 got_x = GetLetterCBox(face, 'X', &x_bbox);
516 if (got_m && got_x) {
517 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
518 x_bbox.yMin) / 2;
519 } else if (got_m && !got_x) {
520 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
521 } else if (!got_m && got_x) {
522 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
523 }
524 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000525
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000526 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
527 face->bbox.xMax, face->bbox.yMin);
528
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000529 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000530 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
531 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
532 }
533
534 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000535 if (FT_IS_FIXED_WIDTH(face)) {
536 appendRange(&info->fGlyphWidths, 0);
537 int16_t advance = face->max_advance_width;
538 info->fGlyphWidths->fAdvance.append(1, &advance);
539 finishRange(info->fGlyphWidths.get(), 0,
540 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000541 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000542 appendRange(&info->fGlyphWidths, 0);
543 // So as to not blow out the stack, get advances in batches.
544 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
545 FT_Fixed advances[128];
546 int advanceCount = 128;
547 if (gID + advanceCount > face->num_glyphs)
548 advanceCount = face->num_glyphs - gID + 1;
549 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
550 advances);
551 for (int i = 0; i < advanceCount; i++) {
552 int16_t advance = advances[gID + i];
553 info->fGlyphWidths->fAdvance.append(1, &advance);
554 }
555 }
556 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
557 SkAdvancedTypefaceMetrics::WidthRange::kRange);
558 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000559 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000560 getAdvanceData(face,
561 face->num_glyphs,
562 glyphIDs,
563 glyphIDsCount,
564 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000565 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000566 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000567
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000568 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
569 FT_HAS_VERTICAL(face)) {
570 SkASSERT(false); // Not implemented yet.
571 }
572
573 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
574 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
575 // Postscript fonts may contain more than 255 glyphs, so we end up
576 // using multiple font descriptions with a glyph ordering. Record
577 // the name of each glyph.
578 info->fGlyphNames.reset(
579 new SkAutoTArray<SkString>(face->num_glyphs));
580 for (int gID = 0; gID < face->num_glyphs; gID++) {
581 char glyphName[128]; // PS limit for names is 127 bytes.
582 FT_Get_Glyph_Name(face, gID, glyphName, 128);
583 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000584 }
585 }
586
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000587 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
588 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
589 face->num_charmaps) {
590 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
591 }
592
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000593 if (!canEmbed(face))
594 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
595
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000596 unref_ft_face(face);
597 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000598#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000599}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000600
reed@google.com618ef5e2011-01-26 22:10:41 +0000601///////////////////////////////////////////////////////////////////////////
602
reed@google.comffe49f52011-11-22 19:42:41 +0000603#define BLACK_LUMINANCE_LIMIT 0x40
604#define WHITE_LUMINANCE_LIMIT 0xA0
605
reed@google.com8ed436c2011-07-21 14:12:36 +0000606static bool bothZero(SkScalar a, SkScalar b) {
607 return 0 == a && 0 == b;
608}
609
610// returns false if there is any non-90-rotation or skew
611static bool isAxisAligned(const SkScalerContext::Rec& rec) {
612 return 0 == rec.fPreSkewX &&
613 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
614 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
615}
616
reed@google.com618ef5e2011-01-26 22:10:41 +0000617void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
618 if (!gLCDSupportValid) {
619 InitFreetype();
620 FT_Done_FreeType(gFTLibrary);
621 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000622
reed@google.comeffc5012011-06-27 16:44:46 +0000623 if (!gLCDSupport && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000624 // If the runtime Freetype library doesn't support LCD mode, we disable
625 // it here.
626 rec->fMaskFormat = SkMask::kA8_Format;
627 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000628
reed@google.com618ef5e2011-01-26 22:10:41 +0000629 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000630 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000631 // collapse full->normal hinting if we're not doing LCD
632 h = SkPaint::kNormal_Hinting;
633 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
634 SkPaint::kNo_Hinting != h) {
635 // to do subpixel, we must have at most slight hinting
636 h = SkPaint::kSlight_Hinting;
637 }
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000638#ifndef SK_IGNORE_ROTATED_FREETYPE_FIX
reed@google.com8ed436c2011-07-21 14:12:36 +0000639 // rotated text looks bad with hinting, so we disable it as needed
640 if (!isAxisAligned(*rec)) {
641 h = SkPaint::kNo_Hinting;
642 }
bsalomon@google.com0e35ca82011-07-22 17:56:19 +0000643#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000644 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000645
646 // for compatibility at the moment, discretize luminance to 3 settings
647 // black, white, gray. This helps with fontcache utilization, since we
648 // won't create multiple entries that in the end map to the same results.
649 {
650 unsigned lum = rec->getLuminanceByte();
651 if (gGammaTables[0] || gGammaTables[1]) {
652 if (lum <= BLACK_LUMINANCE_LIMIT) {
653 lum = 0;
654 } else if (lum >= WHITE_LUMINANCE_LIMIT) {
655 lum = SkScalerContext::kLuminance_Max;
656 } else {
657 lum = SkScalerContext::kLuminance_Max >> 1;
658 }
659 } else {
660 lum = 0; // no gamma correct, so use 0 since SkPaint uses that
661 // when measuring text w/o regard for luminance
662 }
663 rec->setLuminanceBits(lum);
664 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000665}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000666
djsollen@google.comda957722011-11-16 17:00:46 +0000667#ifdef SK_BUILD_FOR_ANDROID
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000668uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
669 SkAutoMutexAcquire ac(gFTMutex);
670 SkFaceRec *rec = ref_ft_face(fontID);
671 uint16_t unitsPerEm = 0;
672
673 if (rec != NULL && rec->fFace != NULL) {
674 unitsPerEm = rec->fFace->units_per_EM;
675 unref_ft_face(rec->fFace);
676 }
677
678 return (uint32_t)unitsPerEm;
679}
680#endif
681
reed@android.com8a1c16f2008-12-17 15:59:43 +0000682SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000683 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000684 SkAutoMutexAcquire ac(gFTMutex);
685
reed@android.com8a1c16f2008-12-17 15:59:43 +0000686 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000687 if (!InitFreetype()) {
688 sk_throw();
689 }
reed@google.comffe49f52011-11-22 19:42:41 +0000690 SkFontHost::GetGammaTables(gGammaTables);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000691 }
692 ++gFTCount;
693
694 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000695 fFTSize = NULL;
696 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000697 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000698 if (NULL == fFaceRec) {
699 return;
700 }
701 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000702
703 // compute our factors from the record
704
705 SkMatrix m;
706
707 fRec.getSingleMatrix(&m);
708
709#ifdef DUMP_STRIKE_CREATION
710 SkString keyString;
711 SkFontHost::GetDescriptorKeyString(desc, &keyString);
712 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
713 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
714 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
715 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000716 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000717#endif
718
719 // now compute our scale factors
720 SkScalar sx = m.getScaleX();
721 SkScalar sy = m.getScaleY();
722
723 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
724 // sort of give up on hinting
725 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
726 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
727 sx = sy = SkScalarAve(sx, sy);
728
729 SkScalar inv = SkScalarInvert(sx);
730
731 // flip the skew elements to go from our Y-down system to FreeType's
732 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
733 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
734 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
735 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
736 } else {
737 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
738 fMatrix22.xy = fMatrix22.yx = 0;
739 }
740
741 fScaleX = SkScalarToFixed(sx);
742 fScaleY = SkScalarToFixed(sy);
743
744 // compute the flags we send to Load_Glyph
745 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000746 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@google.combdc99882011-11-21 14:36:57 +0000747 bool linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000748
agl@chromium.org70a303f2010-05-10 14:15:50 +0000749 if (SkMask::kBW_Format == fRec.fMaskFormat) {
750 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
751 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000752 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000753 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000754 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000755 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000756 } else {
757 switch (fRec.getHinting()) {
758 case SkPaint::kNo_Hinting:
759 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000760 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000761 break;
762 case SkPaint::kSlight_Hinting:
763 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@google.combdc99882011-11-21 14:36:57 +0000764 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000765 break;
766 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000767 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
768 loadFlags = FT_LOAD_FORCE_AUTOHINT;
769 else
770 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000771 break;
772 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000773 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
774 loadFlags = FT_LOAD_FORCE_AUTOHINT;
775 break;
776 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000777 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000778 if (isLCD(fRec)) {
779 if (fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag) {
780 loadFlags = FT_LOAD_TARGET_LCD_V;
781 } else {
782 loadFlags = FT_LOAD_TARGET_LCD;
783 }
reed@google.comea2333d2011-03-14 16:44:56 +0000784 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000785 break;
786 default:
787 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
788 break;
789 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790 }
791
reed@google.comeffc5012011-06-27 16:44:46 +0000792 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000793 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000794 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000795
reed@google.com96a9f7912011-05-06 11:49:30 +0000796 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
797 // advances, as fontconfig and cairo do.
798 // See http://code.google.com/p/skia/issues/detail?id=222.
799 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
800
reed@android.come4d0bc02009-07-24 19:53:20 +0000801 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000802 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000803 }
804
805 // now create the FT_Size
806
807 {
808 FT_Error err;
809
810 err = FT_New_Size(fFace, &fFTSize);
811 if (err != 0) {
812 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
813 fFaceRec->fFontID, fScaleX, fScaleY, err));
814 fFace = NULL;
815 return;
816 }
817
818 err = FT_Activate_Size(fFTSize);
819 if (err != 0) {
820 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
821 fFaceRec->fFontID, fScaleX, fScaleY, err));
822 fFTSize = NULL;
823 }
824
825 err = FT_Set_Char_Size( fFace,
826 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
827 72, 72);
828 if (err != 0) {
829 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
830 fFaceRec->fFontID, fScaleX, fScaleY, err));
831 fFace = NULL;
832 return;
833 }
834
835 FT_Set_Transform( fFace, &fMatrix22, NULL);
836 }
837}
838
839SkScalerContext_FreeType::~SkScalerContext_FreeType() {
840 if (fFTSize != NULL) {
841 FT_Done_Size(fFTSize);
842 }
843
844 SkAutoMutexAcquire ac(gFTMutex);
845
846 if (fFace != NULL) {
847 unref_ft_face(fFace);
848 }
849 if (--gFTCount == 0) {
850// SkDEBUGF(("FT_Done_FreeType\n"));
851 FT_Done_FreeType(gFTLibrary);
852 SkDEBUGCODE(gFTLibrary = NULL;)
853 }
854}
855
856/* We call this before each use of the fFace, since we may be sharing
857 this face with other context (at different sizes).
858*/
859FT_Error SkScalerContext_FreeType::setupSize() {
860 /* In the off-chance that a font has been removed, we want to error out
861 right away, so call resolve just to be sure.
862
863 TODO: perhaps we can skip this, by walking the global font cache and
864 killing all of the contexts when we know that a given fontID is going
865 away...
866 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000867 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000868 return (FT_Error)-1;
869 }
870
871 FT_Error err = FT_Activate_Size(fFTSize);
872
873 if (err != 0) {
874 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
875 fFaceRec->fFontID, fScaleX, fScaleY, err));
876 fFTSize = NULL;
877 } else {
878 // seems we need to reset this every time (not sure why, but without it
879 // I get random italics from some other fFTSize)
880 FT_Set_Transform( fFace, &fMatrix22, NULL);
881 }
882 return err;
883}
884
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000885void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
886 FT_Pos strength;
887 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
888 / 24;
889 FT_Outline_Embolden(outline, strength);
890}
891
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000892unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000893 return fFace->num_glyphs;
894}
895
896uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
897 return SkToU16(FT_Get_Char_Index( fFace, uni ));
898}
899
reed@android.com9d3a9852010-01-08 14:07:42 +0000900SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
901 // iterate through each cmap entry, looking for matching glyph indices
902 FT_UInt glyphIndex;
903 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
904
905 while (glyphIndex != 0) {
906 if (glyphIndex == glyph) {
907 return charCode;
908 }
909 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
910 }
911
912 return 0;
913}
914
reed@android.com8a1c16f2008-12-17 15:59:43 +0000915static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
916 switch (format) {
917 case SkMask::kBW_Format:
918 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000919 case SkMask::kA8_Format:
920 default:
921 return FT_PIXEL_MODE_GRAY;
922 }
923}
924
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
926#ifdef FT_ADVANCES_H
927 /* unhinted and light hinted text have linearly scaled advances
928 * which are very cheap to compute with some font formats...
929 */
reed@google.combdc99882011-11-21 14:36:57 +0000930 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000931 SkAutoMutexAcquire ac(gFTMutex);
932
933 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000934 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000935 return;
936 }
937
938 FT_Error error;
939 FT_Fixed advance;
940
941 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
942 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
943 &advance );
944 if (0 == error) {
945 glyph->fRsbDelta = 0;
946 glyph->fLsbDelta = 0;
947 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
948 glyph->fAdvanceY = 0;
949 return;
950 }
951 }
952#endif /* FT_ADVANCES_H */
953 /* otherwise, we need to load/hint the glyph, which is slower */
954 this->generateMetrics(glyph);
955 return;
956}
957
958void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
959 SkAutoMutexAcquire ac(gFTMutex);
960
961 glyph->fRsbDelta = 0;
962 glyph->fLsbDelta = 0;
963
964 FT_Error err;
965
966 if (this->setupSize()) {
967 goto ERROR;
968 }
969
970 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
971 if (err != 0) {
972 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
973 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
974 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000975 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000976 return;
977 }
978
979 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +0000980 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000981 FT_BBox bbox;
982
bungeman@google.com0f0c2882011-11-04 15:47:41 +0000983 if (0 == fFace->glyph->outline.n_contours) {
984 glyph->fWidth = 0;
985 glyph->fHeight = 0;
986 glyph->fTop = 0;
987 glyph->fLeft = 0;
988 break;
989 }
990
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000991 if (fRec.fFlags & kEmbolden_Flag) {
992 emboldenOutline(&fFace->glyph->outline);
993 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000994 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
995
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000996 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000997 int dx = glyph->getSubXFixed() >> 10;
998 int dy = glyph->getSubYFixed() >> 10;
999 // negate dy since freetype-y-goes-up and skia-y-goes-down
1000 bbox.xMin += dx;
1001 bbox.yMin -= dy;
1002 bbox.xMax += dx;
1003 bbox.yMax -= dy;
1004 }
1005
1006 bbox.xMin &= ~63;
1007 bbox.yMin &= ~63;
1008 bbox.xMax = (bbox.xMax + 63) & ~63;
1009 bbox.yMax = (bbox.yMax + 63) & ~63;
1010
1011 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
1012 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
1013 glyph->fTop = -SkToS16(bbox.yMax >> 6);
1014 glyph->fLeft = SkToS16(bbox.xMin >> 6);
1015 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001016 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001017
1018 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001019 if (fRec.fFlags & kEmbolden_Flag) {
1020 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1021 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1022 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001023 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1024 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1025 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1026 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1027 break;
1028
1029 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001030 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001031 goto ERROR;
1032 }
1033
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001034 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1036 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1037 if (fRec.fFlags & kDevKernText_Flag) {
1038 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1039 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1040 }
1041 } else {
1042 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1043 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1044 }
1045
1046#ifdef ENABLE_GLYPH_SPEW
1047 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1048 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1049#endif
1050}
1051
reed@google.combde3c8e2011-05-18 11:58:10 +00001052static int lerp(int start, int end) {
1053 SkASSERT((unsigned)SK_FREETYPE_LCD_LERP <= 256);
1054 return start + ((end - start) * (SK_FREETYPE_LCD_LERP) >> 8);
reed@google.comc5181342011-05-17 20:52:46 +00001055}
1056
1057static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
1058 if (SK_FREETYPE_LCD_LERP) {
reed@google.combde3c8e2011-05-18 11:58:10 +00001059 // want (a+b+c)/3, but we approx to avoid the divide
1060 unsigned ave = (5 * (r + g + b) + b) >> 4;
1061 r = lerp(r, ave);
1062 g = lerp(g, ave);
1063 b = lerp(b, ave);
reed@google.comc5181342011-05-17 20:52:46 +00001064 }
1065 return SkPackRGB16(r >> 3, g >> 2, b >> 3);
1066}
1067
reed@google.com73824072011-06-23 13:17:30 +00001068static uint16_t grayToRGB16(U8CPU gray) {
1069 SkASSERT(gray <= 255);
1070 return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3);
1071}
1072
1073static int bittst(const uint8_t data[], int bitOffset) {
1074 SkASSERT(bitOffset >= 0);
reed@google.comc8e0f932011-06-23 19:39:49 +00001075 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
reed@google.com73824072011-06-23 13:17:30 +00001076 return lowBit & 1;
1077}
1078
reed@google.comeffc5012011-06-27 16:44:46 +00001079static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap,
1080 int lcdIsBGR) {
reed@google.comea2333d2011-03-14 16:44:56 +00001081 SkASSERT(glyph.fHeight == bitmap.rows);
reed@google.comea2333d2011-03-14 16:44:56 +00001082 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
reed@google.com73824072011-06-23 13:17:30 +00001083 const size_t dstRB = glyph.rowBytes();
1084 const int width = glyph.fWidth;
1085 const uint8_t* src = bitmap.buffer;
reed@google.comea2333d2011-03-14 16:44:56 +00001086
reed@google.com73824072011-06-23 13:17:30 +00001087 switch (bitmap.pixel_mode) {
1088 case FT_PIXEL_MODE_MONO: {
1089 for (int y = 0; y < glyph.fHeight; ++y) {
1090 for (int x = 0; x < width; ++x) {
1091 dst[x] = -bittst(src, x);
1092 }
1093 dst = (uint16_t*)((char*)dst + dstRB);
1094 src += bitmap.pitch;
1095 }
1096 } break;
1097 case FT_PIXEL_MODE_GRAY: {
1098 for (int y = 0; y < glyph.fHeight; ++y) {
1099 for (int x = 0; x < width; ++x) {
1100 dst[x] = grayToRGB16(src[x]);
1101 }
1102 dst = (uint16_t*)((char*)dst + dstRB);
1103 src += bitmap.pitch;
1104 }
1105 } break;
1106 default: {
1107 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
1108 src += 3;
1109 for (int y = 0; y < glyph.fHeight; y++) {
1110 const uint8_t* triple = src;
reed@google.comeffc5012011-06-27 16:44:46 +00001111 if (lcdIsBGR) {
1112 for (int x = 0; x < width; x++) {
1113 dst[x] = packTriple(triple[2], triple[1], triple[0]);
1114 triple += 3;
1115 }
1116 } else {
1117 for (int x = 0; x < width; x++) {
1118 dst[x] = packTriple(triple[0], triple[1], triple[2]);
1119 triple += 3;
1120 }
reed@google.com73824072011-06-23 13:17:30 +00001121 }
1122 src += bitmap.pitch;
1123 dst = (uint16_t*)((char*)dst + dstRB);
1124 }
1125 } break;
reed@google.comea2333d2011-03-14 16:44:56 +00001126 }
1127}
1128
reed@android.com8a1c16f2008-12-17 15:59:43 +00001129void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1130 SkAutoMutexAcquire ac(gFTMutex);
1131
1132 FT_Error err;
1133
1134 if (this->setupSize()) {
1135 goto ERROR;
1136 }
1137
1138 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1139 if (err != 0) {
1140 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1141 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1142 ERROR:
1143 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1144 return;
1145 }
1146
1147 switch ( fFace->glyph->format ) {
1148 case FT_GLYPH_FORMAT_OUTLINE: {
1149 FT_Outline* outline = &fFace->glyph->outline;
1150 FT_BBox bbox;
1151 FT_Bitmap target;
1152
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001153 if (fRec.fFlags & kEmbolden_Flag) {
1154 emboldenOutline(outline);
1155 }
1156
reed@android.com8a1c16f2008-12-17 15:59:43 +00001157 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001158 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001159 dx = glyph.getSubXFixed() >> 10;
1160 dy = glyph.getSubYFixed() >> 10;
1161 // negate dy since freetype-y-goes-up and skia-y-goes-down
1162 dy = -dy;
1163 }
1164 FT_Outline_Get_CBox(outline, &bbox);
1165 /*
1166 what we really want to do for subpixel is
1167 offset(dx, dy)
1168 compute_bounds
1169 offset(bbox & !63)
1170 but that is two calls to offset, so we do the following, which
1171 achieves the same thing with only one offset call.
1172 */
1173 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1174 dy - ((bbox.yMin + dy) & ~63));
1175
reed@google.comea2333d2011-03-14 16:44:56 +00001176 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1177 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
reed@google.comeffc5012011-06-27 16:44:46 +00001178 copyFT2LCD16(glyph, fFace->glyph->bitmap,
1179 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
reed@google.comea2333d2011-03-14 16:44:56 +00001180 } else {
1181 target.width = glyph.fWidth;
1182 target.rows = glyph.fHeight;
1183 target.pitch = glyph.rowBytes();
1184 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1185 target.pixel_mode = compute_pixel_mode(
1186 (SkMask::Format)fRec.fMaskFormat);
1187 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188
reed@google.comea2333d2011-03-14 16:44:56 +00001189 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1190 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1191 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001192 } break;
1193
1194 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001195 if (fRec.fFlags & kEmbolden_Flag) {
1196 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1197 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1198 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001199 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1200 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1201 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1202 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1203
1204 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1205 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001206
agl@chromium.org558434a2009-08-11 17:22:38 +00001207 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1208 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1209 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001210 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1211 unsigned dstRowBytes = glyph.rowBytes();
1212 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1213 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1214
1215 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1216 memcpy(dst, src, minRowBytes);
1217 memset(dst + minRowBytes, 0, extraRowBytes);
1218 src += srcRowBytes;
1219 dst += dstRowBytes;
1220 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001221 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
reed@google.comeffc5012011-06-27 16:44:46 +00001222 glyph.fMaskFormat == SkMask::kA8_Format) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001223 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1224 uint8_t byte = 0;
1225 int bits = 0;
1226 const uint8_t* src_row = src;
1227 uint8_t* dst_row = dst;
1228
1229 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1230 if (!bits) {
1231 byte = *src_row++;
1232 bits = 8;
1233 }
1234
1235 *dst_row++ = byte & 0x80 ? 0xff : 0;
1236 bits--;
1237 byte <<= 1;
1238 }
1239
1240 src += fFace->glyph->bitmap.pitch;
1241 dst += glyph.rowBytes();
1242 }
reed@google.com73824072011-06-23 13:17:30 +00001243 } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
reed@google.comeffc5012011-06-27 16:44:46 +00001244 copyFT2LCD16(glyph, fFace->glyph->bitmap,
1245 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
agl@chromium.org558434a2009-08-11 17:22:38 +00001246 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001247 SkDEBUGFAIL("unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001248 }
1249 } break;
1250
1251 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001252 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253 goto ERROR;
1254 }
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001255
reed@google.comffe49f52011-11-22 19:42:41 +00001256 if (gGammaTables[0] || gGammaTables[1]) {
1257 bool isWhite = fRec.getLuminanceByte() >= WHITE_LUMINANCE_LIMIT;
1258 bool isBlack = fRec.getLuminanceByte() <= BLACK_LUMINANCE_LIMIT;
1259 if ((isWhite | isBlack) && SkMask::kA8_Format == glyph.fMaskFormat) {
1260 int index = isBlack ? 0 : 1;
1261 if (gGammaTables[index]) {
1262 const uint8_t* SK_RESTRICT table = gGammaTables[index];
1263 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1264 unsigned rowBytes = glyph.rowBytes();
1265
1266 for (int y = glyph.fHeight - 1; y >= 0; --y) {
1267 for (int x = glyph.fWidth - 1; x >= 0; --x) {
1268 dst[x] = table[dst[x]];
1269 }
1270 dst += rowBytes;
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001271 }
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001272 }
1273 }
1274 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001275}
1276
1277///////////////////////////////////////////////////////////////////////////////
1278
1279#define ft2sk(x) SkFixedToScalar((x) << 10)
1280
reed@android.com6f252972009-01-14 16:46:16 +00001281#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001282 #define CONST_PARAM const
1283#else // older freetype doesn't use const here
1284 #define CONST_PARAM
1285#endif
1286
1287static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1288 SkPath* path = (SkPath*)ctx;
1289 path->close(); // to close the previous contour (if any)
1290 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1291 return 0;
1292}
1293
1294static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1295 SkPath* path = (SkPath*)ctx;
1296 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1297 return 0;
1298}
1299
1300static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1301 void* ctx) {
1302 SkPath* path = (SkPath*)ctx;
1303 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1304 return 0;
1305}
1306
1307static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1308 CONST_PARAM FT_Vector* pt2, void* ctx) {
1309 SkPath* path = (SkPath*)ctx;
1310 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1311 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1312 return 0;
1313}
1314
1315void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1316 SkPath* path) {
1317 SkAutoMutexAcquire ac(gFTMutex);
1318
1319 SkASSERT(&glyph && path);
1320
1321 if (this->setupSize()) {
1322 path->reset();
1323 return;
1324 }
1325
1326 uint32_t flags = fLoadGlyphFlags;
1327 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1328 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1329
1330 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1331
1332 if (err != 0) {
1333 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1334 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1335 path->reset();
1336 return;
1337 }
1338
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001339 if (fRec.fFlags & kEmbolden_Flag) {
1340 emboldenOutline(&fFace->glyph->outline);
1341 }
1342
reed@android.com8a1c16f2008-12-17 15:59:43 +00001343 FT_Outline_Funcs funcs;
1344
1345 funcs.move_to = move_proc;
1346 funcs.line_to = line_proc;
1347 funcs.conic_to = quad_proc;
1348 funcs.cubic_to = cubic_proc;
1349 funcs.shift = 0;
1350 funcs.delta = 0;
1351
1352 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1353
1354 if (err != 0) {
1355 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1356 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1357 path->reset();
1358 return;
1359 }
1360
1361 path->close();
1362}
1363
1364void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1365 SkPaint::FontMetrics* my) {
1366 if (NULL == mx && NULL == my) {
1367 return;
1368 }
1369
1370 SkAutoMutexAcquire ac(gFTMutex);
1371
1372 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001373 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001374 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001375 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001376 }
1377 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001378 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001379 }
1380 return;
1381 }
1382
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001383 FT_Face face = fFace;
1384 int upem = face->units_per_EM;
1385 if (upem <= 0) {
1386 goto ERROR;
1387 }
1388
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001389 SkPoint pts[6];
1390 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001391 SkFixed scaleY = fScaleY;
1392 SkFixed mxy = fMatrix22.xy;
1393 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001394 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1395 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001396
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001397 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001398 if (leading < 0) {
1399 leading = 0;
1400 }
1401
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001402 // Try to get the OS/2 table from the font. This contains the specific
1403 // average font width metrics which Windows uses.
1404 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1405
reed@android.com8a1c16f2008-12-17 15:59:43 +00001406 ys[0] = -face->bbox.yMax;
1407 ys[1] = -face->ascender;
1408 ys[2] = -face->descender;
1409 ys[3] = -face->bbox.yMin;
1410 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001411 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1412
1413 SkScalar x_height;
1414 if (os2 && os2->sxHeight) {
1415 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1416 } else {
1417 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1418 if (x_glyph) {
1419 FT_BBox bbox;
1420 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001421 if (fRec.fFlags & kEmbolden_Flag) {
1422 emboldenOutline(&fFace->glyph->outline);
1423 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001424 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1425 x_height = SkIntToScalar(bbox.yMax) / 64;
1426 } else {
1427 x_height = 0;
1428 }
1429 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001430
1431 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001432 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001433 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1434 SkFixed x = SkFixedMul(mxy, y);
1435 y = SkFixedMul(myy, y);
1436 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1437 }
1438
1439 if (mx) {
1440 mx->fTop = pts[0].fX;
1441 mx->fAscent = pts[1].fX;
1442 mx->fDescent = pts[2].fX;
1443 mx->fBottom = pts[3].fX;
1444 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001445 mx->fAvgCharWidth = pts[5].fX;
1446 mx->fXMin = xmin;
1447 mx->fXMax = xmax;
1448 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001449 }
1450 if (my) {
1451 my->fTop = pts[0].fY;
1452 my->fAscent = pts[1].fY;
1453 my->fDescent = pts[2].fY;
1454 my->fBottom = pts[3].fY;
1455 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001456 my->fAvgCharWidth = pts[5].fY;
1457 my->fXMin = xmin;
1458 my->fXMax = xmax;
1459 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001460 }
1461}
1462
1463////////////////////////////////////////////////////////////////////////
1464////////////////////////////////////////////////////////////////////////
1465
1466SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001467 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1468 if (!c->success()) {
1469 SkDELETE(c);
1470 c = NULL;
1471 }
1472 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001473}
1474
1475///////////////////////////////////////////////////////////////////////////////
1476
1477/* Export this so that other parts of our FonttHost port can make use of our
1478 ability to extract the name+style from a stream, using FreeType's api.
1479*/
reed@google.com5b31b0f2011-02-23 14:41:42 +00001480SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
1481 bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001482 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001483 if (FT_Init_FreeType(&library)) {
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001484 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001485 return SkTypeface::kNormal;
1486 }
1487
1488 FT_Open_Args args;
1489 memset(&args, 0, sizeof(args));
1490
1491 const void* memoryBase = stream->getMemoryBase();
1492 FT_StreamRec streamRec;
1493
1494 if (NULL != memoryBase) {
1495 args.flags = FT_OPEN_MEMORY;
1496 args.memory_base = (const FT_Byte*)memoryBase;
1497 args.memory_size = stream->getLength();
1498 } else {
1499 memset(&streamRec, 0, sizeof(streamRec));
1500 streamRec.size = stream->read(NULL, 0);
1501 streamRec.descriptor.pointer = stream;
1502 streamRec.read = sk_stream_read;
1503 streamRec.close = sk_stream_close;
1504
1505 args.flags = FT_OPEN_STREAM;
1506 args.stream = &streamRec;
1507 }
1508
1509 FT_Face face;
1510 if (FT_Open_Face(library, &args, 0, &face)) {
1511 FT_Done_FreeType(library);
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001512 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001513 return SkTypeface::kNormal;
1514 }
1515
1516 name->set(face->family_name);
1517 int style = SkTypeface::kNormal;
1518
1519 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1520 style |= SkTypeface::kBold;
1521 }
1522 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1523 style |= SkTypeface::kItalic;
1524 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001525 if (isFixedWidth) {
1526 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1527 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001528
1529 FT_Done_Face(face);
1530 FT_Done_FreeType(library);
1531 return (SkTypeface::Style)style;
1532}