blob: da1040daa3d27b3cc7b73aa93835744c503aad2b [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
reed@google.com1ac83502012-02-28 17:06:02 +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@android.com8a1c16f2008-12-17 15:59:43 +0000162
163 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000164 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000165};
166
167///////////////////////////////////////////////////////////////////////////
168///////////////////////////////////////////////////////////////////////////
169
170#include "SkStream.h"
171
172struct SkFaceRec {
173 SkFaceRec* fNext;
174 FT_Face fFace;
175 FT_StreamRec fFTStream;
176 SkStream* fSkStream;
177 uint32_t fRefCnt;
178 uint32_t fFontID;
179
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000180 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000181 SkFaceRec(SkStream* strm, uint32_t fontID);
182 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000183 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000184 }
185};
186
187extern "C" {
188 static unsigned long sk_stream_read(FT_Stream stream,
189 unsigned long offset,
190 unsigned char* buffer,
191 unsigned long count ) {
192 SkStream* str = (SkStream*)stream->descriptor.pointer;
193
194 if (count) {
195 if (!str->rewind()) {
196 return 0;
197 } else {
198 unsigned long ret;
199 if (offset) {
200 ret = str->read(NULL, offset);
201 if (ret != offset) {
202 return 0;
203 }
204 }
205 ret = str->read(buffer, count);
206 if (ret != count) {
207 return 0;
208 }
209 count = ret;
210 }
211 }
212 return count;
213 }
214
215 static void sk_stream_close( FT_Stream stream) {}
216}
217
218SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
219 : fSkStream(strm), fFontID(fontID) {
220// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
221
reed@android.com4516f472009-06-29 16:25:36 +0000222 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000223 fFTStream.size = fSkStream->getLength();
224 fFTStream.descriptor.pointer = fSkStream;
225 fFTStream.read = sk_stream_read;
226 fFTStream.close = sk_stream_close;
227}
228
reed@android.com62900b42009-02-11 15:07:19 +0000229// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000230static SkFaceRec* ref_ft_face(uint32_t fontID) {
231 SkFaceRec* rec = gFaceRecHead;
232 while (rec) {
233 if (rec->fFontID == fontID) {
234 SkASSERT(rec->fFace);
235 rec->fRefCnt += 1;
236 return rec;
237 }
238 rec = rec->fNext;
239 }
240
241 SkStream* strm = SkFontHost::OpenStream(fontID);
242 if (NULL == strm) {
243 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000244 return 0;
245 }
246
247 // this passes ownership of strm to the rec
248 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
249
250 FT_Open_Args args;
251 memset(&args, 0, sizeof(args));
252 const void* memoryBase = strm->getMemoryBase();
253
254 if (NULL != memoryBase) {
255//printf("mmap(%s)\n", keyString.c_str());
256 args.flags = FT_OPEN_MEMORY;
257 args.memory_base = (const FT_Byte*)memoryBase;
258 args.memory_size = strm->getLength();
259 } else {
260//printf("fopen(%s)\n", keyString.c_str());
261 args.flags = FT_OPEN_STREAM;
262 args.stream = &rec->fFTStream;
263 }
264
agl@chromium.org61a678a2010-08-06 18:08:18 +0000265 int face_index;
266 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
267 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
268 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000269
270 if (err) { // bad filename, try the default font
271 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
272 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000273 return 0;
274 } else {
275 SkASSERT(rec->fFace);
276 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
277 rec->fNext = gFaceRecHead;
278 gFaceRecHead = rec;
279 rec->fRefCnt = 1;
280 return rec;
281 }
282}
283
284static void unref_ft_face(FT_Face face) {
285 SkFaceRec* rec = gFaceRecHead;
286 SkFaceRec* prev = NULL;
287 while (rec) {
288 SkFaceRec* next = rec->fNext;
289 if (rec->fFace == face) {
290 if (--rec->fRefCnt == 0) {
291 if (prev) {
292 prev->fNext = next;
293 } else {
294 gFaceRecHead = next;
295 }
296 FT_Done_Face(face);
297 SkDELETE(rec);
298 }
299 return;
300 }
301 prev = rec;
302 rec = next;
303 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000304 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000305}
306
307///////////////////////////////////////////////////////////////////////////
308
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000309// Work around for old versions of freetype.
310static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
311 FT_Int32 loadFlags, FT_Fixed* advances) {
312#ifdef FT_ADVANCES_H
313 return FT_Get_Advances(face, start, count, loadFlags, advances);
314#else
315 if (!face || start >= face->num_glyphs ||
316 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
317 return 6; // "Invalid argument."
318 }
319 if (count == 0)
320 return 0;
321
322 for (int i = 0; i < count; i++) {
323 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
324 if (err)
325 return err;
326 advances[i] = face->glyph->advance.x;
327 }
328
329 return 0;
330#endif
331}
332
333static bool canEmbed(FT_Face face) {
djsollen@google.comfa394d42012-01-09 20:40:25 +0000334#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000335 FT_UShort fsType = FT_Get_FSType_Flags(face);
336 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
337 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
338#else
339 // No embedding is 0x2 and bitmap embedding only is 0x200.
340 TT_OS2* os2_table;
341 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
342 return (os2_table->fsType & 0x202) == 0;
343 }
344 return false; // We tried, fail safe.
345#endif
346}
347
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000348static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
349 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
350 if (!glyph_id)
351 return false;
352 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
353 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
354 return true;
355}
356
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000357static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000358 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000359 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
360 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000361 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000362 SkASSERT(data);
363 *data = advance;
364 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000365}
366
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000367static void populate_glyph_to_unicode(FT_Face& face,
368 SkTDArray<SkUnichar>* glyphToUnicode) {
369 // Check and see if we have Unicode cmaps.
370 for (int i = 0; i < face->num_charmaps; ++i) {
371 // CMaps known to support Unicode:
372 // Platform ID Encoding ID Name
373 // ----------- ----------- -----------------------------------
374 // 0 0,1 Apple Unicode
375 // 0 3 Apple Unicode 2.0 (preferred)
376 // 3 1 Microsoft Unicode UCS-2
377 // 3 10 Microsoft Unicode UCS-4 (preferred)
378 //
379 // See Apple TrueType Reference Manual
380 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
381 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
382 // Microsoft OpenType Specification
383 // http://www.microsoft.com/typography/otspec/cmap.htm
384
385 FT_UShort platformId = face->charmaps[i]->platform_id;
386 FT_UShort encodingId = face->charmaps[i]->encoding_id;
387
388 if (platformId != 0 && platformId != 3) {
389 continue;
390 }
391 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
392 continue;
393 }
394 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
395 (platformId == 0 && encodingId == 3));
396
397 FT_Set_Charmap(face, face->charmaps[i]);
398 if (glyphToUnicode->isEmpty()) {
399 glyphToUnicode->setCount(face->num_glyphs);
400 memset(glyphToUnicode->begin(), 0,
401 sizeof(SkUnichar) * face->num_glyphs);
402 }
403
404 // Iterate through each cmap entry.
405 FT_UInt glyphIndex;
406 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
407 glyphIndex != 0;
408 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
409 if (charCode &&
410 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
411 (*glyphToUnicode)[glyphIndex] = charCode;
412 }
413 }
414 }
415}
416
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000417// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000418SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000419 uint32_t fontID,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000420 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
421 const uint32_t* glyphIDs,
422 uint32_t glyphIDsCount) {
djsollen@google.comda957722011-11-16 17:00:46 +0000423#if defined(SK_BUILD_FOR_MAC)
reed@google.com8a5d6922011-03-14 15:08:03 +0000424 return NULL;
425#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000426 SkAutoMutexAcquire ac(gFTMutex);
427 FT_Library libInit = NULL;
428 if (gFTCount == 0) {
429 if (!InitFreetype())
430 sk_throw();
431 libInit = gFTLibrary;
432 }
433 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
434 SkFaceRec* rec = ref_ft_face(fontID);
435 if (NULL == rec)
436 return NULL;
437 FT_Face face = rec->fFace;
438
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000439 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
440 info->fFontName.set(FT_Get_Postscript_Name(face));
441 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
442 info->fLastGlyphID = face->num_glyphs - 1;
443 info->fEmSize = 1000;
444
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000445 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000446 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000447 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000448 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000449 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000450 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000451 cid = true;
452 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000453 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000455 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000456 cid = true;
457 TT_Header* ttHeader;
458 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
459 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000460 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000461 }
462 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000463
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000464 info->fStyle = 0;
465 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000466 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000467 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000468 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000469 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
470 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000471 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
472
473 PS_FontInfoRec ps_info;
474 TT_Postscript* tt_info;
475 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
476 info->fItalicAngle = ps_info.italic_angle;
477 } else if ((tt_info =
478 (TT_Postscript*)FT_Get_Sfnt_Table(face,
479 ft_sfnt_post)) != NULL) {
480 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
481 } else {
482 info->fItalicAngle = 0;
483 }
484
485 info->fAscent = face->ascender;
486 info->fDescent = face->descender;
487
488 // Figure out a good guess for StemV - Min width of i, I, !, 1.
489 // This probably isn't very good with an italic font.
490 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000491 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000492 char stem_chars[] = {'i', 'I', '!', '1'};
493 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
494 FT_BBox bbox;
495 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
496 int16_t width = bbox.xMax - bbox.xMin;
497 if (width > 0 && width < min_width) {
498 min_width = width;
499 info->fStemV = min_width;
500 }
501 }
502 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000503
504 TT_PCLT* pclt_info;
505 TT_OS2* os2_table;
506 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
507 info->fCapHeight = pclt_info->CapHeight;
508 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
509 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000510 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000511 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000512 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000513 } else if ((os2_table =
514 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
515 info->fCapHeight = os2_table->sCapHeight;
516 } else {
517 // Figure out a good guess for CapHeight: average the height of M and X.
518 FT_BBox m_bbox, x_bbox;
519 bool got_m, got_x;
520 got_m = GetLetterCBox(face, 'M', &m_bbox);
521 got_x = GetLetterCBox(face, 'X', &x_bbox);
522 if (got_m && got_x) {
523 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
524 x_bbox.yMin) / 2;
525 } else if (got_m && !got_x) {
526 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
527 } else if (!got_m && got_x) {
528 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
529 }
530 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000531
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000532 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
533 face->bbox.xMax, face->bbox.yMin);
534
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000535 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000536 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
537 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
538 }
539
540 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000541 if (FT_IS_FIXED_WIDTH(face)) {
542 appendRange(&info->fGlyphWidths, 0);
543 int16_t advance = face->max_advance_width;
544 info->fGlyphWidths->fAdvance.append(1, &advance);
545 finishRange(info->fGlyphWidths.get(), 0,
546 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000547 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000548 appendRange(&info->fGlyphWidths, 0);
549 // So as to not blow out the stack, get advances in batches.
550 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
551 FT_Fixed advances[128];
552 int advanceCount = 128;
553 if (gID + advanceCount > face->num_glyphs)
554 advanceCount = face->num_glyphs - gID + 1;
555 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
556 advances);
557 for (int i = 0; i < advanceCount; i++) {
558 int16_t advance = advances[gID + i];
559 info->fGlyphWidths->fAdvance.append(1, &advance);
560 }
561 }
562 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
563 SkAdvancedTypefaceMetrics::WidthRange::kRange);
564 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000565 info->fGlyphWidths.reset(
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000566 getAdvanceData(face,
567 face->num_glyphs,
568 glyphIDs,
569 glyphIDsCount,
570 &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000571 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000572 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000573
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000574 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
575 FT_HAS_VERTICAL(face)) {
576 SkASSERT(false); // Not implemented yet.
577 }
578
579 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
580 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
581 // Postscript fonts may contain more than 255 glyphs, so we end up
582 // using multiple font descriptions with a glyph ordering. Record
583 // the name of each glyph.
584 info->fGlyphNames.reset(
585 new SkAutoTArray<SkString>(face->num_glyphs));
586 for (int gID = 0; gID < face->num_glyphs; gID++) {
587 char glyphName[128]; // PS limit for names is 127 bytes.
588 FT_Get_Glyph_Name(face, gID, glyphName, 128);
589 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000590 }
591 }
592
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000593 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
594 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
595 face->num_charmaps) {
596 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
597 }
598
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000599 if (!canEmbed(face))
600 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
601
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000602 unref_ft_face(face);
603 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000604#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000605}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000606
reed@google.com618ef5e2011-01-26 22:10:41 +0000607///////////////////////////////////////////////////////////////////////////
608
reed@google.comffe49f52011-11-22 19:42:41 +0000609#define BLACK_LUMINANCE_LIMIT 0x40
610#define WHITE_LUMINANCE_LIMIT 0xA0
611
reed@google.com8ed436c2011-07-21 14:12:36 +0000612static bool bothZero(SkScalar a, SkScalar b) {
613 return 0 == a && 0 == b;
614}
615
616// returns false if there is any non-90-rotation or skew
617static bool isAxisAligned(const SkScalerContext::Rec& rec) {
618 return 0 == rec.fPreSkewX &&
619 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
620 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
621}
622
reed@google.com618ef5e2011-01-26 22:10:41 +0000623void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
624 if (!gLCDSupportValid) {
625 InitFreetype();
626 FT_Done_FreeType(gFTLibrary);
627 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000628
reed@google.comeffc5012011-06-27 16:44:46 +0000629 if (!gLCDSupport && isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000630 // If the runtime Freetype library doesn't support LCD mode, we disable
631 // it here.
632 rec->fMaskFormat = SkMask::kA8_Format;
633 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000634
reed@google.com618ef5e2011-01-26 22:10:41 +0000635 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000636 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000637 // collapse full->normal hinting if we're not doing LCD
638 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000639 }
reed@google.com1ac83502012-02-28 17:06:02 +0000640 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) || isLCD(*rec)) {
641 if (SkPaint::kNo_Hinting != h) {
642 h = SkPaint::kSlight_Hinting;
643 }
644 }
645
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000646#ifndef SK_IGNORE_ROTATED_FREETYPE_FIX
reed@google.com8ed436c2011-07-21 14:12:36 +0000647 // rotated text looks bad with hinting, so we disable it as needed
648 if (!isAxisAligned(*rec)) {
649 h = SkPaint::kNo_Hinting;
650 }
bsalomon@google.com0e35ca82011-07-22 17:56:19 +0000651#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000652 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000653
reed@google.com1ac83502012-02-28 17:06:02 +0000654#ifndef SK_USE_COLOR_LUMINANCE
reed@google.comffe49f52011-11-22 19:42:41 +0000655 // for compatibility at the moment, discretize luminance to 3 settings
656 // black, white, gray. This helps with fontcache utilization, since we
657 // won't create multiple entries that in the end map to the same results.
658 {
659 unsigned lum = rec->getLuminanceByte();
660 if (gGammaTables[0] || gGammaTables[1]) {
661 if (lum <= BLACK_LUMINANCE_LIMIT) {
662 lum = 0;
663 } else if (lum >= WHITE_LUMINANCE_LIMIT) {
664 lum = SkScalerContext::kLuminance_Max;
665 } else {
666 lum = SkScalerContext::kLuminance_Max >> 1;
667 }
668 } else {
669 lum = 0; // no gamma correct, so use 0 since SkPaint uses that
670 // when measuring text w/o regard for luminance
671 }
672 rec->setLuminanceBits(lum);
673 }
reed@google.com1ac83502012-02-28 17:06:02 +0000674#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000675}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000676
djsollen@google.comda957722011-11-16 17:00:46 +0000677#ifdef SK_BUILD_FOR_ANDROID
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000678uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
679 SkAutoMutexAcquire ac(gFTMutex);
680 SkFaceRec *rec = ref_ft_face(fontID);
681 uint16_t unitsPerEm = 0;
682
683 if (rec != NULL && rec->fFace != NULL) {
684 unitsPerEm = rec->fFace->units_per_EM;
685 unref_ft_face(rec->fFace);
686 }
687
688 return (uint32_t)unitsPerEm;
689}
690#endif
691
reed@android.com8a1c16f2008-12-17 15:59:43 +0000692SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000693 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000694 SkAutoMutexAcquire ac(gFTMutex);
695
reed@android.com8a1c16f2008-12-17 15:59:43 +0000696 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000697 if (!InitFreetype()) {
698 sk_throw();
699 }
reed@google.comffe49f52011-11-22 19:42:41 +0000700 SkFontHost::GetGammaTables(gGammaTables);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000701 }
702 ++gFTCount;
703
704 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000705 fFTSize = NULL;
706 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000707 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000708 if (NULL == fFaceRec) {
709 return;
710 }
711 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000712
713 // compute our factors from the record
714
715 SkMatrix m;
716
717 fRec.getSingleMatrix(&m);
718
719#ifdef DUMP_STRIKE_CREATION
720 SkString keyString;
721 SkFontHost::GetDescriptorKeyString(desc, &keyString);
722 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
723 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
724 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
725 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000726 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000727#endif
728
729 // now compute our scale factors
730 SkScalar sx = m.getScaleX();
731 SkScalar sy = m.getScaleY();
732
733 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
734 // sort of give up on hinting
735 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
736 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
737 sx = sy = SkScalarAve(sx, sy);
738
739 SkScalar inv = SkScalarInvert(sx);
740
741 // flip the skew elements to go from our Y-down system to FreeType's
742 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
743 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
744 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
745 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
746 } else {
747 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
748 fMatrix22.xy = fMatrix22.yx = 0;
749 }
750
751 fScaleX = SkScalarToFixed(sx);
752 fScaleY = SkScalarToFixed(sy);
753
754 // compute the flags we send to Load_Glyph
755 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000756 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@google.combdc99882011-11-21 14:36:57 +0000757 bool linearMetrics = false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000758
agl@chromium.org70a303f2010-05-10 14:15:50 +0000759 if (SkMask::kBW_Format == fRec.fMaskFormat) {
760 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
761 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000762 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000763 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000764 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000765 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000766 } else {
767 switch (fRec.getHinting()) {
768 case SkPaint::kNo_Hinting:
769 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000770 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000771 break;
772 case SkPaint::kSlight_Hinting:
773 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@google.combdc99882011-11-21 14:36:57 +0000774 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000775 break;
776 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000777 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
778 loadFlags = FT_LOAD_FORCE_AUTOHINT;
779 else
780 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000781 break;
782 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000783 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
784 loadFlags = FT_LOAD_FORCE_AUTOHINT;
785 break;
786 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000787 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000788 if (isLCD(fRec)) {
789 if (fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag) {
790 loadFlags = FT_LOAD_TARGET_LCD_V;
791 } else {
792 loadFlags = FT_LOAD_TARGET_LCD;
793 }
reed@google.comea2333d2011-03-14 16:44:56 +0000794 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000795 break;
796 default:
797 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
798 break;
799 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000800 }
801
reed@google.comeffc5012011-06-27 16:44:46 +0000802 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000803 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000804 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000805
reed@google.com96a9f7912011-05-06 11:49:30 +0000806 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
807 // advances, as fontconfig and cairo do.
808 // See http://code.google.com/p/skia/issues/detail?id=222.
809 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
810
reed@android.come4d0bc02009-07-24 19:53:20 +0000811 fLoadGlyphFlags = loadFlags;
reed@google.combdc99882011-11-21 14:36:57 +0000812 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000813 }
814
815 // now create the FT_Size
816
817 {
818 FT_Error err;
819
820 err = FT_New_Size(fFace, &fFTSize);
821 if (err != 0) {
822 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
823 fFaceRec->fFontID, fScaleX, fScaleY, err));
824 fFace = NULL;
825 return;
826 }
827
828 err = FT_Activate_Size(fFTSize);
829 if (err != 0) {
830 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
831 fFaceRec->fFontID, fScaleX, fScaleY, err));
832 fFTSize = NULL;
833 }
834
835 err = FT_Set_Char_Size( fFace,
836 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
837 72, 72);
838 if (err != 0) {
839 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
840 fFaceRec->fFontID, fScaleX, fScaleY, err));
841 fFace = NULL;
842 return;
843 }
844
845 FT_Set_Transform( fFace, &fMatrix22, NULL);
846 }
847}
848
849SkScalerContext_FreeType::~SkScalerContext_FreeType() {
850 if (fFTSize != NULL) {
851 FT_Done_Size(fFTSize);
852 }
853
854 SkAutoMutexAcquire ac(gFTMutex);
855
856 if (fFace != NULL) {
857 unref_ft_face(fFace);
858 }
859 if (--gFTCount == 0) {
860// SkDEBUGF(("FT_Done_FreeType\n"));
861 FT_Done_FreeType(gFTLibrary);
862 SkDEBUGCODE(gFTLibrary = NULL;)
863 }
864}
865
866/* We call this before each use of the fFace, since we may be sharing
867 this face with other context (at different sizes).
868*/
869FT_Error SkScalerContext_FreeType::setupSize() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000870 FT_Error err = FT_Activate_Size(fFTSize);
871
872 if (err != 0) {
873 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
874 fFaceRec->fFontID, fScaleX, fScaleY, err));
875 fFTSize = NULL;
876 } else {
877 // seems we need to reset this every time (not sure why, but without it
878 // I get random italics from some other fFTSize)
879 FT_Set_Transform( fFace, &fMatrix22, NULL);
880 }
881 return err;
882}
883
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000884void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
885 FT_Pos strength;
886 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
887 / 24;
888 FT_Outline_Embolden(outline, strength);
889}
890
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000891unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000892 return fFace->num_glyphs;
893}
894
895uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
896 return SkToU16(FT_Get_Char_Index( fFace, uni ));
897}
898
reed@android.com9d3a9852010-01-08 14:07:42 +0000899SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
900 // iterate through each cmap entry, looking for matching glyph indices
901 FT_UInt glyphIndex;
902 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
903
904 while (glyphIndex != 0) {
905 if (glyphIndex == glyph) {
906 return charCode;
907 }
908 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
909 }
910
911 return 0;
912}
913
reed@android.com8a1c16f2008-12-17 15:59:43 +0000914static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
915 switch (format) {
916 case SkMask::kBW_Format:
917 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000918 case SkMask::kA8_Format:
919 default:
920 return FT_PIXEL_MODE_GRAY;
921 }
922}
923
reed@android.com8a1c16f2008-12-17 15:59:43 +0000924void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
925#ifdef FT_ADVANCES_H
926 /* unhinted and light hinted text have linearly scaled advances
927 * which are very cheap to compute with some font formats...
928 */
reed@google.combdc99882011-11-21 14:36:57 +0000929 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000930 SkAutoMutexAcquire ac(gFTMutex);
931
932 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000933 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000934 return;
935 }
936
937 FT_Error error;
938 FT_Fixed advance;
939
940 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
941 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
942 &advance );
943 if (0 == error) {
944 glyph->fRsbDelta = 0;
945 glyph->fLsbDelta = 0;
946 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
947 glyph->fAdvanceY = 0;
948 return;
949 }
950 }
951#endif /* FT_ADVANCES_H */
952 /* otherwise, we need to load/hint the glyph, which is slower */
953 this->generateMetrics(glyph);
954 return;
955}
956
957void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
958 SkAutoMutexAcquire ac(gFTMutex);
959
960 glyph->fRsbDelta = 0;
961 glyph->fLsbDelta = 0;
962
963 FT_Error err;
964
965 if (this->setupSize()) {
966 goto ERROR;
967 }
968
969 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
970 if (err != 0) {
971 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
972 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
973 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000974 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000975 return;
976 }
977
978 switch ( fFace->glyph->format ) {
thakis@chromium.org598b8592011-05-24 05:42:55 +0000979 case FT_GLYPH_FORMAT_OUTLINE: {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000980 FT_BBox bbox;
981
bungeman@google.com0f0c2882011-11-04 15:47:41 +0000982 if (0 == fFace->glyph->outline.n_contours) {
983 glyph->fWidth = 0;
984 glyph->fHeight = 0;
985 glyph->fTop = 0;
986 glyph->fLeft = 0;
987 break;
988 }
989
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000990 if (fRec.fFlags & kEmbolden_Flag) {
991 emboldenOutline(&fFace->glyph->outline);
992 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000993 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
994
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000995 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000996 int dx = glyph->getSubXFixed() >> 10;
997 int dy = glyph->getSubYFixed() >> 10;
998 // negate dy since freetype-y-goes-up and skia-y-goes-down
999 bbox.xMin += dx;
1000 bbox.yMin -= dy;
1001 bbox.xMax += dx;
1002 bbox.yMax -= dy;
1003 }
1004
1005 bbox.xMin &= ~63;
1006 bbox.yMin &= ~63;
1007 bbox.xMax = (bbox.xMax + 63) & ~63;
1008 bbox.yMax = (bbox.yMax + 63) & ~63;
1009
1010 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
1011 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
1012 glyph->fTop = -SkToS16(bbox.yMax >> 6);
1013 glyph->fLeft = SkToS16(bbox.xMin >> 6);
reed@google.coma1c32562012-03-01 19:38:23 +00001014
1015 if (isLCD(fRec)) {
1016 glyph->fWidth += gLCDExtra;
1017 glyph->fLeft -= gLCDExtra >> 1;
1018 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001019 break;
thakis@chromium.org598b8592011-05-24 05:42:55 +00001020 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001021
1022 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +00001023 if (fRec.fFlags & kEmbolden_Flag) {
1024 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1025 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1026 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001027 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1028 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1029 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1030 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1031 break;
1032
1033 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001034 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035 goto ERROR;
1036 }
1037
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001038 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001039 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1040 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1041 if (fRec.fFlags & kDevKernText_Flag) {
1042 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1043 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1044 }
1045 } else {
1046 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1047 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1048 }
1049
1050#ifdef ENABLE_GLYPH_SPEW
1051 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1052 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1053#endif
1054}
1055
reed@google.com1ac83502012-02-28 17:06:02 +00001056///////////////////////////////////////////////////////////////////////////////
1057
1058static int apply_contrast(int srca, int contrast) {
1059 return srca + (((255 - srca) * contrast * srca) / (255*255));
reed@google.comc5181342011-05-17 20:52:46 +00001060}
1061
reed@google.com1ac83502012-02-28 17:06:02 +00001062static void build_power_table(uint8_t table[], float ee) {
1063 for (int i = 0; i < 256; i++) {
1064 float x = i / 255.f;
1065 x = powf(x, ee);
1066 int xx = SkScalarRoundToInt(SkFloatToScalar(x * 255));
1067 table[i] = SkToU8(xx);
reed@google.comc5181342011-05-17 20:52:46 +00001068 }
reed@google.com1ac83502012-02-28 17:06:02 +00001069}
1070
1071static void build_gamma_table(uint8_t table[256], int src, int dst) {
1072 static bool gInit;
1073 static uint8_t powTable[256], invPowTable[256];
1074 if (!gInit) {
1075 const float g = SK_GAMMA_EXPONENT;
1076 build_power_table(powTable, g);
1077 build_power_table(invPowTable, 1/g);
1078 gInit = true;
1079 }
reed@google.com1ac83502012-02-28 17:06:02 +00001080
reed@google.com613e9fe2012-02-29 15:08:00 +00001081 const int linSrc = powTable[src];
1082 const int linDst = powTable[dst];
1083 // have our contrast value taper off to 0 as the src luminance becomes white
1084 const int contrast = SK_GAMMA_CONTRAST * (255 - linSrc) / 255;
1085
reed@google.com1ac83502012-02-28 17:06:02 +00001086 for (int i = 0; i < 256; ++i) {
reed@google.com613e9fe2012-02-29 15:08:00 +00001087 int srca = apply_contrast(i, contrast);
1088 SkASSERT((unsigned)srca <= 255);
reed@google.com1ac83502012-02-28 17:06:02 +00001089 int dsta = 255 - srca;
1090
1091 //Calculate the output we want.
1092 int linOut = (linSrc * srca + dsta * linDst) / 255;
1093 SkASSERT((unsigned)linOut <= 255);
1094 int out = invPowTable[linOut];
1095
1096 //Undo what the blit blend will do.
1097 int result = ((255 * out) - (255 * dst)) / (src - dst);
1098 SkASSERT((unsigned)result <= 255);
1099
reed@google.com613e9fe2012-02-29 15:08:00 +00001100 table[i] = result;
reed@google.com1ac83502012-02-28 17:06:02 +00001101 }
1102}
1103
1104static const uint8_t* getGammaTable(U8CPU luminance) {
1105 static uint8_t gGammaTables[4][256];
1106 static bool gInited;
1107 if (!gInited) {
1108 build_gamma_table(gGammaTables[0], 0x00, 0xFF);
reed@google.coma1c32562012-03-01 19:38:23 +00001109 build_gamma_table(gGammaTables[1], 0x66, 0x99);
1110 build_gamma_table(gGammaTables[2], 0x99, 0x66);
reed@google.com1ac83502012-02-28 17:06:02 +00001111 build_gamma_table(gGammaTables[3], 0xFF, 0x00);
1112
1113 gInited = true;
1114 }
1115 SkASSERT(0 == (luminance >> 8));
1116 return gGammaTables[luminance >> 6];
1117}
1118
reed@google.comd61b92b2012-03-02 16:02:07 +00001119#ifndef SK_USE_COLOR_LUMINANCE
1120static const uint8_t* getIdentityTable() {
1121 static bool gOnce;
1122 static uint8_t gIdentityTable[256];
1123 if (!gOnce) {
1124 for (int i = 0; i < 256; ++i) {
1125 gIdentityTable[i] = i;
1126 }
1127 gOnce = true;
1128 }
1129 return gIdentityTable;
1130}
1131#endif
reed@google.com1ac83502012-02-28 17:06:02 +00001132
1133static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
reed@google.comc5181342011-05-17 20:52:46 +00001134 return SkPackRGB16(r >> 3, g >> 2, b >> 3);
1135}
1136
reed@google.com73824072011-06-23 13:17:30 +00001137static uint16_t grayToRGB16(U8CPU gray) {
1138 SkASSERT(gray <= 255);
1139 return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3);
1140}
1141
1142static int bittst(const uint8_t data[], int bitOffset) {
1143 SkASSERT(bitOffset >= 0);
reed@google.comc8e0f932011-06-23 19:39:49 +00001144 int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
reed@google.com73824072011-06-23 13:17:30 +00001145 return lowBit & 1;
1146}
1147
reed@google.comeffc5012011-06-27 16:44:46 +00001148static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001149 int lcdIsBGR, const uint8_t* tableR,
1150 const uint8_t* tableG, const uint8_t* tableB) {
reed@google.comea2333d2011-03-14 16:44:56 +00001151 SkASSERT(glyph.fHeight == bitmap.rows);
reed@google.comea2333d2011-03-14 16:44:56 +00001152 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
reed@google.com73824072011-06-23 13:17:30 +00001153 const size_t dstRB = glyph.rowBytes();
1154 const int width = glyph.fWidth;
1155 const uint8_t* src = bitmap.buffer;
reed@google.comea2333d2011-03-14 16:44:56 +00001156
reed@google.com73824072011-06-23 13:17:30 +00001157 switch (bitmap.pixel_mode) {
1158 case FT_PIXEL_MODE_MONO: {
1159 for (int y = 0; y < glyph.fHeight; ++y) {
1160 for (int x = 0; x < width; ++x) {
1161 dst[x] = -bittst(src, x);
1162 }
1163 dst = (uint16_t*)((char*)dst + dstRB);
1164 src += bitmap.pitch;
1165 }
1166 } break;
1167 case FT_PIXEL_MODE_GRAY: {
1168 for (int y = 0; y < glyph.fHeight; ++y) {
1169 for (int x = 0; x < width; ++x) {
1170 dst[x] = grayToRGB16(src[x]);
1171 }
1172 dst = (uint16_t*)((char*)dst + dstRB);
1173 src += bitmap.pitch;
1174 }
1175 } break;
1176 default: {
reed@google.coma1c32562012-03-01 19:38:23 +00001177 SkASSERT(glyph.fWidth * 3 == bitmap.width);
reed@google.com73824072011-06-23 13:17:30 +00001178 for (int y = 0; y < glyph.fHeight; y++) {
1179 const uint8_t* triple = src;
reed@google.comeffc5012011-06-27 16:44:46 +00001180 if (lcdIsBGR) {
1181 for (int x = 0; x < width; x++) {
reed@google.com1ac83502012-02-28 17:06:02 +00001182 dst[x] = packTriple(tableR[triple[2]],
1183 tableG[triple[1]],
1184 tableB[triple[0]]);
reed@google.comeffc5012011-06-27 16:44:46 +00001185 triple += 3;
1186 }
1187 } else {
1188 for (int x = 0; x < width; x++) {
reed@google.com1ac83502012-02-28 17:06:02 +00001189 dst[x] = packTriple(tableR[triple[0]],
1190 tableG[triple[1]],
1191 tableB[triple[2]]);
reed@google.comeffc5012011-06-27 16:44:46 +00001192 triple += 3;
1193 }
reed@google.com73824072011-06-23 13:17:30 +00001194 }
1195 src += bitmap.pitch;
1196 dst = (uint16_t*)((char*)dst + dstRB);
1197 }
1198 } break;
reed@google.comea2333d2011-03-14 16:44:56 +00001199 }
1200}
1201
reed@android.com8a1c16f2008-12-17 15:59:43 +00001202void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1203 SkAutoMutexAcquire ac(gFTMutex);
1204
1205 FT_Error err;
1206
1207 if (this->setupSize()) {
1208 goto ERROR;
1209 }
1210
1211 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1212 if (err != 0) {
1213 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1214 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1215 ERROR:
1216 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1217 return;
1218 }
1219
reed@google.com1ac83502012-02-28 17:06:02 +00001220#ifdef SK_USE_COLOR_LUMINANCE
1221 SkColor lumColor = fRec.getLuminanceColor();
1222 const uint8_t* tableR = getGammaTable(SkColorGetR(lumColor));
1223 const uint8_t* tableG = getGammaTable(SkColorGetG(lumColor));
1224 const uint8_t* tableB = getGammaTable(SkColorGetB(lumColor));
1225#else
1226 unsigned lum = fRec.getLuminanceByte();
reed@google.comd61b92b2012-03-02 16:02:07 +00001227 const uint8_t* tableR;
1228 const uint8_t* tableG;
1229 const uint8_t* tableB;
1230
1231 bool isWhite = lum >= WHITE_LUMINANCE_LIMIT;
1232 bool isBlack = lum <= BLACK_LUMINANCE_LIMIT;
1233 if ((gGammaTables[0] || gGammaTables[1]) && (isBlack || isWhite)) {
1234 tableR = tableG = tableB = gGammaTables[isBlack ? 0 : 1];
1235 } else {
1236 tableR = tableG = tableB = getIdentityTable();
1237 }
reed@google.com1ac83502012-02-28 17:06:02 +00001238#endif
1239
reed@android.com8a1c16f2008-12-17 15:59:43 +00001240 switch ( fFace->glyph->format ) {
1241 case FT_GLYPH_FORMAT_OUTLINE: {
1242 FT_Outline* outline = &fFace->glyph->outline;
1243 FT_BBox bbox;
1244 FT_Bitmap target;
1245
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001246 if (fRec.fFlags & kEmbolden_Flag) {
1247 emboldenOutline(outline);
1248 }
1249
reed@android.com8a1c16f2008-12-17 15:59:43 +00001250 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001251 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001252 dx = glyph.getSubXFixed() >> 10;
1253 dy = glyph.getSubYFixed() >> 10;
1254 // negate dy since freetype-y-goes-up and skia-y-goes-down
1255 dy = -dy;
1256 }
1257 FT_Outline_Get_CBox(outline, &bbox);
1258 /*
1259 what we really want to do for subpixel is
1260 offset(dx, dy)
1261 compute_bounds
1262 offset(bbox & !63)
1263 but that is two calls to offset, so we do the following, which
1264 achieves the same thing with only one offset call.
1265 */
1266 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1267 dy - ((bbox.yMin + dy) & ~63));
1268
reed@google.comea2333d2011-03-14 16:44:56 +00001269 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1270 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
reed@google.comeffc5012011-06-27 16:44:46 +00001271 copyFT2LCD16(glyph, fFace->glyph->bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001272 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1273 tableR, tableG, tableB);
reed@google.comea2333d2011-03-14 16:44:56 +00001274 } else {
1275 target.width = glyph.fWidth;
1276 target.rows = glyph.fHeight;
1277 target.pitch = glyph.rowBytes();
1278 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1279 target.pixel_mode = compute_pixel_mode(
1280 (SkMask::Format)fRec.fMaskFormat);
1281 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001282
reed@google.comea2333d2011-03-14 16:44:56 +00001283 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1284 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1285 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001286 } break;
1287
1288 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001289 if (fRec.fFlags & kEmbolden_Flag) {
1290 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1291 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1292 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001293 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1294 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1295 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1296 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1297
1298 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1299 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001300
agl@chromium.org558434a2009-08-11 17:22:38 +00001301 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1302 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1303 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001304 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1305 unsigned dstRowBytes = glyph.rowBytes();
1306 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1307 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1308
1309 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1310 memcpy(dst, src, minRowBytes);
1311 memset(dst + minRowBytes, 0, extraRowBytes);
1312 src += srcRowBytes;
1313 dst += dstRowBytes;
1314 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001315 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
reed@google.comeffc5012011-06-27 16:44:46 +00001316 glyph.fMaskFormat == SkMask::kA8_Format) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001317 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1318 uint8_t byte = 0;
1319 int bits = 0;
1320 const uint8_t* src_row = src;
1321 uint8_t* dst_row = dst;
1322
1323 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1324 if (!bits) {
1325 byte = *src_row++;
1326 bits = 8;
1327 }
1328
1329 *dst_row++ = byte & 0x80 ? 0xff : 0;
1330 bits--;
1331 byte <<= 1;
1332 }
1333
1334 src += fFace->glyph->bitmap.pitch;
1335 dst += glyph.rowBytes();
1336 }
reed@google.com73824072011-06-23 13:17:30 +00001337 } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
reed@google.comeffc5012011-06-27 16:44:46 +00001338 copyFT2LCD16(glyph, fFace->glyph->bitmap,
reed@google.com1ac83502012-02-28 17:06:02 +00001339 fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1340 tableR, tableG, tableB);
agl@chromium.org558434a2009-08-11 17:22:38 +00001341 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001342 SkDEBUGFAIL("unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001343 }
1344 } break;
1345
1346 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001347 SkDEBUGFAIL("unknown glyph format");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001348 goto ERROR;
1349 }
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001350
reed@google.comd61b92b2012-03-02 16:02:07 +00001351// We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum,
1352// it is optional
1353#if defined(SK_GAMMA_APPLY_TO_A8) || !defined(SK_USE_COLOR_LUMINANCE)
reed@google.com1ac83502012-02-28 17:06:02 +00001354 if (SkMask::kA8_Format == glyph.fMaskFormat) {
1355 SkASSERT(tableR == tableG && tableR == tableB);
1356 const uint8_t* table = tableR;
1357 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1358 unsigned rowBytes = glyph.rowBytes();
1359
1360 for (int y = glyph.fHeight - 1; y >= 0; --y) {
1361 for (int x = glyph.fWidth - 1; x >= 0; --x) {
1362 dst[x] = table[dst[x]];
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001363 }
reed@google.com1ac83502012-02-28 17:06:02 +00001364 dst += rowBytes;
reed@google.com1f6b4ae2011-11-22 14:20:55 +00001365 }
1366 }
reed@google.com1ac83502012-02-28 17:06:02 +00001367#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +00001368}
1369
1370///////////////////////////////////////////////////////////////////////////////
1371
1372#define ft2sk(x) SkFixedToScalar((x) << 10)
1373
reed@android.com6f252972009-01-14 16:46:16 +00001374#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001375 #define CONST_PARAM const
1376#else // older freetype doesn't use const here
1377 #define CONST_PARAM
1378#endif
1379
1380static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1381 SkPath* path = (SkPath*)ctx;
1382 path->close(); // to close the previous contour (if any)
1383 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1384 return 0;
1385}
1386
1387static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1388 SkPath* path = (SkPath*)ctx;
1389 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1390 return 0;
1391}
1392
1393static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1394 void* ctx) {
1395 SkPath* path = (SkPath*)ctx;
1396 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1397 return 0;
1398}
1399
1400static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1401 CONST_PARAM FT_Vector* pt2, void* ctx) {
1402 SkPath* path = (SkPath*)ctx;
1403 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1404 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1405 return 0;
1406}
1407
1408void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1409 SkPath* path) {
1410 SkAutoMutexAcquire ac(gFTMutex);
1411
1412 SkASSERT(&glyph && path);
1413
1414 if (this->setupSize()) {
1415 path->reset();
1416 return;
1417 }
1418
1419 uint32_t flags = fLoadGlyphFlags;
1420 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1421 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1422
1423 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1424
1425 if (err != 0) {
1426 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1427 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1428 path->reset();
1429 return;
1430 }
1431
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001432 if (fRec.fFlags & kEmbolden_Flag) {
1433 emboldenOutline(&fFace->glyph->outline);
1434 }
1435
reed@android.com8a1c16f2008-12-17 15:59:43 +00001436 FT_Outline_Funcs funcs;
1437
1438 funcs.move_to = move_proc;
1439 funcs.line_to = line_proc;
1440 funcs.conic_to = quad_proc;
1441 funcs.cubic_to = cubic_proc;
1442 funcs.shift = 0;
1443 funcs.delta = 0;
1444
1445 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1446
1447 if (err != 0) {
1448 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1449 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1450 path->reset();
1451 return;
1452 }
1453
1454 path->close();
1455}
1456
1457void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1458 SkPaint::FontMetrics* my) {
1459 if (NULL == mx && NULL == my) {
1460 return;
1461 }
1462
1463 SkAutoMutexAcquire ac(gFTMutex);
1464
1465 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001466 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001467 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001468 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001469 }
1470 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001471 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001472 }
1473 return;
1474 }
1475
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001476 FT_Face face = fFace;
1477 int upem = face->units_per_EM;
1478 if (upem <= 0) {
1479 goto ERROR;
1480 }
1481
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001482 SkPoint pts[6];
1483 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001484 SkFixed scaleY = fScaleY;
1485 SkFixed mxy = fMatrix22.xy;
1486 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001487 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1488 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001489
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001490 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001491 if (leading < 0) {
1492 leading = 0;
1493 }
1494
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001495 // Try to get the OS/2 table from the font. This contains the specific
1496 // average font width metrics which Windows uses.
1497 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1498
reed@android.com8a1c16f2008-12-17 15:59:43 +00001499 ys[0] = -face->bbox.yMax;
1500 ys[1] = -face->ascender;
1501 ys[2] = -face->descender;
1502 ys[3] = -face->bbox.yMin;
1503 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001504 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1505
1506 SkScalar x_height;
1507 if (os2 && os2->sxHeight) {
1508 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1509 } else {
1510 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1511 if (x_glyph) {
1512 FT_BBox bbox;
1513 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001514 if (fRec.fFlags & kEmbolden_Flag) {
1515 emboldenOutline(&fFace->glyph->outline);
1516 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001517 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
epoger@google.comb90113d2012-01-18 19:20:39 +00001518 x_height = SkFixedToScalar(SkFDot6ToFixed(bbox.yMax));
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001519 } else {
1520 x_height = 0;
1521 }
1522 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001523
1524 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001525 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001526 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1527 SkFixed x = SkFixedMul(mxy, y);
1528 y = SkFixedMul(myy, y);
1529 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1530 }
1531
1532 if (mx) {
1533 mx->fTop = pts[0].fX;
1534 mx->fAscent = pts[1].fX;
1535 mx->fDescent = pts[2].fX;
1536 mx->fBottom = pts[3].fX;
1537 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001538 mx->fAvgCharWidth = pts[5].fX;
1539 mx->fXMin = xmin;
1540 mx->fXMax = xmax;
1541 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001542 }
1543 if (my) {
1544 my->fTop = pts[0].fY;
1545 my->fAscent = pts[1].fY;
1546 my->fDescent = pts[2].fY;
1547 my->fBottom = pts[3].fY;
1548 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001549 my->fAvgCharWidth = pts[5].fY;
1550 my->fXMin = xmin;
1551 my->fXMax = xmax;
1552 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001553 }
1554}
1555
1556////////////////////////////////////////////////////////////////////////
1557////////////////////////////////////////////////////////////////////////
1558
1559SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001560 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1561 if (!c->success()) {
1562 SkDELETE(c);
1563 c = NULL;
1564 }
1565 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001566}
1567
1568///////////////////////////////////////////////////////////////////////////////
1569
1570/* Export this so that other parts of our FonttHost port can make use of our
1571 ability to extract the name+style from a stream, using FreeType's api.
1572*/
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001573bool find_name_and_attributes(SkStream* stream, SkString* name,
1574 SkTypeface::Style* style, bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001575 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001576 if (FT_Init_FreeType(&library)) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001577 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001578 }
1579
1580 FT_Open_Args args;
1581 memset(&args, 0, sizeof(args));
1582
1583 const void* memoryBase = stream->getMemoryBase();
1584 FT_StreamRec streamRec;
1585
1586 if (NULL != memoryBase) {
1587 args.flags = FT_OPEN_MEMORY;
1588 args.memory_base = (const FT_Byte*)memoryBase;
1589 args.memory_size = stream->getLength();
1590 } else {
1591 memset(&streamRec, 0, sizeof(streamRec));
1592 streamRec.size = stream->read(NULL, 0);
1593 streamRec.descriptor.pointer = stream;
1594 streamRec.read = sk_stream_read;
1595 streamRec.close = sk_stream_close;
1596
1597 args.flags = FT_OPEN_STREAM;
1598 args.stream = &streamRec;
1599 }
1600
1601 FT_Face face;
1602 if (FT_Open_Face(library, &args, 0, &face)) {
1603 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001604 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001605 }
1606
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001607 int tempStyle = SkTypeface::kNormal;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001608 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001609 tempStyle |= SkTypeface::kBold;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001610 }
1611 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001612 tempStyle |= SkTypeface::kItalic;
1613 }
1614
1615 if (name) {
1616 name->set(face->family_name);
1617 }
1618 if (style) {
1619 *style = (SkTypeface::Style) tempStyle;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001620 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001621 if (isFixedWidth) {
1622 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1623 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001624
1625 FT_Done_Face(face);
1626 FT_Done_FreeType(library);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001627 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001628}