blob: ae5f738decb2377cb558cd17fec5f5a88ecc6170 [file] [log] [blame]
reed@android.com8a1c16f2008-12-17 15:59:43 +00001/* libs/graphics/ports/SkFontHost_FreeType.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
agl@chromium.org309485b2009-07-21 17:41:32 +000018#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000019#include "SkScalerContext.h"
20#include "SkBitmap.h"
21#include "SkCanvas.h"
22#include "SkDescriptor.h"
23#include "SkFDot6.h"
24#include "SkFontHost.h"
25#include "SkMask.h"
26#include "SkStream.h"
27#include "SkString.h"
28#include "SkThread.h"
29#include "SkTemplates.h"
30
31#include <ft2build.h>
32#include FT_FREETYPE_H
33#include FT_OUTLINE_H
34#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000035#include FT_TRUETYPE_TABLES_H
agl@chromium.org309485b2009-07-21 17:41:32 +000036
reed@android.comf5493692009-07-22 19:21:01 +000037#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000038#include FT_LCD_FILTER_H
39#endif
40
reed@android.com8a1c16f2008-12-17 15:59:43 +000041#ifdef FT_ADVANCES_H
42#include FT_ADVANCES_H
43#endif
44
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000045#if 0
46// Also include the files by name for build tools which require this.
47#include <freetype/freetype.h>
48#include <freetype/ftoutln.h>
49#include <freetype/ftsizes.h>
50#include <freetype/tttables.h>
51#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000052#include <freetype/ftlcdfil.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000053#endif
54
reed@android.com8a1c16f2008-12-17 15:59:43 +000055//#define ENABLE_GLYPH_SPEW // for tracing calls
56//#define DUMP_STRIKE_CREATION
57
58#ifdef SK_DEBUG
59 #define SkASSERT_CONTINUE(pred) \
60 do { \
61 if (!(pred)) \
62 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
63 } while (false)
64#else
65 #define SkASSERT_CONTINUE(pred)
66#endif
67
68//////////////////////////////////////////////////////////////////////////
69
70struct SkFaceRec;
71
72static SkMutex gFTMutex;
73static int gFTCount;
74static FT_Library gFTLibrary;
75static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000076static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
77static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000078
79/////////////////////////////////////////////////////////////////////////
80
agl@chromium.org309485b2009-07-21 17:41:32 +000081static bool
82InitFreetype() {
83 FT_Error err = FT_Init_FreeType(&gFTLibrary);
84 if (err)
85 return false;
86
reed@android.comf5493692009-07-22 19:21:01 +000087#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000088 // Setup LCD filtering. This reduces colour fringes for LCD rendered
89 // glyphs.
90 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +000091 gLCDSupport = err == 0;
agl@chromium.org309485b2009-07-21 17:41:32 +000092#endif
reed@android.com61608aa2009-07-31 14:52:54 +000093 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +000094
95 return true;
96}
97
reed@android.com8a1c16f2008-12-17 15:59:43 +000098class SkScalerContext_FreeType : public SkScalerContext {
99public:
100 SkScalerContext_FreeType(const SkDescriptor* desc);
101 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000102
reed@android.com62900b42009-02-11 15:07:19 +0000103 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000104 return fFaceRec != NULL &&
105 fFTSize != NULL &&
106 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000107 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000108
109protected:
110 virtual unsigned generateGlyphCount() const;
111 virtual uint16_t generateCharToGlyph(SkUnichar uni);
112 virtual void generateAdvance(SkGlyph* glyph);
113 virtual void generateMetrics(SkGlyph* glyph);
114 virtual void generateImage(const SkGlyph& glyph);
115 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
116 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
117 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000118 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000119
120private:
121 SkFaceRec* fFaceRec;
122 FT_Face fFace; // reference to shared face in gFaceRecHead
123 FT_Size fFTSize; // our own copy
124 SkFixed fScaleX, fScaleY;
125 FT_Matrix fMatrix22;
126 uint32_t fLoadGlyphFlags;
127
128 FT_Error setupSize();
129};
130
131///////////////////////////////////////////////////////////////////////////
132///////////////////////////////////////////////////////////////////////////
133
134#include "SkStream.h"
135
136struct SkFaceRec {
137 SkFaceRec* fNext;
138 FT_Face fFace;
139 FT_StreamRec fFTStream;
140 SkStream* fSkStream;
141 uint32_t fRefCnt;
142 uint32_t fFontID;
143
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000144 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000145 SkFaceRec(SkStream* strm, uint32_t fontID);
146 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000147 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000148 }
149};
150
151extern "C" {
152 static unsigned long sk_stream_read(FT_Stream stream,
153 unsigned long offset,
154 unsigned char* buffer,
155 unsigned long count ) {
156 SkStream* str = (SkStream*)stream->descriptor.pointer;
157
158 if (count) {
159 if (!str->rewind()) {
160 return 0;
161 } else {
162 unsigned long ret;
163 if (offset) {
164 ret = str->read(NULL, offset);
165 if (ret != offset) {
166 return 0;
167 }
168 }
169 ret = str->read(buffer, count);
170 if (ret != count) {
171 return 0;
172 }
173 count = ret;
174 }
175 }
176 return count;
177 }
178
179 static void sk_stream_close( FT_Stream stream) {}
180}
181
182SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
183 : fSkStream(strm), fFontID(fontID) {
184// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
185
reed@android.com4516f472009-06-29 16:25:36 +0000186 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000187 fFTStream.size = fSkStream->getLength();
188 fFTStream.descriptor.pointer = fSkStream;
189 fFTStream.read = sk_stream_read;
190 fFTStream.close = sk_stream_close;
191}
192
reed@android.com62900b42009-02-11 15:07:19 +0000193// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000194static SkFaceRec* ref_ft_face(uint32_t fontID) {
195 SkFaceRec* rec = gFaceRecHead;
196 while (rec) {
197 if (rec->fFontID == fontID) {
198 SkASSERT(rec->fFace);
199 rec->fRefCnt += 1;
200 return rec;
201 }
202 rec = rec->fNext;
203 }
204
205 SkStream* strm = SkFontHost::OpenStream(fontID);
206 if (NULL == strm) {
207 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000208 return 0;
209 }
210
211 // this passes ownership of strm to the rec
212 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
213
214 FT_Open_Args args;
215 memset(&args, 0, sizeof(args));
216 const void* memoryBase = strm->getMemoryBase();
217
218 if (NULL != memoryBase) {
219//printf("mmap(%s)\n", keyString.c_str());
220 args.flags = FT_OPEN_MEMORY;
221 args.memory_base = (const FT_Byte*)memoryBase;
222 args.memory_size = strm->getLength();
223 } else {
224//printf("fopen(%s)\n", keyString.c_str());
225 args.flags = FT_OPEN_STREAM;
226 args.stream = &rec->fFTStream;
227 }
228
229 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
230
231 if (err) { // bad filename, try the default font
232 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
233 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000234 return 0;
235 } else {
236 SkASSERT(rec->fFace);
237 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
238 rec->fNext = gFaceRecHead;
239 gFaceRecHead = rec;
240 rec->fRefCnt = 1;
241 return rec;
242 }
243}
244
245static void unref_ft_face(FT_Face face) {
246 SkFaceRec* rec = gFaceRecHead;
247 SkFaceRec* prev = NULL;
248 while (rec) {
249 SkFaceRec* next = rec->fNext;
250 if (rec->fFace == face) {
251 if (--rec->fRefCnt == 0) {
252 if (prev) {
253 prev->fNext = next;
254 } else {
255 gFaceRecHead = next;
256 }
257 FT_Done_Face(face);
258 SkDELETE(rec);
259 }
260 return;
261 }
262 prev = rec;
263 rec = next;
264 }
265 SkASSERT("shouldn't get here, face not in list");
266}
267
268///////////////////////////////////////////////////////////////////////////
269
reed@android.com36a4c2a2009-07-22 19:52:11 +0000270void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000271 if (!gLCDSupportValid) {
272 InitFreetype();
273 FT_Done_FreeType(gFTLibrary);
274 }
275
276 if (!gLCDSupport && rec->isLCD()) {
277 // If the runtime Freetype library doesn't support LCD mode, we disable
278 // it here.
279 rec->fMaskFormat = SkMask::kA8_Format;
280 }
281
reed@android.com36a4c2a2009-07-22 19:52:11 +0000282 SkPaint::Hinting h = rec->getHinting();
283 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
agl@chromium.orgb4234a22010-01-21 11:43:44 +0000284 // collapse full->normal hinting if we're not doing LCD
reed@android.come4d0bc02009-07-24 19:53:20 +0000285 h = SkPaint::kNormal_Hinting;
286 } else if (rec->fSubpixelPositioning && SkPaint::kNo_Hinting != h) {
287 // to do subpixel, we must have at most slight hinting
288 h = SkPaint::kSlight_Hinting;
reed@android.com36a4c2a2009-07-22 19:52:11 +0000289 }
reed@android.come4d0bc02009-07-24 19:53:20 +0000290 rec->setHinting(h);
reed@android.com36a4c2a2009-07-22 19:52:11 +0000291}
292
reed@android.com8a1c16f2008-12-17 15:59:43 +0000293SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000294 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000295 SkAutoMutexAcquire ac(gFTMutex);
296
reed@android.com8a1c16f2008-12-17 15:59:43 +0000297 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000298 if (!InitFreetype()) {
299 sk_throw();
300 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000301 }
302 ++gFTCount;
303
304 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000305 fFTSize = NULL;
306 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000307 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000308 if (NULL == fFaceRec) {
309 return;
310 }
311 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000312
313 // compute our factors from the record
314
315 SkMatrix m;
316
317 fRec.getSingleMatrix(&m);
318
319#ifdef DUMP_STRIKE_CREATION
320 SkString keyString;
321 SkFontHost::GetDescriptorKeyString(desc, &keyString);
322 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
323 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
324 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
325 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000326 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000327#endif
328
329 // now compute our scale factors
330 SkScalar sx = m.getScaleX();
331 SkScalar sy = m.getScaleY();
332
333 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
334 // sort of give up on hinting
335 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
336 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
337 sx = sy = SkScalarAve(sx, sy);
338
339 SkScalar inv = SkScalarInvert(sx);
340
341 // flip the skew elements to go from our Y-down system to FreeType's
342 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
343 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
344 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
345 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
346 } else {
347 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
348 fMatrix22.xy = fMatrix22.yx = 0;
349 }
350
351 fScaleX = SkScalarToFixed(sx);
352 fScaleY = SkScalarToFixed(sy);
353
354 // compute the flags we send to Load_Glyph
355 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000356 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000357
agl@chromium.org309485b2009-07-21 17:41:32 +0000358 switch (fRec.getHinting()) {
359 case SkPaint::kNo_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000360 loadFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000361 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000362 case SkPaint::kSlight_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000363 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000364 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000365 case SkPaint::kNormal_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000366 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000367 break;
368 case SkPaint::kFull_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000369 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000370 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000371 loadFlags = FT_LOAD_TARGET_LCD;
agl@chromium.org309485b2009-07-21 17:41:32 +0000372 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000373 loadFlags = FT_LOAD_TARGET_LCD_V;
374 break;
375 default:
376 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000377 break;
378 }
379
agl@chromium.org99e1b902010-01-05 01:19:44 +0000380 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000381 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000382
reed@android.come4d0bc02009-07-24 19:53:20 +0000383 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000384 }
385
386 // now create the FT_Size
387
388 {
389 FT_Error err;
390
391 err = FT_New_Size(fFace, &fFTSize);
392 if (err != 0) {
393 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
394 fFaceRec->fFontID, fScaleX, fScaleY, err));
395 fFace = NULL;
396 return;
397 }
398
399 err = FT_Activate_Size(fFTSize);
400 if (err != 0) {
401 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
402 fFaceRec->fFontID, fScaleX, fScaleY, err));
403 fFTSize = NULL;
404 }
405
406 err = FT_Set_Char_Size( fFace,
407 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
408 72, 72);
409 if (err != 0) {
410 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
411 fFaceRec->fFontID, fScaleX, fScaleY, err));
412 fFace = NULL;
413 return;
414 }
415
416 FT_Set_Transform( fFace, &fMatrix22, NULL);
417 }
418}
419
420SkScalerContext_FreeType::~SkScalerContext_FreeType() {
421 if (fFTSize != NULL) {
422 FT_Done_Size(fFTSize);
423 }
424
425 SkAutoMutexAcquire ac(gFTMutex);
426
427 if (fFace != NULL) {
428 unref_ft_face(fFace);
429 }
430 if (--gFTCount == 0) {
431// SkDEBUGF(("FT_Done_FreeType\n"));
432 FT_Done_FreeType(gFTLibrary);
433 SkDEBUGCODE(gFTLibrary = NULL;)
434 }
435}
436
437/* We call this before each use of the fFace, since we may be sharing
438 this face with other context (at different sizes).
439*/
440FT_Error SkScalerContext_FreeType::setupSize() {
441 /* In the off-chance that a font has been removed, we want to error out
442 right away, so call resolve just to be sure.
443
444 TODO: perhaps we can skip this, by walking the global font cache and
445 killing all of the contexts when we know that a given fontID is going
446 away...
447 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000448 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000449 return (FT_Error)-1;
450 }
451
452 FT_Error err = FT_Activate_Size(fFTSize);
453
454 if (err != 0) {
455 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
456 fFaceRec->fFontID, fScaleX, fScaleY, err));
457 fFTSize = NULL;
458 } else {
459 // seems we need to reset this every time (not sure why, but without it
460 // I get random italics from some other fFTSize)
461 FT_Set_Transform( fFace, &fMatrix22, NULL);
462 }
463 return err;
464}
465
466unsigned SkScalerContext_FreeType::generateGlyphCount() const {
467 return fFace->num_glyphs;
468}
469
470uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
471 return SkToU16(FT_Get_Char_Index( fFace, uni ));
472}
473
reed@android.com9d3a9852010-01-08 14:07:42 +0000474SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
475 // iterate through each cmap entry, looking for matching glyph indices
476 FT_UInt glyphIndex;
477 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
478
479 while (glyphIndex != 0) {
480 if (glyphIndex == glyph) {
481 return charCode;
482 }
483 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
484 }
485
486 return 0;
487}
488
reed@android.com8a1c16f2008-12-17 15:59:43 +0000489static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
490 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000491 case SkMask::kHorizontalLCD_Format:
492 case SkMask::kVerticalLCD_Format:
493 SkASSERT(!"An LCD format should never be passed here");
494 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000495 case SkMask::kBW_Format:
496 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000497 case SkMask::kA8_Format:
498 default:
499 return FT_PIXEL_MODE_GRAY;
500 }
501}
502
reed@android.com8a1c16f2008-12-17 15:59:43 +0000503void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
504#ifdef FT_ADVANCES_H
505 /* unhinted and light hinted text have linearly scaled advances
506 * which are very cheap to compute with some font formats...
507 */
508 {
509 SkAutoMutexAcquire ac(gFTMutex);
510
511 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000512 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000513 return;
514 }
515
516 FT_Error error;
517 FT_Fixed advance;
518
519 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
520 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
521 &advance );
522 if (0 == error) {
523 glyph->fRsbDelta = 0;
524 glyph->fLsbDelta = 0;
525 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
526 glyph->fAdvanceY = 0;
527 return;
528 }
529 }
530#endif /* FT_ADVANCES_H */
531 /* otherwise, we need to load/hint the glyph, which is slower */
532 this->generateMetrics(glyph);
533 return;
534}
535
536void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
537 SkAutoMutexAcquire ac(gFTMutex);
538
539 glyph->fRsbDelta = 0;
540 glyph->fLsbDelta = 0;
541
542 FT_Error err;
543
544 if (this->setupSize()) {
545 goto ERROR;
546 }
547
548 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
549 if (err != 0) {
550 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
551 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
552 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000553 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000554 return;
555 }
556
557 switch ( fFace->glyph->format ) {
558 case FT_GLYPH_FORMAT_OUTLINE:
559 FT_BBox bbox;
560
561 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
562
agl@chromium.org309485b2009-07-21 17:41:32 +0000563 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000564 int dx = glyph->getSubXFixed() >> 10;
565 int dy = glyph->getSubYFixed() >> 10;
566 // negate dy since freetype-y-goes-up and skia-y-goes-down
567 bbox.xMin += dx;
568 bbox.yMin -= dy;
569 bbox.xMax += dx;
570 bbox.yMax -= dy;
571 }
572
573 bbox.xMin &= ~63;
574 bbox.yMin &= ~63;
575 bbox.xMax = (bbox.xMax + 63) & ~63;
576 bbox.yMax = (bbox.yMax + 63) & ~63;
577
578 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
579 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
580 glyph->fTop = -SkToS16(bbox.yMax >> 6);
581 glyph->fLeft = SkToS16(bbox.xMin >> 6);
582 break;
583
584 case FT_GLYPH_FORMAT_BITMAP:
585 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
586 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
587 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
588 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
589 break;
590
591 default:
592 SkASSERT(!"unknown glyph format");
593 goto ERROR;
594 }
595
agl@chromium.org309485b2009-07-21 17:41:32 +0000596 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000597 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
598 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
599 if (fRec.fFlags & kDevKernText_Flag) {
600 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
601 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
602 }
603 } else {
604 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
605 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
606 }
607
608#ifdef ENABLE_GLYPH_SPEW
609 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
610 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
611#endif
612}
613
reed@android.comf5493692009-07-22 19:21:01 +0000614#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000615namespace skia_freetype_support {
616// extern functions from SkFontHost_FreeType_Subpixel
617extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
618extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
619}
620
621using namespace skia_freetype_support;
622#endif
623
reed@android.com8a1c16f2008-12-17 15:59:43 +0000624void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
625 SkAutoMutexAcquire ac(gFTMutex);
626
627 FT_Error err;
628
629 if (this->setupSize()) {
630 goto ERROR;
631 }
632
633 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
634 if (err != 0) {
635 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
636 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
637 ERROR:
638 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
639 return;
640 }
641
agl@chromium.org309485b2009-07-21 17:41:32 +0000642 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
643 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
644
reed@android.com8a1c16f2008-12-17 15:59:43 +0000645 switch ( fFace->glyph->format ) {
646 case FT_GLYPH_FORMAT_OUTLINE: {
647 FT_Outline* outline = &fFace->glyph->outline;
648 FT_BBox bbox;
649 FT_Bitmap target;
650
651 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000652 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000653 dx = glyph.getSubXFixed() >> 10;
654 dy = glyph.getSubYFixed() >> 10;
655 // negate dy since freetype-y-goes-up and skia-y-goes-down
656 dy = -dy;
657 }
658 FT_Outline_Get_CBox(outline, &bbox);
659 /*
660 what we really want to do for subpixel is
661 offset(dx, dy)
662 compute_bounds
663 offset(bbox & !63)
664 but that is two calls to offset, so we do the following, which
665 achieves the same thing with only one offset call.
666 */
667 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
668 dy - ((bbox.yMin + dy) & ~63));
669
reed@android.comf5493692009-07-22 19:21:01 +0000670#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000671 if (lcdRenderMode) {
672 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
673 // we have to call FT_Render_Glyph and memcpy the image out.
674 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
675 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
676 FT_Render_Glyph(fFace->glyph, mode);
677
678 if (isVertical)
679 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
680 else
681 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
682
683 break;
684 }
685#endif
686
reed@android.com8a1c16f2008-12-17 15:59:43 +0000687 target.width = glyph.fWidth;
688 target.rows = glyph.fHeight;
689 target.pitch = glyph.rowBytes();
690 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
691 target.pixel_mode = compute_pixel_mode(
692 (SkMask::Format)fRec.fMaskFormat);
693 target.num_grays = 256;
694
695 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
696 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
697 } break;
698
699 case FT_GLYPH_FORMAT_BITMAP: {
700 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
701 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
702 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
703 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
704
705 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
706 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000707
agl@chromium.org558434a2009-08-11 17:22:38 +0000708 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
709 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
710 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000711 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
712 unsigned dstRowBytes = glyph.rowBytes();
713 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
714 unsigned extraRowBytes = dstRowBytes - minRowBytes;
715
716 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
717 memcpy(dst, src, minRowBytes);
718 memset(dst + minRowBytes, 0, extraRowBytes);
719 src += srcRowBytes;
720 dst += dstRowBytes;
721 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000722 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +0000723 (glyph.fMaskFormat == SkMask::kA8_Format ||
724 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
725 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000726 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
727 uint8_t byte = 0;
728 int bits = 0;
729 const uint8_t* src_row = src;
730 uint8_t* dst_row = dst;
731
732 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
733 if (!bits) {
734 byte = *src_row++;
735 bits = 8;
736 }
737
738 *dst_row++ = byte & 0x80 ? 0xff : 0;
739 bits--;
740 byte <<= 1;
741 }
742
743 src += fFace->glyph->bitmap.pitch;
744 dst += glyph.rowBytes();
745 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000746 } else {
747 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000748 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000749
750 if (lcdRenderMode)
751 glyph.expandA8ToLCD();
752
reed@android.com8a1c16f2008-12-17 15:59:43 +0000753 } break;
754
755 default:
756 SkASSERT(!"unknown glyph format");
757 goto ERROR;
758 }
759}
760
761///////////////////////////////////////////////////////////////////////////////
762
763#define ft2sk(x) SkFixedToScalar((x) << 10)
764
reed@android.com6f252972009-01-14 16:46:16 +0000765#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000766 #define CONST_PARAM const
767#else // older freetype doesn't use const here
768 #define CONST_PARAM
769#endif
770
771static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
772 SkPath* path = (SkPath*)ctx;
773 path->close(); // to close the previous contour (if any)
774 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
775 return 0;
776}
777
778static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
779 SkPath* path = (SkPath*)ctx;
780 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
781 return 0;
782}
783
784static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
785 void* ctx) {
786 SkPath* path = (SkPath*)ctx;
787 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
788 return 0;
789}
790
791static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
792 CONST_PARAM FT_Vector* pt2, void* ctx) {
793 SkPath* path = (SkPath*)ctx;
794 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
795 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
796 return 0;
797}
798
799void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
800 SkPath* path) {
801 SkAutoMutexAcquire ac(gFTMutex);
802
803 SkASSERT(&glyph && path);
804
805 if (this->setupSize()) {
806 path->reset();
807 return;
808 }
809
810 uint32_t flags = fLoadGlyphFlags;
811 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
812 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
813
814 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
815
816 if (err != 0) {
817 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
818 glyph.getGlyphID(fBaseGlyphCount), flags, err));
819 path->reset();
820 return;
821 }
822
823 FT_Outline_Funcs funcs;
824
825 funcs.move_to = move_proc;
826 funcs.line_to = line_proc;
827 funcs.conic_to = quad_proc;
828 funcs.cubic_to = cubic_proc;
829 funcs.shift = 0;
830 funcs.delta = 0;
831
832 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
833
834 if (err != 0) {
835 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
836 glyph.getGlyphID(fBaseGlyphCount), flags, err));
837 path->reset();
838 return;
839 }
840
841 path->close();
842}
843
844void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
845 SkPaint::FontMetrics* my) {
846 if (NULL == mx && NULL == my) {
847 return;
848 }
849
850 SkAutoMutexAcquire ac(gFTMutex);
851
852 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000853 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000854 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000855 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000856 }
857 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000858 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000859 }
860 return;
861 }
862
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000863 FT_Face face = fFace;
864 int upem = face->units_per_EM;
865 if (upem <= 0) {
866 goto ERROR;
867 }
868
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000869 SkPoint pts[6];
870 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000871 SkFixed scaleY = fScaleY;
872 SkFixed mxy = fMatrix22.xy;
873 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000874 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
875 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000876
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000877 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000878 if (leading < 0) {
879 leading = 0;
880 }
881
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000882 // Try to get the OS/2 table from the font. This contains the specific
883 // average font width metrics which Windows uses.
884 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
885
reed@android.com8a1c16f2008-12-17 15:59:43 +0000886 ys[0] = -face->bbox.yMax;
887 ys[1] = -face->ascender;
888 ys[2] = -face->descender;
889 ys[3] = -face->bbox.yMin;
890 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000891 ys[5] = os2 ? os2->xAvgCharWidth : 0;
892
893 SkScalar x_height;
894 if (os2 && os2->sxHeight) {
895 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
896 } else {
897 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
898 if (x_glyph) {
899 FT_BBox bbox;
900 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
901 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
902 x_height = SkIntToScalar(bbox.yMax) / 64;
903 } else {
904 x_height = 0;
905 }
906 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000907
908 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000909 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000910 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
911 SkFixed x = SkFixedMul(mxy, y);
912 y = SkFixedMul(myy, y);
913 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
914 }
915
916 if (mx) {
917 mx->fTop = pts[0].fX;
918 mx->fAscent = pts[1].fX;
919 mx->fDescent = pts[2].fX;
920 mx->fBottom = pts[3].fX;
921 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000922 mx->fAvgCharWidth = pts[5].fX;
923 mx->fXMin = xmin;
924 mx->fXMax = xmax;
925 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000926 }
927 if (my) {
928 my->fTop = pts[0].fY;
929 my->fAscent = pts[1].fY;
930 my->fDescent = pts[2].fY;
931 my->fBottom = pts[3].fY;
932 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000933 my->fAvgCharWidth = pts[5].fY;
934 my->fXMin = xmin;
935 my->fXMax = xmax;
936 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000937 }
938}
939
940////////////////////////////////////////////////////////////////////////
941////////////////////////////////////////////////////////////////////////
942
943SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000944 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
945 if (!c->success()) {
946 SkDELETE(c);
947 c = NULL;
948 }
949 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000950}
951
952///////////////////////////////////////////////////////////////////////////////
953
954/* Export this so that other parts of our FonttHost port can make use of our
955 ability to extract the name+style from a stream, using FreeType's api.
956*/
957SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
958 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +0000959 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960 name->set(NULL);
961 return SkTypeface::kNormal;
962 }
963
964 FT_Open_Args args;
965 memset(&args, 0, sizeof(args));
966
967 const void* memoryBase = stream->getMemoryBase();
968 FT_StreamRec streamRec;
969
970 if (NULL != memoryBase) {
971 args.flags = FT_OPEN_MEMORY;
972 args.memory_base = (const FT_Byte*)memoryBase;
973 args.memory_size = stream->getLength();
974 } else {
975 memset(&streamRec, 0, sizeof(streamRec));
976 streamRec.size = stream->read(NULL, 0);
977 streamRec.descriptor.pointer = stream;
978 streamRec.read = sk_stream_read;
979 streamRec.close = sk_stream_close;
980
981 args.flags = FT_OPEN_STREAM;
982 args.stream = &streamRec;
983 }
984
985 FT_Face face;
986 if (FT_Open_Face(library, &args, 0, &face)) {
987 FT_Done_FreeType(library);
988 name->set(NULL);
989 return SkTypeface::kNormal;
990 }
991
992 name->set(face->family_name);
993 int style = SkTypeface::kNormal;
994
995 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
996 style |= SkTypeface::kBold;
997 }
998 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
999 style |= SkTypeface::kItalic;
1000 }
1001
1002 FT_Done_Face(face);
1003 FT_Done_FreeType(library);
1004 return (SkTypeface::Style)style;
1005}