blob: f81f37241927fc8cb5055a387e4e3782f95c5a9d [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.comec9ed812012-03-01 19:40:21 +000058
59#ifndef SK_GAMMA_CONTRAST
60 #define SK_GAMMA_CONTRAST 0x66
61#endif
62#ifndef SK_GAMMA_EXPONENT
63 #define SK_GAMMA_EXPONENT 2.2
64#endif
reed@google.com1ac83502012-02-28 17:06:02 +000065
reed@android.com8a1c16f2008-12-17 15:59:43 +000066#ifdef SK_DEBUG
67 #define SkASSERT_CONTINUE(pred) \
68 do { \
69 if (!(pred)) \
70 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
71 } while (false)
72#else
73 #define SkASSERT_CONTINUE(pred)
74#endif
75
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000076using namespace skia_advanced_typeface_metrics_utils;
77
reed@google.comeffc5012011-06-27 16:44:46 +000078static bool isLCD(const SkScalerContext::Rec& rec) {
79 switch (rec.fMaskFormat) {
80 case SkMask::kLCD16_Format:
81 case SkMask::kLCD32_Format:
82 return true;
83 default:
84 return false;
85 }
86}
87
reed@android.com8a1c16f2008-12-17 15:59:43 +000088//////////////////////////////////////////////////////////////////////////
89
90struct SkFaceRec;
91
digit@google.com1771cbf2012-01-26 21:26:40 +000092SK_DECLARE_STATIC_MUTEX(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +000093static int gFTCount;
94static FT_Library gFTLibrary;
95static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000096static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
97static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@google.coma1c32562012-03-01 19:38:23 +000098static int gLCDExtra; // number of extra pixels for filtering.
reed@android.com8a1c16f2008-12-17 15:59:43 +000099
reed@google.comffe49f52011-11-22 19:42:41 +0000100static const uint8_t* gGammaTables[2];
101
reed@android.com8a1c16f2008-12-17 15:59:43 +0000102/////////////////////////////////////////////////////////////////////////
103
agl@chromium.orge76073b2010-06-04 20:31:17 +0000104// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
105// This value was chosen by eyeballing the result in Firefox and trying to match it.
106static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
107
agl@chromium.org309485b2009-07-21 17:41:32 +0000108static bool
109InitFreetype() {
110 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +0000111 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000112 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000113 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000114
agl@chromium.org309485b2009-07-21 17:41:32 +0000115 // Setup LCD filtering. This reduces colour fringes for LCD rendered
116 // glyphs.
epoger@google.comb371ed12011-06-29 21:20:52 +0000117#ifdef FT_LCD_FILTER_H
bungeman@google.comd2dae962012-03-09 20:31:17 +0000118 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
119// err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_LIGHT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000120 gLCDSupport = err == 0;
reed@google.coma1c32562012-03-01 19:38:23 +0000121 if (gLCDSupport) {
122 gLCDExtra = 2; //DEFAULT and LIGHT add one pixel to each side.
123 }
epoger@google.com5070d792011-06-29 20:43:14 +0000124#else
125 gLCDSupport = false;
126#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000127 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000128
129 return true;
130}
131
reed@android.com8a1c16f2008-12-17 15:59:43 +0000132class SkScalerContext_FreeType : public SkScalerContext {
133public:
134 SkScalerContext_FreeType(const SkDescriptor* desc);
135 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000136
reed@android.com62900b42009-02-11 15:07:19 +0000137 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000138 return fFaceRec != NULL &&
139 fFTSize != NULL &&
140 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000141 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000142
143protected:
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000144 virtual unsigned generateGlyphCount();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000145 virtual uint16_t generateCharToGlyph(SkUnichar uni);
146 virtual void generateAdvance(SkGlyph* glyph);
147 virtual void generateMetrics(SkGlyph* glyph);
148 virtual void generateImage(const SkGlyph& glyph);
149 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
150 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
151 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000152 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000153
154private:
155 SkFaceRec* fFaceRec;
156 FT_Face fFace; // reference to shared face in gFaceRecHead
157 FT_Size fFTSize; // our own copy
158 SkFixed fScaleX, fScaleY;
159 FT_Matrix fMatrix22;
160 uint32_t fLoadGlyphFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000161 bool fDoLinearMetrics;
reed@google.coma1bfa212012-03-08 21:57:12 +0000162 bool fLCDIsVert;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000163
164 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000165 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000166};
167
168///////////////////////////////////////////////////////////////////////////
169///////////////////////////////////////////////////////////////////////////
170
171#include "SkStream.h"
172
173struct SkFaceRec {
174 SkFaceRec* fNext;
175 FT_Face fFace;
176 FT_StreamRec fFTStream;
177 SkStream* fSkStream;
178 uint32_t fRefCnt;
179 uint32_t fFontID;
180
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000181 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182 SkFaceRec(SkStream* strm, uint32_t fontID);
183 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000184 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000185 }
186};
187
188extern "C" {
189 static unsigned long sk_stream_read(FT_Stream stream,
190 unsigned long offset,
191 unsigned char* buffer,
192 unsigned long count ) {
193 SkStream* str = (SkStream*)stream->descriptor.pointer;
194
195 if (count) {
196 if (!str->rewind()) {
197 return 0;
198 } else {
199 unsigned long ret;
200 if (offset) {
201 ret = str->read(NULL, offset);
202 if (ret != offset) {
203 return 0;
204 }
205 }
206 ret = str->read(buffer, count);
207 if (ret != count) {
208 return 0;
209 }
210 count = ret;
211 }
212 }
213 return count;
214 }
215
216 static void sk_stream_close( FT_Stream stream) {}
217}
218
219SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
220 : fSkStream(strm), fFontID(fontID) {
221// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
222
reed@android.com4516f472009-06-29 16:25:36 +0000223 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000224 fFTStream.size = fSkStream->getLength();
225 fFTStream.descriptor.pointer = fSkStream;
226 fFTStream.read = sk_stream_read;
227 fFTStream.close = sk_stream_close;
228}
229
reed@android.com62900b42009-02-11 15:07:19 +0000230// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000231static SkFaceRec* ref_ft_face(uint32_t fontID) {
232 SkFaceRec* rec = gFaceRecHead;
233 while (rec) {
234 if (rec->fFontID == fontID) {
235 SkASSERT(rec->fFace);
236 rec->fRefCnt += 1;
237 return rec;
238 }
239 rec = rec->fNext;
240 }
241
242 SkStream* strm = SkFontHost::OpenStream(fontID);
243 if (NULL == strm) {
244 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000245 return 0;
246 }
247
248 // this passes ownership of strm to the rec
249 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
250
251 FT_Open_Args args;
252 memset(&args, 0, sizeof(args));
253 const void* memoryBase = strm->getMemoryBase();
254
255 if (NULL != memoryBase) {
256//printf("mmap(%s)\n", keyString.c_str());
257 args.flags = FT_OPEN_MEMORY;
258 args.memory_base = (const FT_Byte*)memoryBase;
259 args.memory_size = strm->getLength();
260 } else {
261//printf("fopen(%s)\n", keyString.c_str());
262 args.flags = FT_OPEN_STREAM;
263 args.stream = &rec->fFTStream;
264 }
265
agl@chromium.org61a678a2010-08-06 18:08:18 +0000266 int face_index;
267 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
268 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
269 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000270
271 if (err) { // bad filename, try the default font
272 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
273 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000274 return 0;
275 } else {
276 SkASSERT(rec->fFace);
277 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
278 rec->fNext = gFaceRecHead;
279 gFaceRecHead = rec;
280 rec->fRefCnt = 1;
281 return rec;
282 }
283}
284
285static void unref_ft_face(FT_Face face) {
286 SkFaceRec* rec = gFaceRecHead;
287 SkFaceRec* prev = NULL;
288 while (rec) {
289 SkFaceRec* next = rec->fNext;
290 if (rec->fFace == face) {
291 if (--rec->fRefCnt == 0) {
292 if (prev) {
293 prev->fNext = next;
294 } else {
295 gFaceRecHead = next;
296 }
297 FT_Done_Face(face);
298 SkDELETE(rec);
299 }
300 return;
301 }
302 prev = rec;
303 rec = next;
304 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000305 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306}
307
308///////////////////////////////////////////////////////////////////////////
309
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000310// Work around for old versions of freetype.
311static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
312 FT_Int32 loadFlags, FT_Fixed* advances) {
313#ifdef FT_ADVANCES_H
314 return FT_Get_Advances(face, start, count, loadFlags, advances);
315#else
316 if (!face || start >= face->num_glyphs ||
317 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
318 return 6; // "Invalid argument."
319 }
320 if (count == 0)
321 return 0;
322
323 for (int i = 0; i < count; i++) {
324 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
325 if (err)
326 return err;
327 advances[i] = face->glyph->advance.x;
328 }
329
330 return 0;
331#endif
332}
333
334static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000335#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000336 FT_UShort fsType = FT_Get_FSType_Flags(face);
337 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
338 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
339#else
340 // No embedding is 0x2 and bitmap embedding only is 0x200.
341 TT_OS2* os2_table;
342 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
343 return (os2_table->fsType & 0x202) == 0;
344 }
345 return false; // We tried, fail safe.
346#endif
347}
348
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000349static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
350 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
351 if (!glyph_id)
352 return false;
353 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
354 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
355 return true;
356}
357
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000358static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000359 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000360 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
361 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000362 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000363 SkASSERT(data);
364 *data = advance;
365 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000366}
367
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000368static void populate_glyph_to_unicode(FT_Face& face,
369 SkTDArray<SkUnichar>* glyphToUnicode) {
370 // Check and see if we have Unicode cmaps.
371 for (int i = 0; i < face->num_charmaps; ++i) {
372 // CMaps known to support Unicode:
373 // Platform ID Encoding ID Name
374 // ----------- ----------- -----------------------------------
375 // 0 0,1 Apple Unicode
376 // 0 3 Apple Unicode 2.0 (preferred)
377 // 3 1 Microsoft Unicode UCS-2
378 // 3 10 Microsoft Unicode UCS-4 (preferred)
379 //
380 // See Apple TrueType Reference Manual
381 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
382 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
383 // Microsoft OpenType Specification
384 // http://www.microsoft.com/typography/otspec/cmap.htm
385
386 FT_UShort platformId = face->charmaps[i]->platform_id;
387 FT_UShort encodingId = face->charmaps[i]->encoding_id;
388
389 if (platformId != 0 && platformId != 3) {
390 continue;
391 }
392 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
393 continue;
394 }
395 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
396 (platformId == 0 && encodingId == 3));
397
398 FT_Set_Charmap(face, face->charmaps[i]);
399 if (glyphToUnicode->isEmpty()) {
400 glyphToUnicode->setCount(face->num_glyphs);
401 memset(glyphToUnicode->begin(), 0,
402 sizeof(SkUnichar) * face->num_glyphs);
403 }
404
405 // Iterate through each cmap entry.
406 FT_UInt glyphIndex;
407 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
408 glyphIndex != 0;
409 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
410 if (charCode &&
411 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
412 (*glyphToUnicode)[glyphIndex] = charCode;
413 }
414 }
415 }
416}
417
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000418// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000419SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000420 uint32_t fontID,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000421 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
422 const uint32_t* glyphIDs,
423 uint32_t glyphIDsCount) {
djsollen@google.comda957722011-11-16 17:00:46 +0000424#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000425 return NULL;
426#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000427 SkAutoMutexAcquire ac(gFTMutex);
428 FT_Library libInit = NULL;
429 if (gFTCount == 0) {
430 if (!InitFreetype())
431 sk_throw();
432 libInit = gFTLibrary;
433 }
434 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
435 SkFaceRec* rec = ref_ft_face(fontID);
436 if (NULL == rec)
437 return NULL;
438 FT_Face face = rec->fFace;
439
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000440 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
441 info->fFontName.set(FT_Get_Postscript_Name(face));
442 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
443 info->fLastGlyphID = face->num_glyphs - 1;
444 info->fEmSize = 1000;
445
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000446 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000447 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000448 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000449 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000450 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000451 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000452 cid = true;
453 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000454 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000455 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000456 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000457 cid = true;
458 TT_Header* ttHeader;
459 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
460 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000461 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000462 }
463 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000464
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000465 info->fStyle = 0;
466 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000467 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000468 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000469 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000470 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
471 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000472 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
473
474 PS_FontInfoRec ps_info;
475 TT_Postscript* tt_info;
476 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
477 info->fItalicAngle = ps_info.italic_angle;
478 } else if ((tt_info =
479 (TT_Postscript*)FT_Get_Sfnt_Table(face,
480 ft_sfnt_post)) != NULL) {
481 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
482 } else {
483 info->fItalicAngle = 0;
484 }
485
486 info->fAscent = face->ascender;
487 info->fDescent = face->descender;
488
489 // Figure out a good guess for StemV - Min width of i, I, !, 1.
490 // This probably isn't very good with an italic font.
491 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000492 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000493 char stem_chars[] = {'i', 'I', '!', '1'};
494 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
495 FT_BBox bbox;
496 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
497 int16_t width = bbox.xMax - bbox.xMin;
498 if (width > 0 && width < min_width) {
499 min_width = width;
500 info->fStemV = min_width;
501 }
502 }
503 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000504
505 TT_PCLT* pclt_info;
506 TT_OS2* os2_table;
507 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
508 info->fCapHeight = pclt_info->CapHeight;
509 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
510 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000511 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000512 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000513 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000514 } else if ((os2_table =
515 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
516 info->fCapHeight = os2_table->sCapHeight;
517 } else {
518 // Figure out a good guess for CapHeight: average the height of M and X.
519 FT_BBox m_bbox, x_bbox;
520 bool got_m, got_x;
521 got_m = GetLetterCBox(face, 'M', &m_bbox);
522 got_x = GetLetterCBox(face, 'X', &x_bbox);
523 if (got_m && got_x) {
524 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
525 x_bbox.yMin) / 2;
526 } else if (got_m && !got_x) {
527 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
528 } else if (!got_m && got_x) {
529 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
530 }
531 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000532
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000533 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
534 face->bbox.xMax, face->bbox.yMin);
535
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000536 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000537 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
538 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
539 }
540
541 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000542 if (FT_IS_FIXED_WIDTH(face)) {
543 appendRange(&info->fGlyphWidths, 0);
544 int16_t advance = face->max_advance_width;
545 info->fGlyphWidths->fAdvance.append(1, &advance);
546 finishRange(info->fGlyphWidths.get(), 0,
547 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000548 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000549 appendRange(&info->fGlyphWidths, 0);
550 // So as to not blow out the stack, get advances in batches.
551 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
552 FT_Fixed advances[128];
553 int advanceCount = 128;
554 if (gID + advanceCount > face->num_glyphs)
555 advanceCount = face->num_glyphs - gID + 1;
556 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
557 advances);
558 for (int i = 0; i < advanceCount; i++) {
559 int16_t advance = advances[gID + i];
560 info->fGlyphWidths->fAdvance.append(1, &advance);
561 }
562 }
563 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
564 SkAdvancedTypefaceMetrics::WidthRange::kRange);
565 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000566 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000567 getAdvanceData(face,
568 face->num_glyphs,
569 glyphIDs,
570 glyphIDsCount,
571 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000572 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000573 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000574
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000575 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
576 FT_HAS_VERTICAL(face)) {
577 SkASSERT(false); // Not implemented yet.
578 }
579
580 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
581 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
582 // Postscript fonts may contain more than 255 glyphs, so we end up
583 // using multiple font descriptions with a glyph ordering. Record
584 // the name of each glyph.
585 info->fGlyphNames.reset(
586 new SkAutoTArray<SkString>(face->num_glyphs));
587 for (int gID = 0; gID < face->num_glyphs; gID++) {
588 char glyphName[128]; // PS limit for names is 127 bytes.
589 FT_Get_Glyph_Name(face, gID, glyphName, 128);
590 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000591 }
592 }
593
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000594 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
595 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
596 face->num_charmaps) {
597 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
598 }
599
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000600 if (!canEmbed(face))
601 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
602
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000603 unref_ft_face(face);
604 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000605#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000606}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000607
reed@google.com618ef5e2011-01-26 22:10:41 +0000608///////////////////////////////////////////////////////////////////////////
609
reed@google.comffe49f52011-11-22 19:42:41 +0000610#define BLACK_LUMINANCE_LIMIT 0x40
611#define WHITE_LUMINANCE_LIMIT 0xA0
612
reed@google.com8ed436c2011-07-21 14:12:36 +0000613static bool bothZero(SkScalar a, SkScalar b) {
614 return 0 == a && 0 == b;
615}
616
617// returns false if there is any non-90-rotation or skew
618static bool isAxisAligned(const SkScalerContext::Rec& rec) {
619 return 0 == rec.fPreSkewX &&
620 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
621 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
622}
623
reed@google.com618ef5e2011-01-26 22:10:41 +0000624void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
625 if (!gLCDSupportValid) {
626 InitFreetype();
627 FT_Done_FreeType(gFTLibrary);
628 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000629
reed@google.comeffc5012011-06-27 16:44:46 +0000630 if (!gLCDSupport && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000631 // If the runtime Freetype library doesn't support LCD mode, we disable
632 // it here.
633 rec->fMaskFormat = SkMask::kA8_Format;
634 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000635
reed@google.com618ef5e2011-01-26 22:10:41 +0000636 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000637 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000638 // collapse full->normal hinting if we're not doing LCD
639 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000640 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000641 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000642 if (SkPaint::kNo_Hinting != h) {
643 h = SkPaint::kSlight_Hinting;
644 }
645 }
646
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000647#ifndef SK_IGNORE_ROTATED_FREETYPE_FIX
reed@google.com8ed436c2011-07-21 14:12:36 +0000648 // rotated text looks bad with hinting, so we disable it as needed
649 if (!isAxisAligned(*rec)) {
650 h = SkPaint::kNo_Hinting;
651 }
bsalomon@google.com0e35ca82011-07-22 17:56:19 +0000652#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000653 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000654
reed@google.com1ac83502012-02-28 17:06:02 +0000655#ifndef SK_USE_COLOR_LUMINANCE
reed@google.comffe49f52011-11-22 19:42:41 +0000656 // for compatibility at the moment, discretize luminance to 3 settings
657 // black, white, gray. This helps with fontcache utilization, since we
658 // won't create multiple entries that in the end map to the same results.
659 {
660 unsigned lum = rec->getLuminanceByte();
661 if (gGammaTables[0] || gGammaTables[1]) {
662 if (lum <= BLACK_LUMINANCE_LIMIT) {
663 lum = 0;
664 } else if (lum >= WHITE_LUMINANCE_LIMIT) {
665 lum = SkScalerContext::kLuminance_Max;
666 } else {
667 lum = SkScalerContext::kLuminance_Max >> 1;
668 }
669 } else {
670 lum = 0; // no gamma correct, so use 0 since SkPaint uses that
671 // when measuring text w/o regard for luminance
672 }
673 rec->setLuminanceBits(lum);
674 }
reed@google.com1ac83502012-02-28 17:06:02 +0000675#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000676}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000677
djsollen@google.comda957722011-11-16 17:00:46 +0000678#ifdef SK_BUILD_FOR_ANDROID
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000679uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
680 SkAutoMutexAcquire ac(gFTMutex);
681 SkFaceRec *rec = ref_ft_face(fontID);
682 uint16_t unitsPerEm = 0;
683
684 if (rec != NULL && rec->fFace != NULL) {
685 unitsPerEm = rec->fFace->units_per_EM;
686 unref_ft_face(rec->fFace);
687 }
688
689 return (uint32_t)unitsPerEm;
690}
691#endif
692
reed@android.com8a1c16f2008-12-17 15:59:43 +0000693SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000694 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000695 SkAutoMutexAcquire ac(gFTMutex);
696
reed@android.com8a1c16f2008-12-17 15:59:43 +0000697 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000698 if (!InitFreetype()) {
699 sk_throw();
700 }
reed@google.comffe49f52011-11-22 19:42:41 +0000701 SkFontHost::GetGammaTables(gGammaTables);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000702 }
703 ++gFTCount;
704
705 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000706 fFTSize = NULL;
707 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000708 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000709 if (NULL == fFaceRec) {
710 return;
711 }
712 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000713
714 // compute our factors from the record
715
716 SkMatrix m;
717
718 fRec.getSingleMatrix(&m);
719
720#ifdef DUMP_STRIKE_CREATION
721 SkString keyString;
722 SkFontHost::GetDescriptorKeyString(desc, &keyString);
723 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
724 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
725 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
726 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000727 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000728#endif
729
730 // now compute our scale factors
731 SkScalar sx = m.getScaleX();
732 SkScalar sy = m.getScaleY();
733
734 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
735 // sort of give up on hinting
736 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
737 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
738 sx = sy = SkScalarAve(sx, sy);
739
740 SkScalar inv = SkScalarInvert(sx);
741
742 // flip the skew elements to go from our Y-down system to FreeType's
743 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
744 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
745 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
746 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
747 } else {
748 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
749 fMatrix22.xy = fMatrix22.yx = 0;
750 }
751
752 fScaleX = SkScalarToFixed(sx);
753 fScaleY = SkScalarToFixed(sy);
754
reed@google.coma1bfa212012-03-08 21:57:12 +0000755 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
756
reed@android.com8a1c16f2008-12-17 15:59:43 +0000757 // compute the flags we send to Load_Glyph
758 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000759 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@google.combdc99882011-11-21 14:36:57 +0000760 bool linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000761
agl@chromium.org70a303f2010-05-10 14:15:50 +0000762 if (SkMask::kBW_Format == fRec.fMaskFormat) {
763 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
764 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000765 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000766 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000767 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000768 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000769 } else {
770 switch (fRec.getHinting()) {
771 case SkPaint::kNo_Hinting:
772 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000773 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000774 break;
775 case SkPaint::kSlight_Hinting:
776 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@google.combdc99882011-11-21 14:36:57 +0000777 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000778 break;
779 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000780 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
781 loadFlags = FT_LOAD_FORCE_AUTOHINT;
782 else
783 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000784 break;
785 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000786 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
787 loadFlags = FT_LOAD_FORCE_AUTOHINT;
788 break;
789 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000790 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000791 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000792 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000793 loadFlags = FT_LOAD_TARGET_LCD_V;
794 } else {
795 loadFlags = FT_LOAD_TARGET_LCD;
796 }
reed@google.comea2333d2011-03-14 16:44:56 +0000797 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000798 break;
799 default:
800 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
801 break;
802 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000803 }
804
reed@google.comeffc5012011-06-27 16:44:46 +0000805 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000806 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000807 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000808
reed@google.com96a9f7912011-05-06 11:49:30 +0000809 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
810 // advances, as fontconfig and cairo do.
811 // See http://code.google.com/p/skia/issues/detail?id=222.
812 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
813
reed@android.come4d0bc02009-07-24 19:53:20 +0000814 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000815 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000816 }
817
818 // now create the FT_Size
819
820 {
821 FT_Error err;
822
823 err = FT_New_Size(fFace, &fFTSize);
824 if (err != 0) {
825 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
826 fFaceRec->fFontID, fScaleX, fScaleY, err));
827 fFace = NULL;
828 return;
829 }
830
831 err = FT_Activate_Size(fFTSize);
832 if (err != 0) {
833 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
834 fFaceRec->fFontID, fScaleX, fScaleY, err));
835 fFTSize = NULL;
836 }
837
838 err = FT_Set_Char_Size( fFace,
839 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
840 72, 72);
841 if (err != 0) {
842 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
843 fFaceRec->fFontID, fScaleX, fScaleY, err));
844 fFace = NULL;
845 return;
846 }
847
848 FT_Set_Transform( fFace, &fMatrix22, NULL);
849 }
850}
851
852SkScalerContext_FreeType::~SkScalerContext_FreeType() {
853 if (fFTSize != NULL) {
854 FT_Done_Size(fFTSize);
855 }
856
857 SkAutoMutexAcquire ac(gFTMutex);
858
859 if (fFace != NULL) {
860 unref_ft_face(fFace);
861 }
862 if (--gFTCount == 0) {
863// SkDEBUGF(("FT_Done_FreeType\n"));
864 FT_Done_FreeType(gFTLibrary);
865 SkDEBUGCODE(gFTLibrary = NULL;)
866 }
867}
868
869/* We call this before each use of the fFace, since we may be sharing
870 this face with other context (at different sizes).
871*/
872FT_Error SkScalerContext_FreeType::setupSize() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000873 FT_Error err = FT_Activate_Size(fFTSize);
874
875 if (err != 0) {
876 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
877 fFaceRec->fFontID, fScaleX, fScaleY, err));
878 fFTSize = NULL;
879 } else {
880 // seems we need to reset this every time (not sure why, but without it
881 // I get random italics from some other fFTSize)
882 FT_Set_Transform( fFace, &fMatrix22, NULL);
883 }
884 return err;
885}
886
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000887void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
888 FT_Pos strength;
889 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
890 / 24;
891 FT_Outline_Embolden(outline, strength);
892}
893
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000894unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000895 return fFace->num_glyphs;
896}
897
898uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
899 return SkToU16(FT_Get_Char_Index( fFace, uni ));
900}
901
reed@android.com9d3a9852010-01-08 14:07:42 +0000902SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
903 // iterate through each cmap entry, looking for matching glyph indices
904 FT_UInt glyphIndex;
905 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
906
907 while (glyphIndex != 0) {
908 if (glyphIndex == glyph) {
909 return charCode;
910 }
911 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
912 }
913
914 return 0;
915}
916
reed@android.com8a1c16f2008-12-17 15:59:43 +0000917static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
918 switch (format) {
919 case SkMask::kBW_Format:
920 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000921 case SkMask::kA8_Format:
922 default:
923 return FT_PIXEL_MODE_GRAY;
924 }
925}
926
reed@android.com8a1c16f2008-12-17 15:59:43 +0000927void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
928#ifdef FT_ADVANCES_H
929 /* unhinted and light hinted text have linearly scaled advances
930 * which are very cheap to compute with some font formats...
931 */
reed@google.combdc99882011-11-21 14:36:57 +0000932 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000933 SkAutoMutexAcquire ac(gFTMutex);
934
935 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000936 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000937 return;
938 }
939
940 FT_Error error;
941 FT_Fixed advance;
942
943 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
944 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
945 &advance );
946 if (0 == error) {
947 glyph->fRsbDelta = 0;
948 glyph->fLsbDelta = 0;
949 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
950 glyph->fAdvanceY = 0;
951 return;
952 }
953 }
954#endif /* FT_ADVANCES_H */
955 /* otherwise, we need to load/hint the glyph, which is slower */
956 this->generateMetrics(glyph);
957 return;
958}
959
960void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
961 SkAutoMutexAcquire ac(gFTMutex);
962
963 glyph->fRsbDelta = 0;
964 glyph->fLsbDelta = 0;
965
966 FT_Error err;
967
968 if (this->setupSize()) {
969 goto ERROR;
970 }
971
972 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
973 if (err != 0) {
974 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
975 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
976 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000977 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000978 return;
979 }
980
981 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +0000982 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983 FT_BBox bbox;
984
bungeman@google.com0f0c2882011-11-04 15:47:41 +0000985 if (0 == fFace->glyph->outline.n_contours) {
986 glyph->fWidth = 0;
987 glyph->fHeight = 0;
988 glyph->fTop = 0;
989 glyph->fLeft = 0;
990 break;
991 }
992
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000993 if (fRec.fFlags & kEmbolden_Flag) {
994 emboldenOutline(&fFace->glyph->outline);
995 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000996 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
997
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000998 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000999 int dx = glyph->getSubXFixed() >> 10;
1000 int dy = glyph->getSubYFixed() >> 10;
1001 // negate dy since freetype-y-goes-up and skia-y-goes-down
1002 bbox.xMin += dx;
1003 bbox.yMin -= dy;
1004 bbox.xMax += dx;
1005 bbox.yMax -= dy;
1006 }
1007
1008 bbox.xMin &= ~63;
1009 bbox.yMin &= ~63;
1010 bbox.xMax = (bbox.xMax + 63) & ~63;
1011 bbox.yMax = (bbox.yMax + 63) & ~63;
1012
1013 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
1014 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
1015 glyph->fTop = -SkToS16(bbox.yMax >> 6);
1016 glyph->fLeft = SkToS16(bbox.xMin >> 6);
reed@google.coma1c32562012-03-01 19:38:23 +00001017
1018 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001019 if (fLCDIsVert) {
1020 glyph->fHeight += gLCDExtra;
1021 glyph->fTop -= gLCDExtra >> 1;
1022 } else {
1023 glyph->fWidth += gLCDExtra;
1024 glyph->fLeft -= gLCDExtra >> 1;
1025 }
reed@google.coma1c32562012-03-01 19:38:23 +00001026 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001027 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001028 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001029
1030 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001031 if (fRec.fFlags & kEmbolden_Flag) {
1032 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1033 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1034 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1036 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1037 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1038 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1039 break;
1040
1041 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001042 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001043 goto ERROR;
1044 }
1045
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001046 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001047 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1048 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1049 if (fRec.fFlags & kDevKernText_Flag) {
1050 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1051 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1052 }
1053 } else {
1054 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1055 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1056 }
1057
1058#ifdef ENABLE_GLYPH_SPEW
1059 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1060 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1061#endif
1062}
1063
reed@google.com1ac83502012-02-28 17:06:02 +00001064///////////////////////////////////////////////////////////////////////////////
1065
1066static int apply_contrast(int srca, int contrast) {
1067 return srca + (((255 - srca) * contrast * srca) / (255*255));
reed@google.comc5181342011-05-17 20:52:46 +00001068}
1069
reed@google.com1ac83502012-02-28 17:06:02 +00001070static void build_power_table(uint8_t table[], float ee) {
1071 for (int i = 0; i < 256; i++) {
1072 float x = i / 255.f;
1073 x = powf(x, ee);
1074 int xx = SkScalarRoundToInt(SkFloatToScalar(x * 255));
1075 table[i] = SkToU8(xx);
reed@google.comc5181342011-05-17 20:52:46 +00001076 }
reed@google.com1ac83502012-02-28 17:06:02 +00001077}
1078
bungeman@google.comd0b6a2d2012-03-05 15:07:25 +00001079static void build_gamma_table(uint8_t table[256], int src) {
reed@google.com1ac83502012-02-28 17:06:02 +00001080 static bool gInit;
1081 static uint8_t powTable[256], invPowTable[256];
1082 if (!gInit) {
1083 const float g = SK_GAMMA_EXPONENT;
1084 build_power_table(powTable, g);
1085 build_power_table(invPowTable, 1/g);
1086 gInit = true;
1087 }
reed@google.com1ac83502012-02-28 17:06:02 +00001088
reed@google.com613e9fe2012-02-29 15:08:00 +00001089 const int linSrc = powTable[src];
bungeman@google.comd0b6a2d2012-03-05 15:07:25 +00001090 const int linDst = 255 - linSrc;
1091 const int dst = invPowTable[linDst];
1092
reed@google.com613e9fe2012-02-29 15:08:00 +00001093 // have our contrast value taper off to 0 as the src luminance becomes white
1094 const int contrast = SK_GAMMA_CONTRAST * (255 - linSrc) / 255;
1095
reed@google.com1ac83502012-02-28 17:06:02 +00001096 for (int i = 0; i < 256; ++i) {
reed@google.com613e9fe2012-02-29 15:08:00 +00001097 int srca = apply_contrast(i, contrast);
1098 SkASSERT((unsigned)srca <= 255);
reed@google.com1ac83502012-02-28 17:06:02 +00001099 int dsta = 255 - srca;
1100
1101 //Calculate the output we want.
1102 int linOut = (linSrc * srca + dsta * linDst) / 255;
1103 SkASSERT((unsigned)linOut <= 255);
1104 int out = invPowTable[linOut];
1105
1106 //Undo what the blit blend will do.
1107 int result = ((255 * out) - (255 * dst)) / (src - dst);
1108 SkASSERT((unsigned)result <= 255);
1109
reed@google.com613e9fe2012-02-29 15:08:00 +00001110 table[i] = result;
reed@google.com1ac83502012-02-28 17:06:02 +00001111 }
1112}
1113
1114static const uint8_t* getGammaTable(U8CPU luminance) {
1115 static uint8_t gGammaTables[4][256];
1116 static bool gInited;
1117 if (!gInited) {
bungeman@google.comd0b6a2d2012-03-05 15:07:25 +00001118 build_gamma_table(gGammaTables[0], 0x00);
1119 build_gamma_table(gGammaTables[1], 0x55);
1120 build_gamma_table(gGammaTables[2], 0xAA);
1121 build_gamma_table(gGammaTables[3], 0xFF);
reed@google.com1ac83502012-02-28 17:06:02 +00001122
1123 gInited = true;
1124 }
1125 SkASSERT(0 == (luminance >> 8));
1126 return gGammaTables[luminance >> 6];
1127}
1128
reed@google.comd61b92b2012-03-02 16:02:07 +00001129#ifndef SK_USE_COLOR_LUMINANCE
1130static const uint8_t* getIdentityTable() {
1131 static bool gOnce;
1132 static uint8_t gIdentityTable[256];
1133 if (!gOnce) {
1134 for (int i = 0; i < 256; ++i) {
1135 gIdentityTable[i] = i;
1136 }
1137 gOnce = true;
1138 }
1139 return gIdentityTable;
1140}
1141#endif
reed@google.com1ac83502012-02-28 17:06:02 +00001142
1143static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
reed@google.comc5181342011-05-17 20:52:46 +00001144 return SkPackRGB16(r >> 3, g >> 2, b >> 3);
1145}
1146
reed@google.com73824072011-06-23 13:17:30 +00001147static uint16_t grayToRGB16(U8CPU gray) {
1148 SkASSERT(gray <= 255);
1149 return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3);
1150}
1151
1152static int bittst(const uint8_t data[], int bitOffset) {
1153 SkASSERT(bitOffset >= 0);
reed@google.comc8e0f932011-06-23 19:39:49 +00001154 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
reed@google.com73824072011-06-23 13:17:30 +00001155 return lowBit & 1;
1156}
1157
reed@google.comeffc5012011-06-27 16:44:46 +00001158static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap,
reed@google.coma1bfa212012-03-08 21:57:12 +00001159 int lcdIsBGR, bool lcdIsVert, const uint8_t* tableR,
reed@google.com1ac83502012-02-28 17:06:02 +00001160 const uint8_t* tableG, const uint8_t* tableB) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001161 if (lcdIsVert) {
1162 SkASSERT(3 * glyph.fHeight == bitmap.rows);
1163 } else {
1164 SkASSERT(glyph.fHeight == bitmap.rows);
1165 }
1166
reed@google.comea2333d2011-03-14 16:44:56 +00001167 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
reed@google.com73824072011-06-23 13:17:30 +00001168 const size_t dstRB = glyph.rowBytes();
1169 const int width = glyph.fWidth;
1170 const uint8_t* src = bitmap.buffer;
reed@google.comea2333d2011-03-14 16:44:56 +00001171
reed@google.com73824072011-06-23 13:17:30 +00001172 switch (bitmap.pixel_mode) {
1173 case FT_PIXEL_MODE_MONO: {
1174 for (int y = 0; y < glyph.fHeight; ++y) {
1175 for (int x = 0; x < width; ++x) {
1176 dst[x] = -bittst(src, x);
1177 }
1178 dst = (uint16_t*)((char*)dst + dstRB);
1179 src += bitmap.pitch;
1180 }
1181 } break;
1182 case FT_PIXEL_MODE_GRAY: {
1183 for (int y = 0; y < glyph.fHeight; ++y) {
1184 for (int x = 0; x < width; ++x) {
1185 dst[x] = grayToRGB16(src[x]);
1186 }
1187 dst = (uint16_t*)((char*)dst + dstRB);
1188 src += bitmap.pitch;
1189 }
1190 } break;
1191 default: {
reed@google.coma1bfa212012-03-08 21:57:12 +00001192 SkASSERT(lcdIsVert || (glyph.fWidth * 3 == bitmap.width));
reed@google.com73824072011-06-23 13:17:30 +00001193 for (int y = 0; y < glyph.fHeight; y++) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001194 if (lcdIsVert) { // vertical stripes
1195 const uint8_t* srcR = src;
1196 const uint8_t* srcG = srcR + bitmap.pitch;
1197 const uint8_t* srcB = srcG + bitmap.pitch;
1198 if (lcdIsBGR) {
1199 SkTSwap(srcR, srcB);
reed@google.comeffc5012011-06-27 16:44:46 +00001200 }
reed@google.comeffc5012011-06-27 16:44:46 +00001201 for (int x = 0; x < width; x++) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001202 dst[x] = packTriple(tableR[*srcR++],
1203 tableG[*srcG++],
1204 tableB[*srcB++]);
reed@google.comeffc5012011-06-27 16:44:46 +00001205 }
reed@google.coma1bfa212012-03-08 21:57:12 +00001206 src += 3 * bitmap.pitch;
1207 } else { // horizontal stripes
1208 const uint8_t* triple = src;
1209 if (lcdIsBGR) {
1210 for (int x = 0; x < width; x++) {
1211 dst[x] = packTriple(tableR[triple[2]],
1212 tableG[triple[1]],
1213 tableB[triple[0]]);
1214 triple += 3;
1215 }
1216 } else {
1217 for (int x = 0; x < width; x++) {
1218 dst[x] = packTriple(tableR[triple[0]],
1219 tableG[triple[1]],
1220 tableB[triple[2]]);
1221 triple += 3;
1222 }
1223 }
1224 src += bitmap.pitch;
reed@google.com73824072011-06-23 13:17:30 +00001225 }
reed@google.com73824072011-06-23 13:17:30 +00001226 dst = (uint16_t*)((char*)dst + dstRB);
1227 }
1228 } break;
reed@google.comea2333d2011-03-14 16:44:56 +00001229 }
1230}
1231
reed@android.com8a1c16f2008-12-17 15:59:43 +00001232void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1233 SkAutoMutexAcquire ac(gFTMutex);
1234
1235 FT_Error err;
1236
1237 if (this->setupSize()) {
1238 goto ERROR;
1239 }
1240
1241 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1242 if (err != 0) {
1243 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1244 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1245 ERROR:
1246 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1247 return;
1248 }
1249
reed@google.com1ac83502012-02-28 17:06:02 +00001250#ifdef SK_USE_COLOR_LUMINANCE
1251 SkColor lumColor = fRec.getLuminanceColor();
1252 const uint8_t* tableR = getGammaTable(SkColorGetR(lumColor));
1253 const uint8_t* tableG = getGammaTable(SkColorGetG(lumColor));
1254 const uint8_t* tableB = getGammaTable(SkColorGetB(lumColor));
1255#else
1256 unsigned lum = fRec.getLuminanceByte();
reed@google.comd61b92b2012-03-02 16:02:07 +00001257 const uint8_t* tableR;
1258 const uint8_t* tableG;
1259 const uint8_t* tableB;
1260
1261 bool isWhite = lum >= WHITE_LUMINANCE_LIMIT;
1262 bool isBlack = lum <= BLACK_LUMINANCE_LIMIT;
1263 if ((gGammaTables[0] || gGammaTables[1]) && (isBlack || isWhite)) {
1264 tableR = tableG = tableB = gGammaTables[isBlack ? 0 : 1];
1265 } else {
1266 tableR = tableG = tableB = getIdentityTable();
1267 }
reed@google.com1ac83502012-02-28 17:06:02 +00001268#endif
1269
reed@google.coma1bfa212012-03-08 21:57:12 +00001270 const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
1271 const bool doVert = fLCDIsVert;
1272
reed@android.com8a1c16f2008-12-17 15:59:43 +00001273 switch ( fFace->glyph->format ) {
1274 case FT_GLYPH_FORMAT_OUTLINE: {
1275 FT_Outline* outline = &fFace->glyph->outline;
1276 FT_BBox bbox;
1277 FT_Bitmap target;
1278
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001279 if (fRec.fFlags & kEmbolden_Flag) {
1280 emboldenOutline(outline);
1281 }
1282
reed@android.com8a1c16f2008-12-17 15:59:43 +00001283 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001284 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001285 dx = glyph.getSubXFixed() >> 10;
1286 dy = glyph.getSubYFixed() >> 10;
1287 // negate dy since freetype-y-goes-up and skia-y-goes-down
1288 dy = -dy;
1289 }
1290 FT_Outline_Get_CBox(outline, &bbox);
1291 /*
1292 what we really want to do for subpixel is
1293 offset(dx, dy)
1294 compute_bounds
1295 offset(bbox & !63)
1296 but that is two calls to offset, so we do the following, which
1297 achieves the same thing with only one offset call.
1298 */
1299 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1300 dy - ((bbox.yMin + dy) & ~63));
1301
reed@google.comea2333d2011-03-14 16:44:56 +00001302 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001303 FT_Render_Glyph(fFace->glyph, doVert ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD);
1304 copyFT2LCD16(glyph, fFace->glyph->bitmap, doBGR, doVert,
reed@google.com1ac83502012-02-28 17:06:02 +00001305 tableR, tableG, tableB);
reed@google.comea2333d2011-03-14 16:44:56 +00001306 } else {
1307 target.width = glyph.fWidth;
1308 target.rows = glyph.fHeight;
1309 target.pitch = glyph.rowBytes();
1310 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1311 target.pixel_mode = compute_pixel_mode(
1312 (SkMask::Format)fRec.fMaskFormat);
1313 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314
reed@google.comea2333d2011-03-14 16:44:56 +00001315 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1316 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1317 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001318 } break;
1319
1320 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001321 if (fRec.fFlags & kEmbolden_Flag) {
1322 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1323 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1324 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001325 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1326 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1327 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1328 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1329
1330 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1331 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001332
agl@chromium.org558434a2009-08-11 17:22:38 +00001333 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1334 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1335 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001336 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1337 unsigned dstRowBytes = glyph.rowBytes();
1338 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1339 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1340
1341 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1342 memcpy(dst, src, minRowBytes);
1343 memset(dst + minRowBytes, 0, extraRowBytes);
1344 src += srcRowBytes;
1345 dst += dstRowBytes;
1346 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001347 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
reed@google.comeffc5012011-06-27 16:44:46 +00001348 glyph.fMaskFormat == SkMask::kA8_Format) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001349 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1350 uint8_t byte = 0;
1351 int bits = 0;
1352 const uint8_t* src_row = src;
1353 uint8_t* dst_row = dst;
1354
1355 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1356 if (!bits) {
1357 byte = *src_row++;
1358 bits = 8;
1359 }
1360
1361 *dst_row++ = byte & 0x80 ? 0xff : 0;
1362 bits--;
1363 byte <<= 1;
1364 }
1365
1366 src += fFace->glyph->bitmap.pitch;
1367 dst += glyph.rowBytes();
1368 }
reed@google.com73824072011-06-23 13:17:30 +00001369 } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
reed@google.coma1bfa212012-03-08 21:57:12 +00001370 copyFT2LCD16(glyph, fFace->glyph->bitmap, doBGR, doVert,
reed@google.com1ac83502012-02-28 17:06:02 +00001371 tableR, tableG, tableB);
agl@chromium.org558434a2009-08-11 17:22:38 +00001372 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001373 SkDEBUGFAIL("unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001374 }
1375 } break;
1376
1377 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001378 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001379 goto ERROR;
1380 }
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001381
reed@google.comd61b92b2012-03-02 16:02:07 +00001382// We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum,
1383// it is optional
1384#if defined(SK_GAMMA_APPLY_TO_A8) || !defined(SK_USE_COLOR_LUMINANCE)
reed@google.com1ac83502012-02-28 17:06:02 +00001385 if (SkMask::kA8_Format == glyph.fMaskFormat) {
1386 SkASSERT(tableR == tableG && tableR == tableB);
1387 const uint8_t* table = tableR;
1388 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1389 unsigned rowBytes = glyph.rowBytes();
1390
1391 for (int y = glyph.fHeight - 1; y >= 0; --y) {
1392 for (int x = glyph.fWidth - 1; x >= 0; --x) {
1393 dst[x] = table[dst[x]];
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001394 }
reed@google.com1ac83502012-02-28 17:06:02 +00001395 dst += rowBytes;
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001396 }
1397 }
reed@google.com1ac83502012-02-28 17:06:02 +00001398#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001399}
1400
1401///////////////////////////////////////////////////////////////////////////////
1402
1403#define ft2sk(x) SkFixedToScalar((x) << 10)
1404
reed@android.com6f252972009-01-14 16:46:16 +00001405#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001406 #define CONST_PARAM const
1407#else // older freetype doesn't use const here
1408 #define CONST_PARAM
1409#endif
1410
1411static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1412 SkPath* path = (SkPath*)ctx;
1413 path->close(); // to close the previous contour (if any)
1414 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1415 return 0;
1416}
1417
1418static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1419 SkPath* path = (SkPath*)ctx;
1420 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1421 return 0;
1422}
1423
1424static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1425 void* ctx) {
1426 SkPath* path = (SkPath*)ctx;
1427 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1428 return 0;
1429}
1430
1431static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1432 CONST_PARAM FT_Vector* pt2, void* ctx) {
1433 SkPath* path = (SkPath*)ctx;
1434 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1435 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1436 return 0;
1437}
1438
1439void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1440 SkPath* path) {
1441 SkAutoMutexAcquire ac(gFTMutex);
1442
1443 SkASSERT(&glyph && path);
1444
1445 if (this->setupSize()) {
1446 path->reset();
1447 return;
1448 }
1449
1450 uint32_t flags = fLoadGlyphFlags;
1451 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1452 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1453
1454 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1455
1456 if (err != 0) {
1457 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1458 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1459 path->reset();
1460 return;
1461 }
1462
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001463 if (fRec.fFlags & kEmbolden_Flag) {
1464 emboldenOutline(&fFace->glyph->outline);
1465 }
1466
reed@android.com8a1c16f2008-12-17 15:59:43 +00001467 FT_Outline_Funcs funcs;
1468
1469 funcs.move_to = move_proc;
1470 funcs.line_to = line_proc;
1471 funcs.conic_to = quad_proc;
1472 funcs.cubic_to = cubic_proc;
1473 funcs.shift = 0;
1474 funcs.delta = 0;
1475
1476 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1477
1478 if (err != 0) {
1479 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1480 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1481 path->reset();
1482 return;
1483 }
1484
1485 path->close();
1486}
1487
1488void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1489 SkPaint::FontMetrics* my) {
1490 if (NULL == mx && NULL == my) {
1491 return;
1492 }
1493
1494 SkAutoMutexAcquire ac(gFTMutex);
1495
1496 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001497 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001498 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001499 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001500 }
1501 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001502 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001503 }
1504 return;
1505 }
1506
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001507 FT_Face face = fFace;
1508 int upem = face->units_per_EM;
1509 if (upem <= 0) {
1510 goto ERROR;
1511 }
1512
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001513 SkPoint pts[6];
1514 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001515 SkFixed scaleY = fScaleY;
1516 SkFixed mxy = fMatrix22.xy;
1517 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001518 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1519 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001520
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001521 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001522 if (leading < 0) {
1523 leading = 0;
1524 }
1525
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001526 // Try to get the OS/2 table from the font. This contains the specific
1527 // average font width metrics which Windows uses.
1528 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1529
reed@android.com8a1c16f2008-12-17 15:59:43 +00001530 ys[0] = -face->bbox.yMax;
1531 ys[1] = -face->ascender;
1532 ys[2] = -face->descender;
1533 ys[3] = -face->bbox.yMin;
1534 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001535 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1536
1537 SkScalar x_height;
1538 if (os2 && os2->sxHeight) {
1539 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1540 } else {
1541 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1542 if (x_glyph) {
1543 FT_BBox bbox;
1544 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001545 if (fRec.fFlags & kEmbolden_Flag) {
1546 emboldenOutline(&fFace->glyph->outline);
1547 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001548 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
epoger@google.comb90113d2012-01-18 19:20:39 +00001549 x_height = SkFixedToScalar(SkFDot6ToFixed(bbox.yMax));
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001550 } else {
1551 x_height = 0;
1552 }
1553 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001554
1555 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001556 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001557 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1558 SkFixed x = SkFixedMul(mxy, y);
1559 y = SkFixedMul(myy, y);
1560 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1561 }
1562
1563 if (mx) {
1564 mx->fTop = pts[0].fX;
1565 mx->fAscent = pts[1].fX;
1566 mx->fDescent = pts[2].fX;
1567 mx->fBottom = pts[3].fX;
1568 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001569 mx->fAvgCharWidth = pts[5].fX;
1570 mx->fXMin = xmin;
1571 mx->fXMax = xmax;
1572 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001573 }
1574 if (my) {
1575 my->fTop = pts[0].fY;
1576 my->fAscent = pts[1].fY;
1577 my->fDescent = pts[2].fY;
1578 my->fBottom = pts[3].fY;
1579 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001580 my->fAvgCharWidth = pts[5].fY;
1581 my->fXMin = xmin;
1582 my->fXMax = xmax;
1583 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001584 }
1585}
1586
1587////////////////////////////////////////////////////////////////////////
1588////////////////////////////////////////////////////////////////////////
1589
1590SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001591 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1592 if (!c->success()) {
1593 SkDELETE(c);
1594 c = NULL;
1595 }
1596 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001597}
1598
1599///////////////////////////////////////////////////////////////////////////////
1600
1601/* Export this so that other parts of our FonttHost port can make use of our
1602 ability to extract the name+style from a stream, using FreeType's api.
1603*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001604bool find_name_and_attributes(SkStream* stream, SkString* name,
1605 SkTypeface::Style* style, bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001606 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001607 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001608 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001609 }
1610
1611 FT_Open_Args args;
1612 memset(&args, 0, sizeof(args));
1613
1614 const void* memoryBase = stream->getMemoryBase();
1615 FT_StreamRec streamRec;
1616
1617 if (NULL != memoryBase) {
1618 args.flags = FT_OPEN_MEMORY;
1619 args.memory_base = (const FT_Byte*)memoryBase;
1620 args.memory_size = stream->getLength();
1621 } else {
1622 memset(&streamRec, 0, sizeof(streamRec));
1623 streamRec.size = stream->read(NULL, 0);
1624 streamRec.descriptor.pointer = stream;
1625 streamRec.read = sk_stream_read;
1626 streamRec.close = sk_stream_close;
1627
1628 args.flags = FT_OPEN_STREAM;
1629 args.stream = &streamRec;
1630 }
1631
1632 FT_Face face;
1633 if (FT_Open_Face(library, &args, 0, &face)) {
1634 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001635 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001636 }
1637
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001638 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001639 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001640 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001641 }
1642 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001643 tempStyle |= SkTypeface::kItalic;
1644 }
1645
1646 if (name) {
1647 name->set(face->family_name);
1648 }
1649 if (style) {
1650 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001651 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001652 if (isFixedWidth) {
1653 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1654 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001655
1656 FT_Done_Face(face);
1657 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001658 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001659}