blob: e794f899f0a92bed15eb23e382794ac1ffb4074d [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
reed@google.com1ac83502012-02-28 17:06:02 +000057//#define SK_GAMMA_APPLY_TO_A8
reed@google.com613e9fe2012-02-29 15:08:00 +000058#define SK_GAMMA_CONTRAST 0x80
59#define SK_GAMMA_EXPONENT 2.2
reed@google.com1ac83502012-02-28 17:06:02 +000060
reed@android.com8a1c16f2008-12-17 15:59:43 +000061#ifdef SK_DEBUG
62 #define SkASSERT_CONTINUE(pred) \
63 do { \
64 if (!(pred)) \
65 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
66 } while (false)
67#else
68 #define SkASSERT_CONTINUE(pred)
69#endif
70
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000071using namespace skia_advanced_typeface_metrics_utils;
72
reed@google.comeffc5012011-06-27 16:44:46 +000073static bool isLCD(const SkScalerContext::Rec& rec) {
74 switch (rec.fMaskFormat) {
75 case SkMask::kLCD16_Format:
76 case SkMask::kLCD32_Format:
77 return true;
78 default:
79 return false;
80 }
81}
82
reed@android.com8a1c16f2008-12-17 15:59:43 +000083//////////////////////////////////////////////////////////////////////////
84
85struct SkFaceRec;
86
digit@google.com1771cbf2012-01-26 21:26:40 +000087SK_DECLARE_STATIC_MUTEX(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +000088static int gFTCount;
89static FT_Library gFTLibrary;
90static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000091static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
92static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000093
reed@google.comffe49f52011-11-22 19:42:41 +000094static const uint8_t* gGammaTables[2];
95
reed@android.com8a1c16f2008-12-17 15:59:43 +000096/////////////////////////////////////////////////////////////////////////
97
agl@chromium.orge76073b2010-06-04 20:31:17 +000098// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
99// This value was chosen by eyeballing the result in Firefox and trying to match it.
100static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
101
agl@chromium.org309485b2009-07-21 17:41:32 +0000102static bool
103InitFreetype() {
104 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000105 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000106 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000107 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000108
agl@chromium.org309485b2009-07-21 17:41:32 +0000109 // Setup LCD filtering. This reduces colour fringes for LCD rendered
110 // glyphs.
epoger@google.comb371ed12011-06-29 21:20:52 +0000111#ifdef FT_LCD_FILTER_H
reed@google.com1ac83502012-02-28 17:06:02 +0000112// err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
113 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_LIGHT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000114 gLCDSupport = err == 0;
epoger@google.com5070d792011-06-29 20:43:14 +0000115#else
116 gLCDSupport = false;
117#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000118 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000119
120 return true;
121}
122
reed@android.com8a1c16f2008-12-17 15:59:43 +0000123class SkScalerContext_FreeType : public SkScalerContext {
124public:
125 SkScalerContext_FreeType(const SkDescriptor* desc);
126 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000127
reed@android.com62900b42009-02-11 15:07:19 +0000128 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000129 return fFaceRec != NULL &&
130 fFTSize != NULL &&
131 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000132 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000133
134protected:
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000135 virtual unsigned generateGlyphCount();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000136 virtual uint16_t generateCharToGlyph(SkUnichar uni);
137 virtual void generateAdvance(SkGlyph* glyph);
138 virtual void generateMetrics(SkGlyph* glyph);
139 virtual void generateImage(const SkGlyph& glyph);
140 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
141 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
142 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000143 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144
145private:
146 SkFaceRec* fFaceRec;
147 FT_Face fFace; // reference to shared face in gFaceRecHead
148 FT_Size fFTSize; // our own copy
149 SkFixed fScaleX, fScaleY;
150 FT_Matrix fMatrix22;
151 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000152 bool fDoLinearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000153
154 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000155 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000156};
157
158///////////////////////////////////////////////////////////////////////////
159///////////////////////////////////////////////////////////////////////////
160
161#include "SkStream.h"
162
163struct SkFaceRec {
164 SkFaceRec* fNext;
165 FT_Face fFace;
166 FT_StreamRec fFTStream;
167 SkStream* fSkStream;
168 uint32_t fRefCnt;
169 uint32_t fFontID;
170
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000171 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000172 SkFaceRec(SkStream* strm, uint32_t fontID);
173 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000174 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000175 }
176};
177
178extern "C" {
179 static unsigned long sk_stream_read(FT_Stream stream,
180 unsigned long offset,
181 unsigned char* buffer,
182 unsigned long count ) {
183 SkStream* str = (SkStream*)stream->descriptor.pointer;
184
185 if (count) {
186 if (!str->rewind()) {
187 return 0;
188 } else {
189 unsigned long ret;
190 if (offset) {
191 ret = str->read(NULL, offset);
192 if (ret != offset) {
193 return 0;
194 }
195 }
196 ret = str->read(buffer, count);
197 if (ret != count) {
198 return 0;
199 }
200 count = ret;
201 }
202 }
203 return count;
204 }
205
206 static void sk_stream_close( FT_Stream stream) {}
207}
208
209SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
210 : fSkStream(strm), fFontID(fontID) {
211// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
212
reed@android.com4516f472009-06-29 16:25:36 +0000213 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000214 fFTStream.size = fSkStream->getLength();
215 fFTStream.descriptor.pointer = fSkStream;
216 fFTStream.read = sk_stream_read;
217 fFTStream.close = sk_stream_close;
218}
219
reed@android.com62900b42009-02-11 15:07:19 +0000220// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000221static SkFaceRec* ref_ft_face(uint32_t fontID) {
222 SkFaceRec* rec = gFaceRecHead;
223 while (rec) {
224 if (rec->fFontID == fontID) {
225 SkASSERT(rec->fFace);
226 rec->fRefCnt += 1;
227 return rec;
228 }
229 rec = rec->fNext;
230 }
231
232 SkStream* strm = SkFontHost::OpenStream(fontID);
233 if (NULL == strm) {
234 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000235 return 0;
236 }
237
238 // this passes ownership of strm to the rec
239 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
240
241 FT_Open_Args args;
242 memset(&args, 0, sizeof(args));
243 const void* memoryBase = strm->getMemoryBase();
244
245 if (NULL != memoryBase) {
246//printf("mmap(%s)\n", keyString.c_str());
247 args.flags = FT_OPEN_MEMORY;
248 args.memory_base = (const FT_Byte*)memoryBase;
249 args.memory_size = strm->getLength();
250 } else {
251//printf("fopen(%s)\n", keyString.c_str());
252 args.flags = FT_OPEN_STREAM;
253 args.stream = &rec->fFTStream;
254 }
255
agl@chromium.org61a678a2010-08-06 18:08:18 +0000256 int face_index;
257 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
258 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
259 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000260
261 if (err) { // bad filename, try the default font
262 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
263 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000264 return 0;
265 } else {
266 SkASSERT(rec->fFace);
267 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
268 rec->fNext = gFaceRecHead;
269 gFaceRecHead = rec;
270 rec->fRefCnt = 1;
271 return rec;
272 }
273}
274
275static void unref_ft_face(FT_Face face) {
276 SkFaceRec* rec = gFaceRecHead;
277 SkFaceRec* prev = NULL;
278 while (rec) {
279 SkFaceRec* next = rec->fNext;
280 if (rec->fFace == face) {
281 if (--rec->fRefCnt == 0) {
282 if (prev) {
283 prev->fNext = next;
284 } else {
285 gFaceRecHead = next;
286 }
287 FT_Done_Face(face);
288 SkDELETE(rec);
289 }
290 return;
291 }
292 prev = rec;
293 rec = next;
294 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000295 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000296}
297
298///////////////////////////////////////////////////////////////////////////
299
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000300// Work around for old versions of freetype.
301static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
302 FT_Int32 loadFlags, FT_Fixed* advances) {
303#ifdef FT_ADVANCES_H
304 return FT_Get_Advances(face, start, count, loadFlags, advances);
305#else
306 if (!face || start >= face->num_glyphs ||
307 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
308 return 6; // "Invalid argument."
309 }
310 if (count == 0)
311 return 0;
312
313 for (int i = 0; i < count; i++) {
314 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
315 if (err)
316 return err;
317 advances[i] = face->glyph->advance.x;
318 }
319
320 return 0;
321#endif
322}
323
324static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000325#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000326 FT_UShort fsType = FT_Get_FSType_Flags(face);
327 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
328 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
329#else
330 // No embedding is 0x2 and bitmap embedding only is 0x200.
331 TT_OS2* os2_table;
332 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
333 return (os2_table->fsType & 0x202) == 0;
334 }
335 return false; // We tried, fail safe.
336#endif
337}
338
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000339static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
340 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
341 if (!glyph_id)
342 return false;
343 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
344 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
345 return true;
346}
347
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000348static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000349 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000350 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
351 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000352 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000353 SkASSERT(data);
354 *data = advance;
355 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000356}
357
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000358static void populate_glyph_to_unicode(FT_Face& face,
359 SkTDArray<SkUnichar>* glyphToUnicode) {
360 // Check and see if we have Unicode cmaps.
361 for (int i = 0; i < face->num_charmaps; ++i) {
362 // CMaps known to support Unicode:
363 // Platform ID Encoding ID Name
364 // ----------- ----------- -----------------------------------
365 // 0 0,1 Apple Unicode
366 // 0 3 Apple Unicode 2.0 (preferred)
367 // 3 1 Microsoft Unicode UCS-2
368 // 3 10 Microsoft Unicode UCS-4 (preferred)
369 //
370 // See Apple TrueType Reference Manual
371 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
372 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
373 // Microsoft OpenType Specification
374 // http://www.microsoft.com/typography/otspec/cmap.htm
375
376 FT_UShort platformId = face->charmaps[i]->platform_id;
377 FT_UShort encodingId = face->charmaps[i]->encoding_id;
378
379 if (platformId != 0 && platformId != 3) {
380 continue;
381 }
382 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
383 continue;
384 }
385 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
386 (platformId == 0 && encodingId == 3));
387
388 FT_Set_Charmap(face, face->charmaps[i]);
389 if (glyphToUnicode->isEmpty()) {
390 glyphToUnicode->setCount(face->num_glyphs);
391 memset(glyphToUnicode->begin(), 0,
392 sizeof(SkUnichar) * face->num_glyphs);
393 }
394
395 // Iterate through each cmap entry.
396 FT_UInt glyphIndex;
397 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
398 glyphIndex != 0;
399 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
400 if (charCode &&
401 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
402 (*glyphToUnicode)[glyphIndex] = charCode;
403 }
404 }
405 }
406}
407
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000408// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000409SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000410 uint32_t fontID,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000411 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
412 const uint32_t* glyphIDs,
413 uint32_t glyphIDsCount) {
djsollen@google.comda957722011-11-16 17:00:46 +0000414#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000415 return NULL;
416#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000417 SkAutoMutexAcquire ac(gFTMutex);
418 FT_Library libInit = NULL;
419 if (gFTCount == 0) {
420 if (!InitFreetype())
421 sk_throw();
422 libInit = gFTLibrary;
423 }
424 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
425 SkFaceRec* rec = ref_ft_face(fontID);
426 if (NULL == rec)
427 return NULL;
428 FT_Face face = rec->fFace;
429
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000430 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
431 info->fFontName.set(FT_Get_Postscript_Name(face));
432 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
433 info->fLastGlyphID = face->num_glyphs - 1;
434 info->fEmSize = 1000;
435
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000436 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000437 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000438 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000439 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000440 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000441 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000442 cid = true;
443 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000444 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000445 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000446 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000447 cid = true;
448 TT_Header* ttHeader;
449 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
450 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000451 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000452 }
453 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000455 info->fStyle = 0;
456 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000457 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000458 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000459 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000460 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
461 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000462 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
463
464 PS_FontInfoRec ps_info;
465 TT_Postscript* tt_info;
466 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
467 info->fItalicAngle = ps_info.italic_angle;
468 } else if ((tt_info =
469 (TT_Postscript*)FT_Get_Sfnt_Table(face,
470 ft_sfnt_post)) != NULL) {
471 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
472 } else {
473 info->fItalicAngle = 0;
474 }
475
476 info->fAscent = face->ascender;
477 info->fDescent = face->descender;
478
479 // Figure out a good guess for StemV - Min width of i, I, !, 1.
480 // This probably isn't very good with an italic font.
481 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000482 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000483 char stem_chars[] = {'i', 'I', '!', '1'};
484 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
485 FT_BBox bbox;
486 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
487 int16_t width = bbox.xMax - bbox.xMin;
488 if (width > 0 && width < min_width) {
489 min_width = width;
490 info->fStemV = min_width;
491 }
492 }
493 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000494
495 TT_PCLT* pclt_info;
496 TT_OS2* os2_table;
497 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
498 info->fCapHeight = pclt_info->CapHeight;
499 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
500 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000501 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000502 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000503 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000504 } else if ((os2_table =
505 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
506 info->fCapHeight = os2_table->sCapHeight;
507 } else {
508 // Figure out a good guess for CapHeight: average the height of M and X.
509 FT_BBox m_bbox, x_bbox;
510 bool got_m, got_x;
511 got_m = GetLetterCBox(face, 'M', &m_bbox);
512 got_x = GetLetterCBox(face, 'X', &x_bbox);
513 if (got_m && got_x) {
514 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
515 x_bbox.yMin) / 2;
516 } else if (got_m && !got_x) {
517 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
518 } else if (!got_m && got_x) {
519 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
520 }
521 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000522
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000523 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
524 face->bbox.xMax, face->bbox.yMin);
525
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000526 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000527 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
528 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
529 }
530
531 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000532 if (FT_IS_FIXED_WIDTH(face)) {
533 appendRange(&info->fGlyphWidths, 0);
534 int16_t advance = face->max_advance_width;
535 info->fGlyphWidths->fAdvance.append(1, &advance);
536 finishRange(info->fGlyphWidths.get(), 0,
537 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000538 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000539 appendRange(&info->fGlyphWidths, 0);
540 // So as to not blow out the stack, get advances in batches.
541 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
542 FT_Fixed advances[128];
543 int advanceCount = 128;
544 if (gID + advanceCount > face->num_glyphs)
545 advanceCount = face->num_glyphs - gID + 1;
546 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
547 advances);
548 for (int i = 0; i < advanceCount; i++) {
549 int16_t advance = advances[gID + i];
550 info->fGlyphWidths->fAdvance.append(1, &advance);
551 }
552 }
553 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
554 SkAdvancedTypefaceMetrics::WidthRange::kRange);
555 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000556 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000557 getAdvanceData(face,
558 face->num_glyphs,
559 glyphIDs,
560 glyphIDsCount,
561 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000562 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000563 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000564
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000565 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
566 FT_HAS_VERTICAL(face)) {
567 SkASSERT(false); // Not implemented yet.
568 }
569
570 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
571 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
572 // Postscript fonts may contain more than 255 glyphs, so we end up
573 // using multiple font descriptions with a glyph ordering. Record
574 // the name of each glyph.
575 info->fGlyphNames.reset(
576 new SkAutoTArray<SkString>(face->num_glyphs));
577 for (int gID = 0; gID < face->num_glyphs; gID++) {
578 char glyphName[128]; // PS limit for names is 127 bytes.
579 FT_Get_Glyph_Name(face, gID, glyphName, 128);
580 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000581 }
582 }
583
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000584 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
585 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
586 face->num_charmaps) {
587 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
588 }
589
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000590 if (!canEmbed(face))
591 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
592
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000593 unref_ft_face(face);
594 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000595#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000596}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000597
reed@google.com618ef5e2011-01-26 22:10:41 +0000598///////////////////////////////////////////////////////////////////////////
599
reed@google.comffe49f52011-11-22 19:42:41 +0000600#define BLACK_LUMINANCE_LIMIT 0x40
601#define WHITE_LUMINANCE_LIMIT 0xA0
602
reed@google.com8ed436c2011-07-21 14:12:36 +0000603static bool bothZero(SkScalar a, SkScalar b) {
604 return 0 == a && 0 == b;
605}
606
607// returns false if there is any non-90-rotation or skew
608static bool isAxisAligned(const SkScalerContext::Rec& rec) {
609 return 0 == rec.fPreSkewX &&
610 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
611 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
612}
613
reed@google.com618ef5e2011-01-26 22:10:41 +0000614void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
615 if (!gLCDSupportValid) {
616 InitFreetype();
617 FT_Done_FreeType(gFTLibrary);
618 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000619
reed@google.comeffc5012011-06-27 16:44:46 +0000620 if (!gLCDSupport && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000621 // If the runtime Freetype library doesn't support LCD mode, we disable
622 // it here.
623 rec->fMaskFormat = SkMask::kA8_Format;
624 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000625
reed@google.com618ef5e2011-01-26 22:10:41 +0000626 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000627 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000628 // collapse full->normal hinting if we're not doing LCD
629 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000630 }
reed@google.com1ac83502012-02-28 17:06:02 +0000631 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) || isLCD(*rec)) {
632 if (SkPaint::kNo_Hinting != h) {
633 h = SkPaint::kSlight_Hinting;
634 }
635 }
636
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000637#ifndef SK_IGNORE_ROTATED_FREETYPE_FIX
reed@google.com8ed436c2011-07-21 14:12:36 +0000638 // rotated text looks bad with hinting, so we disable it as needed
639 if (!isAxisAligned(*rec)) {
640 h = SkPaint::kNo_Hinting;
641 }
bsalomon@google.com0e35ca82011-07-22 17:56:19 +0000642#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000643 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000644
reed@google.com1ac83502012-02-28 17:06:02 +0000645#ifndef SK_USE_COLOR_LUMINANCE
reed@google.comffe49f52011-11-22 19:42:41 +0000646 // 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.com1ac83502012-02-28 17:06:02 +0000665#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000666}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000667
djsollen@google.comda957722011-11-16 17:00:46 +0000668#ifdef SK_BUILD_FOR_ANDROID
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000669uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
670 SkAutoMutexAcquire ac(gFTMutex);
671 SkFaceRec *rec = ref_ft_face(fontID);
672 uint16_t unitsPerEm = 0;
673
674 if (rec != NULL && rec->fFace != NULL) {
675 unitsPerEm = rec->fFace->units_per_EM;
676 unref_ft_face(rec->fFace);
677 }
678
679 return (uint32_t)unitsPerEm;
680}
681#endif
682
reed@android.com8a1c16f2008-12-17 15:59:43 +0000683SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000684 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000685 SkAutoMutexAcquire ac(gFTMutex);
686
reed@android.com8a1c16f2008-12-17 15:59:43 +0000687 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000688 if (!InitFreetype()) {
689 sk_throw();
690 }
reed@google.comffe49f52011-11-22 19:42:41 +0000691 SkFontHost::GetGammaTables(gGammaTables);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000692 }
693 ++gFTCount;
694
695 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000696 fFTSize = NULL;
697 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000698 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000699 if (NULL == fFaceRec) {
700 return;
701 }
702 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000703
704 // compute our factors from the record
705
706 SkMatrix m;
707
708 fRec.getSingleMatrix(&m);
709
710#ifdef DUMP_STRIKE_CREATION
711 SkString keyString;
712 SkFontHost::GetDescriptorKeyString(desc, &keyString);
713 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
714 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
715 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
716 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000717 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000718#endif
719
720 // now compute our scale factors
721 SkScalar sx = m.getScaleX();
722 SkScalar sy = m.getScaleY();
723
724 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
725 // sort of give up on hinting
726 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
727 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
728 sx = sy = SkScalarAve(sx, sy);
729
730 SkScalar inv = SkScalarInvert(sx);
731
732 // flip the skew elements to go from our Y-down system to FreeType's
733 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
734 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
735 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
736 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
737 } else {
738 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
739 fMatrix22.xy = fMatrix22.yx = 0;
740 }
741
742 fScaleX = SkScalarToFixed(sx);
743 fScaleY = SkScalarToFixed(sy);
744
745 // compute the flags we send to Load_Glyph
746 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000747 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@google.combdc99882011-11-21 14:36:57 +0000748 bool linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000749
agl@chromium.org70a303f2010-05-10 14:15:50 +0000750 if (SkMask::kBW_Format == fRec.fMaskFormat) {
751 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
752 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000753 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000754 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000755 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000756 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000757 } else {
758 switch (fRec.getHinting()) {
759 case SkPaint::kNo_Hinting:
760 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000761 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000762 break;
763 case SkPaint::kSlight_Hinting:
764 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@google.combdc99882011-11-21 14:36:57 +0000765 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000766 break;
767 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000768 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
769 loadFlags = FT_LOAD_FORCE_AUTOHINT;
770 else
771 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000772 break;
773 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000774 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
775 loadFlags = FT_LOAD_FORCE_AUTOHINT;
776 break;
777 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000778 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000779 if (isLCD(fRec)) {
780 if (fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag) {
781 loadFlags = FT_LOAD_TARGET_LCD_V;
782 } else {
783 loadFlags = FT_LOAD_TARGET_LCD;
784 }
reed@google.comea2333d2011-03-14 16:44:56 +0000785 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000786 break;
787 default:
788 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
789 break;
790 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000791 }
792
reed@google.comeffc5012011-06-27 16:44:46 +0000793 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000794 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000795 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000796
reed@google.com96a9f7912011-05-06 11:49:30 +0000797 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
798 // advances, as fontconfig and cairo do.
799 // See http://code.google.com/p/skia/issues/detail?id=222.
800 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
801
reed@android.come4d0bc02009-07-24 19:53:20 +0000802 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000803 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000804 }
805
806 // now create the FT_Size
807
808 {
809 FT_Error err;
810
811 err = FT_New_Size(fFace, &fFTSize);
812 if (err != 0) {
813 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
814 fFaceRec->fFontID, fScaleX, fScaleY, err));
815 fFace = NULL;
816 return;
817 }
818
819 err = FT_Activate_Size(fFTSize);
820 if (err != 0) {
821 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
822 fFaceRec->fFontID, fScaleX, fScaleY, err));
823 fFTSize = NULL;
824 }
825
826 err = FT_Set_Char_Size( fFace,
827 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
828 72, 72);
829 if (err != 0) {
830 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
831 fFaceRec->fFontID, fScaleX, fScaleY, err));
832 fFace = NULL;
833 return;
834 }
835
836 FT_Set_Transform( fFace, &fMatrix22, NULL);
837 }
838}
839
840SkScalerContext_FreeType::~SkScalerContext_FreeType() {
841 if (fFTSize != NULL) {
842 FT_Done_Size(fFTSize);
843 }
844
845 SkAutoMutexAcquire ac(gFTMutex);
846
847 if (fFace != NULL) {
848 unref_ft_face(fFace);
849 }
850 if (--gFTCount == 0) {
851// SkDEBUGF(("FT_Done_FreeType\n"));
852 FT_Done_FreeType(gFTLibrary);
853 SkDEBUGCODE(gFTLibrary = NULL;)
854 }
855}
856
857/* We call this before each use of the fFace, since we may be sharing
858 this face with other context (at different sizes).
859*/
860FT_Error SkScalerContext_FreeType::setupSize() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000861 FT_Error err = FT_Activate_Size(fFTSize);
862
863 if (err != 0) {
864 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
865 fFaceRec->fFontID, fScaleX, fScaleY, err));
866 fFTSize = NULL;
867 } else {
868 // seems we need to reset this every time (not sure why, but without it
869 // I get random italics from some other fFTSize)
870 FT_Set_Transform( fFace, &fMatrix22, NULL);
871 }
872 return err;
873}
874
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000875void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
876 FT_Pos strength;
877 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
878 / 24;
879 FT_Outline_Embolden(outline, strength);
880}
881
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000882unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000883 return fFace->num_glyphs;
884}
885
886uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
887 return SkToU16(FT_Get_Char_Index( fFace, uni ));
888}
889
reed@android.com9d3a9852010-01-08 14:07:42 +0000890SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
891 // iterate through each cmap entry, looking for matching glyph indices
892 FT_UInt glyphIndex;
893 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
894
895 while (glyphIndex != 0) {
896 if (glyphIndex == glyph) {
897 return charCode;
898 }
899 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
900 }
901
902 return 0;
903}
904
reed@android.com8a1c16f2008-12-17 15:59:43 +0000905static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
906 switch (format) {
907 case SkMask::kBW_Format:
908 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000909 case SkMask::kA8_Format:
910 default:
911 return FT_PIXEL_MODE_GRAY;
912 }
913}
914
reed@android.com8a1c16f2008-12-17 15:59:43 +0000915void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
916#ifdef FT_ADVANCES_H
917 /* unhinted and light hinted text have linearly scaled advances
918 * which are very cheap to compute with some font formats...
919 */
reed@google.combdc99882011-11-21 14:36:57 +0000920 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000921 SkAutoMutexAcquire ac(gFTMutex);
922
923 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000924 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925 return;
926 }
927
928 FT_Error error;
929 FT_Fixed advance;
930
931 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
932 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
933 &advance );
934 if (0 == error) {
935 glyph->fRsbDelta = 0;
936 glyph->fLsbDelta = 0;
937 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
938 glyph->fAdvanceY = 0;
939 return;
940 }
941 }
942#endif /* FT_ADVANCES_H */
943 /* otherwise, we need to load/hint the glyph, which is slower */
944 this->generateMetrics(glyph);
945 return;
946}
947
948void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
949 SkAutoMutexAcquire ac(gFTMutex);
950
951 glyph->fRsbDelta = 0;
952 glyph->fLsbDelta = 0;
953
954 FT_Error err;
955
956 if (this->setupSize()) {
957 goto ERROR;
958 }
959
960 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
961 if (err != 0) {
962 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
963 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
964 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000965 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000966 return;
967 }
968
969 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +0000970 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000971 FT_BBox bbox;
972
bungeman@google.com0f0c2882011-11-04 15:47:41 +0000973 if (0 == fFace->glyph->outline.n_contours) {
974 glyph->fWidth = 0;
975 glyph->fHeight = 0;
976 glyph->fTop = 0;
977 glyph->fLeft = 0;
978 break;
979 }
980
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000981 if (fRec.fFlags & kEmbolden_Flag) {
982 emboldenOutline(&fFace->glyph->outline);
983 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000984 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
985
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000986 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000987 int dx = glyph->getSubXFixed() >> 10;
988 int dy = glyph->getSubYFixed() >> 10;
989 // negate dy since freetype-y-goes-up and skia-y-goes-down
990 bbox.xMin += dx;
991 bbox.yMin -= dy;
992 bbox.xMax += dx;
993 bbox.yMax -= dy;
994 }
995
996 bbox.xMin &= ~63;
997 bbox.yMin &= ~63;
998 bbox.xMax = (bbox.xMax + 63) & ~63;
999 bbox.yMax = (bbox.yMax + 63) & ~63;
1000
1001 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
1002 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
1003 glyph->fTop = -SkToS16(bbox.yMax >> 6);
1004 glyph->fLeft = SkToS16(bbox.xMin >> 6);
1005 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001006 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001007
1008 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001009 if (fRec.fFlags & kEmbolden_Flag) {
1010 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1011 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1012 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1014 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1015 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1016 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1017 break;
1018
1019 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001020 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001021 goto ERROR;
1022 }
1023
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001024 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001025 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1026 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1027 if (fRec.fFlags & kDevKernText_Flag) {
1028 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1029 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1030 }
1031 } else {
1032 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1033 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1034 }
1035
1036#ifdef ENABLE_GLYPH_SPEW
1037 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1038 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1039#endif
1040}
1041
reed@google.com1ac83502012-02-28 17:06:02 +00001042///////////////////////////////////////////////////////////////////////////////
1043
1044static int apply_contrast(int srca, int contrast) {
1045 return srca + (((255 - srca) * contrast * srca) / (255*255));
reed@google.comc5181342011-05-17 20:52:46 +00001046}
1047
reed@google.com1ac83502012-02-28 17:06:02 +00001048static void build_power_table(uint8_t table[], float ee) {
1049 for (int i = 0; i < 256; i++) {
1050 float x = i / 255.f;
1051 x = powf(x, ee);
1052 int xx = SkScalarRoundToInt(SkFloatToScalar(x * 255));
1053 table[i] = SkToU8(xx);
reed@google.comc5181342011-05-17 20:52:46 +00001054 }
reed@google.com1ac83502012-02-28 17:06:02 +00001055}
1056
1057static void build_gamma_table(uint8_t table[256], int src, int dst) {
1058 static bool gInit;
1059 static uint8_t powTable[256], invPowTable[256];
1060 if (!gInit) {
1061 const float g = SK_GAMMA_EXPONENT;
1062 build_power_table(powTable, g);
1063 build_power_table(invPowTable, 1/g);
1064 gInit = true;
1065 }
reed@google.com1ac83502012-02-28 17:06:02 +00001066
reed@google.com613e9fe2012-02-29 15:08:00 +00001067 const int linSrc = powTable[src];
1068 const int linDst = powTable[dst];
1069 // have our contrast value taper off to 0 as the src luminance becomes white
1070 const int contrast = SK_GAMMA_CONTRAST * (255 - linSrc) / 255;
1071
reed@google.com1ac83502012-02-28 17:06:02 +00001072 for (int i = 0; i < 256; ++i) {
reed@google.com613e9fe2012-02-29 15:08:00 +00001073 int srca = apply_contrast(i, contrast);
1074 SkASSERT((unsigned)srca <= 255);
reed@google.com1ac83502012-02-28 17:06:02 +00001075 int dsta = 255 - srca;
1076
1077 //Calculate the output we want.
1078 int linOut = (linSrc * srca + dsta * linDst) / 255;
1079 SkASSERT((unsigned)linOut <= 255);
1080 int out = invPowTable[linOut];
1081
1082 //Undo what the blit blend will do.
1083 int result = ((255 * out) - (255 * dst)) / (src - dst);
1084 SkASSERT((unsigned)result <= 255);
1085
reed@google.com613e9fe2012-02-29 15:08:00 +00001086 table[i] = result;
reed@google.com1ac83502012-02-28 17:06:02 +00001087 }
1088}
1089
1090static const uint8_t* getGammaTable(U8CPU luminance) {
1091 static uint8_t gGammaTables[4][256];
1092 static bool gInited;
1093 if (!gInited) {
1094 build_gamma_table(gGammaTables[0], 0x00, 0xFF);
1095 build_gamma_table(gGammaTables[1], 0x55, 0xAA);
1096 build_gamma_table(gGammaTables[2], 0xAA, 0x55);
1097 build_gamma_table(gGammaTables[3], 0xFF, 0x00);
1098
1099 gInited = true;
1100 }
1101 SkASSERT(0 == (luminance >> 8));
1102 return gGammaTables[luminance >> 6];
1103}
1104
1105
1106
1107static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
reed@google.comc5181342011-05-17 20:52:46 +00001108 return SkPackRGB16(r >> 3, g >> 2, b >> 3);
1109}
1110
reed@google.com73824072011-06-23 13:17:30 +00001111static uint16_t grayToRGB16(U8CPU gray) {
1112 SkASSERT(gray <= 255);
1113 return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3);
1114}
1115
1116static int bittst(const uint8_t data[], int bitOffset) {
1117 SkASSERT(bitOffset >= 0);
reed@google.comc8e0f932011-06-23 19:39:49 +00001118 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
reed@google.com73824072011-06-23 13:17:30 +00001119 return lowBit & 1;
1120}
1121
reed@google.comeffc5012011-06-27 16:44:46 +00001122static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001123 int lcdIsBGR, const uint8_t* tableR,
1124 const uint8_t* tableG, const uint8_t* tableB) {
reed@google.comea2333d2011-03-14 16:44:56 +00001125 SkASSERT(glyph.fHeight == bitmap.rows);
reed@google.comea2333d2011-03-14 16:44:56 +00001126 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
reed@google.com73824072011-06-23 13:17:30 +00001127 const size_t dstRB = glyph.rowBytes();
1128 const int width = glyph.fWidth;
1129 const uint8_t* src = bitmap.buffer;
reed@google.comea2333d2011-03-14 16:44:56 +00001130
reed@google.com73824072011-06-23 13:17:30 +00001131 switch (bitmap.pixel_mode) {
1132 case FT_PIXEL_MODE_MONO: {
1133 for (int y = 0; y < glyph.fHeight; ++y) {
1134 for (int x = 0; x < width; ++x) {
1135 dst[x] = -bittst(src, x);
1136 }
1137 dst = (uint16_t*)((char*)dst + dstRB);
1138 src += bitmap.pitch;
1139 }
1140 } break;
1141 case FT_PIXEL_MODE_GRAY: {
1142 for (int y = 0; y < glyph.fHeight; ++y) {
1143 for (int x = 0; x < width; ++x) {
1144 dst[x] = grayToRGB16(src[x]);
1145 }
1146 dst = (uint16_t*)((char*)dst + dstRB);
1147 src += bitmap.pitch;
1148 }
1149 } break;
1150 default: {
1151 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
1152 src += 3;
1153 for (int y = 0; y < glyph.fHeight; y++) {
1154 const uint8_t* triple = src;
reed@google.comeffc5012011-06-27 16:44:46 +00001155 if (lcdIsBGR) {
1156 for (int x = 0; x < width; x++) {
reed@google.com1ac83502012-02-28 17:06:02 +00001157 dst[x] = packTriple(tableR[triple[2]],
1158 tableG[triple[1]],
1159 tableB[triple[0]]);
reed@google.comeffc5012011-06-27 16:44:46 +00001160 triple += 3;
1161 }
1162 } else {
1163 for (int x = 0; x < width; x++) {
reed@google.com1ac83502012-02-28 17:06:02 +00001164 dst[x] = packTriple(tableR[triple[0]],
1165 tableG[triple[1]],
1166 tableB[triple[2]]);
reed@google.comeffc5012011-06-27 16:44:46 +00001167 triple += 3;
1168 }
reed@google.com73824072011-06-23 13:17:30 +00001169 }
1170 src += bitmap.pitch;
1171 dst = (uint16_t*)((char*)dst + dstRB);
1172 }
1173 } break;
reed@google.comea2333d2011-03-14 16:44:56 +00001174 }
1175}
1176
reed@android.com8a1c16f2008-12-17 15:59:43 +00001177void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1178 SkAutoMutexAcquire ac(gFTMutex);
1179
1180 FT_Error err;
1181
1182 if (this->setupSize()) {
1183 goto ERROR;
1184 }
1185
1186 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1187 if (err != 0) {
1188 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1189 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1190 ERROR:
1191 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1192 return;
1193 }
1194
reed@google.com1ac83502012-02-28 17:06:02 +00001195#ifdef SK_USE_COLOR_LUMINANCE
1196 SkColor lumColor = fRec.getLuminanceColor();
1197 const uint8_t* tableR = getGammaTable(SkColorGetR(lumColor));
1198 const uint8_t* tableG = getGammaTable(SkColorGetG(lumColor));
1199 const uint8_t* tableB = getGammaTable(SkColorGetB(lumColor));
1200#else
1201 unsigned lum = fRec.getLuminanceByte();
1202 const uint8_t* tableR = getGammaTable(lum);
1203 const uint8_t* tableG = getGammaTable(lum);
1204 const uint8_t* tableB = getGammaTable(lum);
1205#endif
1206
reed@android.com8a1c16f2008-12-17 15:59:43 +00001207 switch ( fFace->glyph->format ) {
1208 case FT_GLYPH_FORMAT_OUTLINE: {
1209 FT_Outline* outline = &fFace->glyph->outline;
1210 FT_BBox bbox;
1211 FT_Bitmap target;
1212
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001213 if (fRec.fFlags & kEmbolden_Flag) {
1214 emboldenOutline(outline);
1215 }
1216
reed@android.com8a1c16f2008-12-17 15:59:43 +00001217 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001218 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001219 dx = glyph.getSubXFixed() >> 10;
1220 dy = glyph.getSubYFixed() >> 10;
1221 // negate dy since freetype-y-goes-up and skia-y-goes-down
1222 dy = -dy;
1223 }
1224 FT_Outline_Get_CBox(outline, &bbox);
1225 /*
1226 what we really want to do for subpixel is
1227 offset(dx, dy)
1228 compute_bounds
1229 offset(bbox & !63)
1230 but that is two calls to offset, so we do the following, which
1231 achieves the same thing with only one offset call.
1232 */
1233 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1234 dy - ((bbox.yMin + dy) & ~63));
1235
reed@google.comea2333d2011-03-14 16:44:56 +00001236 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1237 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
reed@google.comeffc5012011-06-27 16:44:46 +00001238 copyFT2LCD16(glyph, fFace->glyph->bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001239 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1240 tableR, tableG, tableB);
reed@google.comea2333d2011-03-14 16:44:56 +00001241 } else {
1242 target.width = glyph.fWidth;
1243 target.rows = glyph.fHeight;
1244 target.pitch = glyph.rowBytes();
1245 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1246 target.pixel_mode = compute_pixel_mode(
1247 (SkMask::Format)fRec.fMaskFormat);
1248 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001249
reed@google.comea2333d2011-03-14 16:44:56 +00001250 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1251 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1252 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253 } break;
1254
1255 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001256 if (fRec.fFlags & kEmbolden_Flag) {
1257 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1258 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1259 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001260 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1261 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1262 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1263 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1264
1265 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1266 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001267
agl@chromium.org558434a2009-08-11 17:22:38 +00001268 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1269 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1270 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001271 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1272 unsigned dstRowBytes = glyph.rowBytes();
1273 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1274 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1275
1276 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1277 memcpy(dst, src, minRowBytes);
1278 memset(dst + minRowBytes, 0, extraRowBytes);
1279 src += srcRowBytes;
1280 dst += dstRowBytes;
1281 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001282 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
reed@google.comeffc5012011-06-27 16:44:46 +00001283 glyph.fMaskFormat == SkMask::kA8_Format) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001284 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1285 uint8_t byte = 0;
1286 int bits = 0;
1287 const uint8_t* src_row = src;
1288 uint8_t* dst_row = dst;
1289
1290 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1291 if (!bits) {
1292 byte = *src_row++;
1293 bits = 8;
1294 }
1295
1296 *dst_row++ = byte & 0x80 ? 0xff : 0;
1297 bits--;
1298 byte <<= 1;
1299 }
1300
1301 src += fFace->glyph->bitmap.pitch;
1302 dst += glyph.rowBytes();
1303 }
reed@google.com73824072011-06-23 13:17:30 +00001304 } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
reed@google.comeffc5012011-06-27 16:44:46 +00001305 copyFT2LCD16(glyph, fFace->glyph->bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001306 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1307 tableR, tableG, tableB);
agl@chromium.org558434a2009-08-11 17:22:38 +00001308 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001309 SkDEBUGFAIL("unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001310 }
1311 } break;
1312
1313 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001314 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001315 goto ERROR;
1316 }
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001317
reed@google.com1ac83502012-02-28 17:06:02 +00001318#ifdef SK_GAMMA_APPLY_TO_A8
1319 if (SkMask::kA8_Format == glyph.fMaskFormat) {
1320 SkASSERT(tableR == tableG && tableR == tableB);
1321 const uint8_t* table = tableR;
1322 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1323 unsigned rowBytes = glyph.rowBytes();
1324
1325 for (int y = glyph.fHeight - 1; y >= 0; --y) {
1326 for (int x = glyph.fWidth - 1; x >= 0; --x) {
1327 dst[x] = table[dst[x]];
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001328 }
reed@google.com1ac83502012-02-28 17:06:02 +00001329 dst += rowBytes;
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001330 }
1331 }
reed@google.com1ac83502012-02-28 17:06:02 +00001332#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001333}
1334
1335///////////////////////////////////////////////////////////////////////////////
1336
1337#define ft2sk(x) SkFixedToScalar((x) << 10)
1338
reed@android.com6f252972009-01-14 16:46:16 +00001339#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001340 #define CONST_PARAM const
1341#else // older freetype doesn't use const here
1342 #define CONST_PARAM
1343#endif
1344
1345static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1346 SkPath* path = (SkPath*)ctx;
1347 path->close(); // to close the previous contour (if any)
1348 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1349 return 0;
1350}
1351
1352static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1353 SkPath* path = (SkPath*)ctx;
1354 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1355 return 0;
1356}
1357
1358static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1359 void* ctx) {
1360 SkPath* path = (SkPath*)ctx;
1361 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1362 return 0;
1363}
1364
1365static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1366 CONST_PARAM FT_Vector* pt2, void* ctx) {
1367 SkPath* path = (SkPath*)ctx;
1368 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1369 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1370 return 0;
1371}
1372
1373void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1374 SkPath* path) {
1375 SkAutoMutexAcquire ac(gFTMutex);
1376
1377 SkASSERT(&glyph && path);
1378
1379 if (this->setupSize()) {
1380 path->reset();
1381 return;
1382 }
1383
1384 uint32_t flags = fLoadGlyphFlags;
1385 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1386 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1387
1388 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1389
1390 if (err != 0) {
1391 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1392 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1393 path->reset();
1394 return;
1395 }
1396
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001397 if (fRec.fFlags & kEmbolden_Flag) {
1398 emboldenOutline(&fFace->glyph->outline);
1399 }
1400
reed@android.com8a1c16f2008-12-17 15:59:43 +00001401 FT_Outline_Funcs funcs;
1402
1403 funcs.move_to = move_proc;
1404 funcs.line_to = line_proc;
1405 funcs.conic_to = quad_proc;
1406 funcs.cubic_to = cubic_proc;
1407 funcs.shift = 0;
1408 funcs.delta = 0;
1409
1410 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1411
1412 if (err != 0) {
1413 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1414 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1415 path->reset();
1416 return;
1417 }
1418
1419 path->close();
1420}
1421
1422void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1423 SkPaint::FontMetrics* my) {
1424 if (NULL == mx && NULL == my) {
1425 return;
1426 }
1427
1428 SkAutoMutexAcquire ac(gFTMutex);
1429
1430 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001431 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001432 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001433 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001434 }
1435 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001436 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001437 }
1438 return;
1439 }
1440
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001441 FT_Face face = fFace;
1442 int upem = face->units_per_EM;
1443 if (upem <= 0) {
1444 goto ERROR;
1445 }
1446
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001447 SkPoint pts[6];
1448 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001449 SkFixed scaleY = fScaleY;
1450 SkFixed mxy = fMatrix22.xy;
1451 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001452 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1453 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001454
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001455 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001456 if (leading < 0) {
1457 leading = 0;
1458 }
1459
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001460 // Try to get the OS/2 table from the font. This contains the specific
1461 // average font width metrics which Windows uses.
1462 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1463
reed@android.com8a1c16f2008-12-17 15:59:43 +00001464 ys[0] = -face->bbox.yMax;
1465 ys[1] = -face->ascender;
1466 ys[2] = -face->descender;
1467 ys[3] = -face->bbox.yMin;
1468 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001469 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1470
1471 SkScalar x_height;
1472 if (os2 && os2->sxHeight) {
1473 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1474 } else {
1475 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1476 if (x_glyph) {
1477 FT_BBox bbox;
1478 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001479 if (fRec.fFlags & kEmbolden_Flag) {
1480 emboldenOutline(&fFace->glyph->outline);
1481 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001482 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
epoger@google.comb90113d2012-01-18 19:20:39 +00001483 x_height = SkFixedToScalar(SkFDot6ToFixed(bbox.yMax));
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001484 } else {
1485 x_height = 0;
1486 }
1487 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001488
1489 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001490 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001491 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1492 SkFixed x = SkFixedMul(mxy, y);
1493 y = SkFixedMul(myy, y);
1494 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1495 }
1496
1497 if (mx) {
1498 mx->fTop = pts[0].fX;
1499 mx->fAscent = pts[1].fX;
1500 mx->fDescent = pts[2].fX;
1501 mx->fBottom = pts[3].fX;
1502 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001503 mx->fAvgCharWidth = pts[5].fX;
1504 mx->fXMin = xmin;
1505 mx->fXMax = xmax;
1506 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001507 }
1508 if (my) {
1509 my->fTop = pts[0].fY;
1510 my->fAscent = pts[1].fY;
1511 my->fDescent = pts[2].fY;
1512 my->fBottom = pts[3].fY;
1513 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001514 my->fAvgCharWidth = pts[5].fY;
1515 my->fXMin = xmin;
1516 my->fXMax = xmax;
1517 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001518 }
1519}
1520
1521////////////////////////////////////////////////////////////////////////
1522////////////////////////////////////////////////////////////////////////
1523
1524SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001525 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1526 if (!c->success()) {
1527 SkDELETE(c);
1528 c = NULL;
1529 }
1530 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001531}
1532
1533///////////////////////////////////////////////////////////////////////////////
1534
1535/* Export this so that other parts of our FonttHost port can make use of our
1536 ability to extract the name+style from a stream, using FreeType's api.
1537*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001538bool find_name_and_attributes(SkStream* stream, SkString* name,
1539 SkTypeface::Style* style, bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001540 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001541 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001542 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001543 }
1544
1545 FT_Open_Args args;
1546 memset(&args, 0, sizeof(args));
1547
1548 const void* memoryBase = stream->getMemoryBase();
1549 FT_StreamRec streamRec;
1550
1551 if (NULL != memoryBase) {
1552 args.flags = FT_OPEN_MEMORY;
1553 args.memory_base = (const FT_Byte*)memoryBase;
1554 args.memory_size = stream->getLength();
1555 } else {
1556 memset(&streamRec, 0, sizeof(streamRec));
1557 streamRec.size = stream->read(NULL, 0);
1558 streamRec.descriptor.pointer = stream;
1559 streamRec.read = sk_stream_read;
1560 streamRec.close = sk_stream_close;
1561
1562 args.flags = FT_OPEN_STREAM;
1563 args.stream = &streamRec;
1564 }
1565
1566 FT_Face face;
1567 if (FT_Open_Face(library, &args, 0, &face)) {
1568 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001569 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001570 }
1571
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001572 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001573 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001574 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001575 }
1576 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001577 tempStyle |= SkTypeface::kItalic;
1578 }
1579
1580 if (name) {
1581 name->set(face->family_name);
1582 }
1583 if (style) {
1584 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001585 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001586 if (isFixedWidth) {
1587 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1588 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001589
1590 FT_Done_Face(face);
1591 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001592 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001593}