blob: 5eb36f6ded194dd58b067d0e586b5f579c6afc7b [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);
118
119private:
120 SkFaceRec* fFaceRec;
121 FT_Face fFace; // reference to shared face in gFaceRecHead
122 FT_Size fFTSize; // our own copy
123 SkFixed fScaleX, fScaleY;
124 FT_Matrix fMatrix22;
125 uint32_t fLoadGlyphFlags;
126
127 FT_Error setupSize();
128};
129
130///////////////////////////////////////////////////////////////////////////
131///////////////////////////////////////////////////////////////////////////
132
133#include "SkStream.h"
134
135struct SkFaceRec {
136 SkFaceRec* fNext;
137 FT_Face fFace;
138 FT_StreamRec fFTStream;
139 SkStream* fSkStream;
140 uint32_t fRefCnt;
141 uint32_t fFontID;
142
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000143 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144 SkFaceRec(SkStream* strm, uint32_t fontID);
145 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000146 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000147 }
148};
149
150extern "C" {
151 static unsigned long sk_stream_read(FT_Stream stream,
152 unsigned long offset,
153 unsigned char* buffer,
154 unsigned long count ) {
155 SkStream* str = (SkStream*)stream->descriptor.pointer;
156
157 if (count) {
158 if (!str->rewind()) {
159 return 0;
160 } else {
161 unsigned long ret;
162 if (offset) {
163 ret = str->read(NULL, offset);
164 if (ret != offset) {
165 return 0;
166 }
167 }
168 ret = str->read(buffer, count);
169 if (ret != count) {
170 return 0;
171 }
172 count = ret;
173 }
174 }
175 return count;
176 }
177
178 static void sk_stream_close( FT_Stream stream) {}
179}
180
181SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
182 : fSkStream(strm), fFontID(fontID) {
183// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
184
reed@android.com4516f472009-06-29 16:25:36 +0000185 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000186 fFTStream.size = fSkStream->getLength();
187 fFTStream.descriptor.pointer = fSkStream;
188 fFTStream.read = sk_stream_read;
189 fFTStream.close = sk_stream_close;
190}
191
reed@android.com62900b42009-02-11 15:07:19 +0000192// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000193static SkFaceRec* ref_ft_face(uint32_t fontID) {
194 SkFaceRec* rec = gFaceRecHead;
195 while (rec) {
196 if (rec->fFontID == fontID) {
197 SkASSERT(rec->fFace);
198 rec->fRefCnt += 1;
199 return rec;
200 }
201 rec = rec->fNext;
202 }
203
204 SkStream* strm = SkFontHost::OpenStream(fontID);
205 if (NULL == strm) {
206 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000207 return 0;
208 }
209
210 // this passes ownership of strm to the rec
211 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
212
213 FT_Open_Args args;
214 memset(&args, 0, sizeof(args));
215 const void* memoryBase = strm->getMemoryBase();
216
217 if (NULL != memoryBase) {
218//printf("mmap(%s)\n", keyString.c_str());
219 args.flags = FT_OPEN_MEMORY;
220 args.memory_base = (const FT_Byte*)memoryBase;
221 args.memory_size = strm->getLength();
222 } else {
223//printf("fopen(%s)\n", keyString.c_str());
224 args.flags = FT_OPEN_STREAM;
225 args.stream = &rec->fFTStream;
226 }
227
228 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
229
230 if (err) { // bad filename, try the default font
231 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
232 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000233 return 0;
234 } else {
235 SkASSERT(rec->fFace);
236 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
237 rec->fNext = gFaceRecHead;
238 gFaceRecHead = rec;
239 rec->fRefCnt = 1;
240 return rec;
241 }
242}
243
244static void unref_ft_face(FT_Face face) {
245 SkFaceRec* rec = gFaceRecHead;
246 SkFaceRec* prev = NULL;
247 while (rec) {
248 SkFaceRec* next = rec->fNext;
249 if (rec->fFace == face) {
250 if (--rec->fRefCnt == 0) {
251 if (prev) {
252 prev->fNext = next;
253 } else {
254 gFaceRecHead = next;
255 }
256 FT_Done_Face(face);
257 SkDELETE(rec);
258 }
259 return;
260 }
261 prev = rec;
262 rec = next;
263 }
264 SkASSERT("shouldn't get here, face not in list");
265}
266
267///////////////////////////////////////////////////////////////////////////
268
reed@android.com36a4c2a2009-07-22 19:52:11 +0000269void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000270 if (!gLCDSupportValid) {
271 InitFreetype();
272 FT_Done_FreeType(gFTLibrary);
273 }
274
275 if (!gLCDSupport && rec->isLCD()) {
276 // If the runtime Freetype library doesn't support LCD mode, we disable
277 // it here.
278 rec->fMaskFormat = SkMask::kA8_Format;
279 }
280
reed@android.com36a4c2a2009-07-22 19:52:11 +0000281 SkPaint::Hinting h = rec->getHinting();
282 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
reed@android.come4d0bc02009-07-24 19:53:20 +0000283 // collapse full->normaling hinting if we're not doing LCD
284 h = SkPaint::kNormal_Hinting;
285 } else if (rec->fSubpixelPositioning && SkPaint::kNo_Hinting != h) {
286 // to do subpixel, we must have at most slight hinting
287 h = SkPaint::kSlight_Hinting;
reed@android.com36a4c2a2009-07-22 19:52:11 +0000288 }
reed@android.come4d0bc02009-07-24 19:53:20 +0000289 rec->setHinting(h);
reed@android.com36a4c2a2009-07-22 19:52:11 +0000290}
291
reed@android.com8a1c16f2008-12-17 15:59:43 +0000292SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000293 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000294 SkAutoMutexAcquire ac(gFTMutex);
295
reed@android.com8a1c16f2008-12-17 15:59:43 +0000296 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000297 if (!InitFreetype()) {
298 sk_throw();
299 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000300 }
301 ++gFTCount;
302
303 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000304 fFTSize = NULL;
305 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000307 if (NULL == fFaceRec) {
308 return;
309 }
310 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000311
312 // compute our factors from the record
313
314 SkMatrix m;
315
316 fRec.getSingleMatrix(&m);
317
318#ifdef DUMP_STRIKE_CREATION
319 SkString keyString;
320 SkFontHost::GetDescriptorKeyString(desc, &keyString);
321 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
322 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
323 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
324 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000325 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000326#endif
327
328 // now compute our scale factors
329 SkScalar sx = m.getScaleX();
330 SkScalar sy = m.getScaleY();
331
332 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
333 // sort of give up on hinting
334 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
335 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
336 sx = sy = SkScalarAve(sx, sy);
337
338 SkScalar inv = SkScalarInvert(sx);
339
340 // flip the skew elements to go from our Y-down system to FreeType's
341 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
342 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
343 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
344 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
345 } else {
346 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
347 fMatrix22.xy = fMatrix22.yx = 0;
348 }
349
350 fScaleX = SkScalarToFixed(sx);
351 fScaleY = SkScalarToFixed(sy);
352
353 // compute the flags we send to Load_Glyph
354 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000355 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000356
agl@chromium.org309485b2009-07-21 17:41:32 +0000357 switch (fRec.getHinting()) {
358 case SkPaint::kNo_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000359 loadFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000360 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000361 case SkPaint::kSlight_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000362 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000363 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000364 case SkPaint::kNormal_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000365 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000366 break;
367 case SkPaint::kFull_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000368 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000369 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000370 loadFlags = FT_LOAD_TARGET_LCD;
agl@chromium.org309485b2009-07-21 17:41:32 +0000371 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000372 loadFlags = FT_LOAD_TARGET_LCD_V;
373 break;
374 default:
375 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000376 break;
377 }
378
agl@chromium.orge95c91e2010-01-04 18:27:55 +0000379 if (!fRec.fUseEmbeddedBitmapText) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000380 loadFlags |= FT_LOAD_NO_BITMAP;
381 }
382
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
474static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
475 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000476 case SkMask::kHorizontalLCD_Format:
477 case SkMask::kVerticalLCD_Format:
478 SkASSERT(!"An LCD format should never be passed here");
479 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000480 case SkMask::kBW_Format:
481 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000482 case SkMask::kA8_Format:
483 default:
484 return FT_PIXEL_MODE_GRAY;
485 }
486}
487
reed@android.com8a1c16f2008-12-17 15:59:43 +0000488void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
489#ifdef FT_ADVANCES_H
490 /* unhinted and light hinted text have linearly scaled advances
491 * which are very cheap to compute with some font formats...
492 */
493 {
494 SkAutoMutexAcquire ac(gFTMutex);
495
496 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000497 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000498 return;
499 }
500
501 FT_Error error;
502 FT_Fixed advance;
503
504 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
505 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
506 &advance );
507 if (0 == error) {
508 glyph->fRsbDelta = 0;
509 glyph->fLsbDelta = 0;
510 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
511 glyph->fAdvanceY = 0;
512 return;
513 }
514 }
515#endif /* FT_ADVANCES_H */
516 /* otherwise, we need to load/hint the glyph, which is slower */
517 this->generateMetrics(glyph);
518 return;
519}
520
521void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
522 SkAutoMutexAcquire ac(gFTMutex);
523
524 glyph->fRsbDelta = 0;
525 glyph->fLsbDelta = 0;
526
527 FT_Error err;
528
529 if (this->setupSize()) {
530 goto ERROR;
531 }
532
533 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
534 if (err != 0) {
535 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
536 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
537 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000538 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000539 return;
540 }
541
542 switch ( fFace->glyph->format ) {
543 case FT_GLYPH_FORMAT_OUTLINE:
544 FT_BBox bbox;
545
546 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
547
agl@chromium.org309485b2009-07-21 17:41:32 +0000548 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000549 int dx = glyph->getSubXFixed() >> 10;
550 int dy = glyph->getSubYFixed() >> 10;
551 // negate dy since freetype-y-goes-up and skia-y-goes-down
552 bbox.xMin += dx;
553 bbox.yMin -= dy;
554 bbox.xMax += dx;
555 bbox.yMax -= dy;
556 }
557
558 bbox.xMin &= ~63;
559 bbox.yMin &= ~63;
560 bbox.xMax = (bbox.xMax + 63) & ~63;
561 bbox.yMax = (bbox.yMax + 63) & ~63;
562
563 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
564 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
565 glyph->fTop = -SkToS16(bbox.yMax >> 6);
566 glyph->fLeft = SkToS16(bbox.xMin >> 6);
567 break;
568
569 case FT_GLYPH_FORMAT_BITMAP:
570 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
571 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
572 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
573 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
574 break;
575
576 default:
577 SkASSERT(!"unknown glyph format");
578 goto ERROR;
579 }
580
agl@chromium.org309485b2009-07-21 17:41:32 +0000581 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000582 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
583 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
584 if (fRec.fFlags & kDevKernText_Flag) {
585 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
586 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
587 }
588 } else {
589 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
590 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
591 }
592
593#ifdef ENABLE_GLYPH_SPEW
594 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
595 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
596#endif
597}
598
reed@android.comf5493692009-07-22 19:21:01 +0000599#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000600namespace skia_freetype_support {
601// extern functions from SkFontHost_FreeType_Subpixel
602extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
603extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
604}
605
606using namespace skia_freetype_support;
607#endif
608
reed@android.com8a1c16f2008-12-17 15:59:43 +0000609void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
610 SkAutoMutexAcquire ac(gFTMutex);
611
612 FT_Error err;
613
614 if (this->setupSize()) {
615 goto ERROR;
616 }
617
618 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
619 if (err != 0) {
620 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
621 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
622 ERROR:
623 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
624 return;
625 }
626
agl@chromium.org309485b2009-07-21 17:41:32 +0000627 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
628 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
629
reed@android.com8a1c16f2008-12-17 15:59:43 +0000630 switch ( fFace->glyph->format ) {
631 case FT_GLYPH_FORMAT_OUTLINE: {
632 FT_Outline* outline = &fFace->glyph->outline;
633 FT_BBox bbox;
634 FT_Bitmap target;
635
636 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000637 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000638 dx = glyph.getSubXFixed() >> 10;
639 dy = glyph.getSubYFixed() >> 10;
640 // negate dy since freetype-y-goes-up and skia-y-goes-down
641 dy = -dy;
642 }
643 FT_Outline_Get_CBox(outline, &bbox);
644 /*
645 what we really want to do for subpixel is
646 offset(dx, dy)
647 compute_bounds
648 offset(bbox & !63)
649 but that is two calls to offset, so we do the following, which
650 achieves the same thing with only one offset call.
651 */
652 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
653 dy - ((bbox.yMin + dy) & ~63));
654
reed@android.comf5493692009-07-22 19:21:01 +0000655#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000656 if (lcdRenderMode) {
657 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
658 // we have to call FT_Render_Glyph and memcpy the image out.
659 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
660 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
661 FT_Render_Glyph(fFace->glyph, mode);
662
663 if (isVertical)
664 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
665 else
666 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
667
668 break;
669 }
670#endif
671
reed@android.com8a1c16f2008-12-17 15:59:43 +0000672 target.width = glyph.fWidth;
673 target.rows = glyph.fHeight;
674 target.pitch = glyph.rowBytes();
675 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
676 target.pixel_mode = compute_pixel_mode(
677 (SkMask::Format)fRec.fMaskFormat);
678 target.num_grays = 256;
679
680 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
681 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
682 } break;
683
684 case FT_GLYPH_FORMAT_BITMAP: {
685 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
686 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
687 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
688 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
689
690 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
691 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000692
agl@chromium.org558434a2009-08-11 17:22:38 +0000693 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
694 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
695 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000696 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
697 unsigned dstRowBytes = glyph.rowBytes();
698 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
699 unsigned extraRowBytes = dstRowBytes - minRowBytes;
700
701 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
702 memcpy(dst, src, minRowBytes);
703 memset(dst + minRowBytes, 0, extraRowBytes);
704 src += srcRowBytes;
705 dst += dstRowBytes;
706 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000707 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +0000708 (glyph.fMaskFormat == SkMask::kA8_Format ||
709 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
710 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000711 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
712 uint8_t byte = 0;
713 int bits = 0;
714 const uint8_t* src_row = src;
715 uint8_t* dst_row = dst;
716
717 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
718 if (!bits) {
719 byte = *src_row++;
720 bits = 8;
721 }
722
723 *dst_row++ = byte & 0x80 ? 0xff : 0;
724 bits--;
725 byte <<= 1;
726 }
727
728 src += fFace->glyph->bitmap.pitch;
729 dst += glyph.rowBytes();
730 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000731 } else {
732 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000733 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000734
735 if (lcdRenderMode)
736 glyph.expandA8ToLCD();
737
reed@android.com8a1c16f2008-12-17 15:59:43 +0000738 } break;
739
740 default:
741 SkASSERT(!"unknown glyph format");
742 goto ERROR;
743 }
744}
745
746///////////////////////////////////////////////////////////////////////////////
747
748#define ft2sk(x) SkFixedToScalar((x) << 10)
749
reed@android.com6f252972009-01-14 16:46:16 +0000750#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000751 #define CONST_PARAM const
752#else // older freetype doesn't use const here
753 #define CONST_PARAM
754#endif
755
756static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
757 SkPath* path = (SkPath*)ctx;
758 path->close(); // to close the previous contour (if any)
759 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
760 return 0;
761}
762
763static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
764 SkPath* path = (SkPath*)ctx;
765 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
766 return 0;
767}
768
769static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
770 void* ctx) {
771 SkPath* path = (SkPath*)ctx;
772 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
773 return 0;
774}
775
776static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
777 CONST_PARAM FT_Vector* pt2, void* ctx) {
778 SkPath* path = (SkPath*)ctx;
779 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
780 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
781 return 0;
782}
783
784void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
785 SkPath* path) {
786 SkAutoMutexAcquire ac(gFTMutex);
787
788 SkASSERT(&glyph && path);
789
790 if (this->setupSize()) {
791 path->reset();
792 return;
793 }
794
795 uint32_t flags = fLoadGlyphFlags;
796 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
797 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
798
799 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
800
801 if (err != 0) {
802 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
803 glyph.getGlyphID(fBaseGlyphCount), flags, err));
804 path->reset();
805 return;
806 }
807
808 FT_Outline_Funcs funcs;
809
810 funcs.move_to = move_proc;
811 funcs.line_to = line_proc;
812 funcs.conic_to = quad_proc;
813 funcs.cubic_to = cubic_proc;
814 funcs.shift = 0;
815 funcs.delta = 0;
816
817 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
818
819 if (err != 0) {
820 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
821 glyph.getGlyphID(fBaseGlyphCount), flags, err));
822 path->reset();
823 return;
824 }
825
826 path->close();
827}
828
829void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
830 SkPaint::FontMetrics* my) {
831 if (NULL == mx && NULL == my) {
832 return;
833 }
834
835 SkAutoMutexAcquire ac(gFTMutex);
836
837 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000838 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000839 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000840 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000841 }
842 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000843 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000844 }
845 return;
846 }
847
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000848 FT_Face face = fFace;
849 int upem = face->units_per_EM;
850 if (upem <= 0) {
851 goto ERROR;
852 }
853
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000854 SkPoint pts[6];
855 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000856 SkFixed scaleY = fScaleY;
857 SkFixed mxy = fMatrix22.xy;
858 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000859 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
860 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000861
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000862 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000863 if (leading < 0) {
864 leading = 0;
865 }
866
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000867 // Try to get the OS/2 table from the font. This contains the specific
868 // average font width metrics which Windows uses.
869 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
870
reed@android.com8a1c16f2008-12-17 15:59:43 +0000871 ys[0] = -face->bbox.yMax;
872 ys[1] = -face->ascender;
873 ys[2] = -face->descender;
874 ys[3] = -face->bbox.yMin;
875 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000876 ys[5] = os2 ? os2->xAvgCharWidth : 0;
877
878 SkScalar x_height;
879 if (os2 && os2->sxHeight) {
880 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
881 } else {
882 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
883 if (x_glyph) {
884 FT_BBox bbox;
885 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
886 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
887 x_height = SkIntToScalar(bbox.yMax) / 64;
888 } else {
889 x_height = 0;
890 }
891 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000892
893 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000894 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000895 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
896 SkFixed x = SkFixedMul(mxy, y);
897 y = SkFixedMul(myy, y);
898 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
899 }
900
901 if (mx) {
902 mx->fTop = pts[0].fX;
903 mx->fAscent = pts[1].fX;
904 mx->fDescent = pts[2].fX;
905 mx->fBottom = pts[3].fX;
906 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000907 mx->fAvgCharWidth = pts[5].fX;
908 mx->fXMin = xmin;
909 mx->fXMax = xmax;
910 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000911 }
912 if (my) {
913 my->fTop = pts[0].fY;
914 my->fAscent = pts[1].fY;
915 my->fDescent = pts[2].fY;
916 my->fBottom = pts[3].fY;
917 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000918 my->fAvgCharWidth = pts[5].fY;
919 my->fXMin = xmin;
920 my->fXMax = xmax;
921 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000922 }
923}
924
925////////////////////////////////////////////////////////////////////////
926////////////////////////////////////////////////////////////////////////
927
928SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000929 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
930 if (!c->success()) {
931 SkDELETE(c);
932 c = NULL;
933 }
934 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000935}
936
937///////////////////////////////////////////////////////////////////////////////
938
939/* Export this so that other parts of our FonttHost port can make use of our
940 ability to extract the name+style from a stream, using FreeType's api.
941*/
942SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
943 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +0000944 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000945 name->set(NULL);
946 return SkTypeface::kNormal;
947 }
948
949 FT_Open_Args args;
950 memset(&args, 0, sizeof(args));
951
952 const void* memoryBase = stream->getMemoryBase();
953 FT_StreamRec streamRec;
954
955 if (NULL != memoryBase) {
956 args.flags = FT_OPEN_MEMORY;
957 args.memory_base = (const FT_Byte*)memoryBase;
958 args.memory_size = stream->getLength();
959 } else {
960 memset(&streamRec, 0, sizeof(streamRec));
961 streamRec.size = stream->read(NULL, 0);
962 streamRec.descriptor.pointer = stream;
963 streamRec.read = sk_stream_read;
964 streamRec.close = sk_stream_close;
965
966 args.flags = FT_OPEN_STREAM;
967 args.stream = &streamRec;
968 }
969
970 FT_Face face;
971 if (FT_Open_Face(library, &args, 0, &face)) {
972 FT_Done_FreeType(library);
973 name->set(NULL);
974 return SkTypeface::kNormal;
975 }
976
977 name->set(face->family_name);
978 int style = SkTypeface::kNormal;
979
980 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
981 style |= SkTypeface::kBold;
982 }
983 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
984 style |= SkTypeface::kItalic;
985 }
986
987 FT_Done_Face(face);
988 FT_Done_FreeType(library);
989 return (SkTypeface::Style)style;
990}