blob: e09e542819732f14323f939f18432bb4a0120d85 [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.orge0d08992009-08-07 19:19:23 +0000379 if (fRec.fMaskFormat != SkMask::kBW_Format) {
380 // If the user requested anti-aliasing then we don't use bitmap
381 // strikes in the font. The consensus among our Japanese users is
382 // that this results in the best quality.
383 loadFlags |= FT_LOAD_NO_BITMAP;
384 }
385
reed@android.come4d0bc02009-07-24 19:53:20 +0000386 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000387 }
388
389 // now create the FT_Size
390
391 {
392 FT_Error err;
393
394 err = FT_New_Size(fFace, &fFTSize);
395 if (err != 0) {
396 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
397 fFaceRec->fFontID, fScaleX, fScaleY, err));
398 fFace = NULL;
399 return;
400 }
401
402 err = FT_Activate_Size(fFTSize);
403 if (err != 0) {
404 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
405 fFaceRec->fFontID, fScaleX, fScaleY, err));
406 fFTSize = NULL;
407 }
408
409 err = FT_Set_Char_Size( fFace,
410 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
411 72, 72);
412 if (err != 0) {
413 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
414 fFaceRec->fFontID, fScaleX, fScaleY, err));
415 fFace = NULL;
416 return;
417 }
418
419 FT_Set_Transform( fFace, &fMatrix22, NULL);
420 }
421}
422
423SkScalerContext_FreeType::~SkScalerContext_FreeType() {
424 if (fFTSize != NULL) {
425 FT_Done_Size(fFTSize);
426 }
427
428 SkAutoMutexAcquire ac(gFTMutex);
429
430 if (fFace != NULL) {
431 unref_ft_face(fFace);
432 }
433 if (--gFTCount == 0) {
434// SkDEBUGF(("FT_Done_FreeType\n"));
435 FT_Done_FreeType(gFTLibrary);
436 SkDEBUGCODE(gFTLibrary = NULL;)
437 }
438}
439
440/* We call this before each use of the fFace, since we may be sharing
441 this face with other context (at different sizes).
442*/
443FT_Error SkScalerContext_FreeType::setupSize() {
444 /* In the off-chance that a font has been removed, we want to error out
445 right away, so call resolve just to be sure.
446
447 TODO: perhaps we can skip this, by walking the global font cache and
448 killing all of the contexts when we know that a given fontID is going
449 away...
450 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000451 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000452 return (FT_Error)-1;
453 }
454
455 FT_Error err = FT_Activate_Size(fFTSize);
456
457 if (err != 0) {
458 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
459 fFaceRec->fFontID, fScaleX, fScaleY, err));
460 fFTSize = NULL;
461 } else {
462 // seems we need to reset this every time (not sure why, but without it
463 // I get random italics from some other fFTSize)
464 FT_Set_Transform( fFace, &fMatrix22, NULL);
465 }
466 return err;
467}
468
469unsigned SkScalerContext_FreeType::generateGlyphCount() const {
470 return fFace->num_glyphs;
471}
472
473uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
474 return SkToU16(FT_Get_Char_Index( fFace, uni ));
475}
476
477static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
478 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000479 case SkMask::kHorizontalLCD_Format:
480 case SkMask::kVerticalLCD_Format:
481 SkASSERT(!"An LCD format should never be passed here");
482 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000483 case SkMask::kBW_Format:
484 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000485 case SkMask::kA8_Format:
486 default:
487 return FT_PIXEL_MODE_GRAY;
488 }
489}
490
reed@android.com8a1c16f2008-12-17 15:59:43 +0000491void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
492#ifdef FT_ADVANCES_H
493 /* unhinted and light hinted text have linearly scaled advances
494 * which are very cheap to compute with some font formats...
495 */
496 {
497 SkAutoMutexAcquire ac(gFTMutex);
498
499 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000500 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000501 return;
502 }
503
504 FT_Error error;
505 FT_Fixed advance;
506
507 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
508 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
509 &advance );
510 if (0 == error) {
511 glyph->fRsbDelta = 0;
512 glyph->fLsbDelta = 0;
513 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
514 glyph->fAdvanceY = 0;
515 return;
516 }
517 }
518#endif /* FT_ADVANCES_H */
519 /* otherwise, we need to load/hint the glyph, which is slower */
520 this->generateMetrics(glyph);
521 return;
522}
523
524void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
525 SkAutoMutexAcquire ac(gFTMutex);
526
527 glyph->fRsbDelta = 0;
528 glyph->fLsbDelta = 0;
529
530 FT_Error err;
531
532 if (this->setupSize()) {
533 goto ERROR;
534 }
535
536 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
537 if (err != 0) {
538 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
539 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
540 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000541 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000542 return;
543 }
544
545 switch ( fFace->glyph->format ) {
546 case FT_GLYPH_FORMAT_OUTLINE:
547 FT_BBox bbox;
548
549 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
550
agl@chromium.org309485b2009-07-21 17:41:32 +0000551 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000552 int dx = glyph->getSubXFixed() >> 10;
553 int dy = glyph->getSubYFixed() >> 10;
554 // negate dy since freetype-y-goes-up and skia-y-goes-down
555 bbox.xMin += dx;
556 bbox.yMin -= dy;
557 bbox.xMax += dx;
558 bbox.yMax -= dy;
559 }
560
561 bbox.xMin &= ~63;
562 bbox.yMin &= ~63;
563 bbox.xMax = (bbox.xMax + 63) & ~63;
564 bbox.yMax = (bbox.yMax + 63) & ~63;
565
566 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
567 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
568 glyph->fTop = -SkToS16(bbox.yMax >> 6);
569 glyph->fLeft = SkToS16(bbox.xMin >> 6);
570 break;
571
572 case FT_GLYPH_FORMAT_BITMAP:
573 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
574 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
575 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
576 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
577 break;
578
579 default:
580 SkASSERT(!"unknown glyph format");
581 goto ERROR;
582 }
583
agl@chromium.org309485b2009-07-21 17:41:32 +0000584 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000585 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
586 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
587 if (fRec.fFlags & kDevKernText_Flag) {
588 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
589 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
590 }
591 } else {
592 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
593 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
594 }
595
596#ifdef ENABLE_GLYPH_SPEW
597 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
598 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
599#endif
600}
601
reed@android.comf5493692009-07-22 19:21:01 +0000602#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000603namespace skia_freetype_support {
604// extern functions from SkFontHost_FreeType_Subpixel
605extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
606extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
607}
608
609using namespace skia_freetype_support;
610#endif
611
reed@android.com8a1c16f2008-12-17 15:59:43 +0000612void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
613 SkAutoMutexAcquire ac(gFTMutex);
614
615 FT_Error err;
616
617 if (this->setupSize()) {
618 goto ERROR;
619 }
620
621 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
622 if (err != 0) {
623 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
624 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
625 ERROR:
626 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
627 return;
628 }
629
agl@chromium.org309485b2009-07-21 17:41:32 +0000630 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
631 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
632
reed@android.com8a1c16f2008-12-17 15:59:43 +0000633 switch ( fFace->glyph->format ) {
634 case FT_GLYPH_FORMAT_OUTLINE: {
635 FT_Outline* outline = &fFace->glyph->outline;
636 FT_BBox bbox;
637 FT_Bitmap target;
638
639 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000640 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000641 dx = glyph.getSubXFixed() >> 10;
642 dy = glyph.getSubYFixed() >> 10;
643 // negate dy since freetype-y-goes-up and skia-y-goes-down
644 dy = -dy;
645 }
646 FT_Outline_Get_CBox(outline, &bbox);
647 /*
648 what we really want to do for subpixel is
649 offset(dx, dy)
650 compute_bounds
651 offset(bbox & !63)
652 but that is two calls to offset, so we do the following, which
653 achieves the same thing with only one offset call.
654 */
655 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
656 dy - ((bbox.yMin + dy) & ~63));
657
reed@android.comf5493692009-07-22 19:21:01 +0000658#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000659 if (lcdRenderMode) {
660 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
661 // we have to call FT_Render_Glyph and memcpy the image out.
662 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
663 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
664 FT_Render_Glyph(fFace->glyph, mode);
665
666 if (isVertical)
667 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
668 else
669 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
670
671 break;
672 }
673#endif
674
reed@android.com8a1c16f2008-12-17 15:59:43 +0000675 target.width = glyph.fWidth;
676 target.rows = glyph.fHeight;
677 target.pitch = glyph.rowBytes();
678 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
679 target.pixel_mode = compute_pixel_mode(
680 (SkMask::Format)fRec.fMaskFormat);
681 target.num_grays = 256;
682
683 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
684 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
685 } break;
686
687 case FT_GLYPH_FORMAT_BITMAP: {
688 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
689 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
690 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
691 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
692
693 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
694 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000695
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000696 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
697 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
698 unsigned dstRowBytes = glyph.rowBytes();
699 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
700 unsigned extraRowBytes = dstRowBytes - minRowBytes;
701
702 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
703 memcpy(dst, src, minRowBytes);
704 memset(dst + minRowBytes, 0, extraRowBytes);
705 src += srcRowBytes;
706 dst += dstRowBytes;
707 }
708 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
709 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
710 uint8_t byte = 0;
711 int bits = 0;
712 const uint8_t* src_row = src;
713 uint8_t* dst_row = dst;
714
715 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
716 if (!bits) {
717 byte = *src_row++;
718 bits = 8;
719 }
720
721 *dst_row++ = byte & 0x80 ? 0xff : 0;
722 bits--;
723 byte <<= 1;
724 }
725
726 src += fFace->glyph->bitmap.pitch;
727 dst += glyph.rowBytes();
728 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000729 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000730
731 if (lcdRenderMode)
732 glyph.expandA8ToLCD();
733
reed@android.com8a1c16f2008-12-17 15:59:43 +0000734 } break;
735
736 default:
737 SkASSERT(!"unknown glyph format");
738 goto ERROR;
739 }
740}
741
742///////////////////////////////////////////////////////////////////////////////
743
744#define ft2sk(x) SkFixedToScalar((x) << 10)
745
reed@android.com6f252972009-01-14 16:46:16 +0000746#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000747 #define CONST_PARAM const
748#else // older freetype doesn't use const here
749 #define CONST_PARAM
750#endif
751
752static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
753 SkPath* path = (SkPath*)ctx;
754 path->close(); // to close the previous contour (if any)
755 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
756 return 0;
757}
758
759static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
760 SkPath* path = (SkPath*)ctx;
761 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
762 return 0;
763}
764
765static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
766 void* ctx) {
767 SkPath* path = (SkPath*)ctx;
768 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
769 return 0;
770}
771
772static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
773 CONST_PARAM FT_Vector* pt2, void* ctx) {
774 SkPath* path = (SkPath*)ctx;
775 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
776 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
777 return 0;
778}
779
780void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
781 SkPath* path) {
782 SkAutoMutexAcquire ac(gFTMutex);
783
784 SkASSERT(&glyph && path);
785
786 if (this->setupSize()) {
787 path->reset();
788 return;
789 }
790
791 uint32_t flags = fLoadGlyphFlags;
792 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
793 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
794
795 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
796
797 if (err != 0) {
798 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
799 glyph.getGlyphID(fBaseGlyphCount), flags, err));
800 path->reset();
801 return;
802 }
803
804 FT_Outline_Funcs funcs;
805
806 funcs.move_to = move_proc;
807 funcs.line_to = line_proc;
808 funcs.conic_to = quad_proc;
809 funcs.cubic_to = cubic_proc;
810 funcs.shift = 0;
811 funcs.delta = 0;
812
813 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
814
815 if (err != 0) {
816 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
817 glyph.getGlyphID(fBaseGlyphCount), flags, err));
818 path->reset();
819 return;
820 }
821
822 path->close();
823}
824
825void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
826 SkPaint::FontMetrics* my) {
827 if (NULL == mx && NULL == my) {
828 return;
829 }
830
831 SkAutoMutexAcquire ac(gFTMutex);
832
833 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000834 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000835 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000836 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837 }
838 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000839 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000840 }
841 return;
842 }
843
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000844 FT_Face face = fFace;
845 int upem = face->units_per_EM;
846 if (upem <= 0) {
847 goto ERROR;
848 }
849
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000850 SkPoint pts[6];
851 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000852 SkFixed scaleY = fScaleY;
853 SkFixed mxy = fMatrix22.xy;
854 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000855 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
856 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000857
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000858 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000859 if (leading < 0) {
860 leading = 0;
861 }
862
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000863 // Try to get the OS/2 table from the font. This contains the specific
864 // average font width metrics which Windows uses.
865 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
866
reed@android.com8a1c16f2008-12-17 15:59:43 +0000867 ys[0] = -face->bbox.yMax;
868 ys[1] = -face->ascender;
869 ys[2] = -face->descender;
870 ys[3] = -face->bbox.yMin;
871 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000872 ys[5] = os2 ? os2->xAvgCharWidth : 0;
873
874 SkScalar x_height;
875 if (os2 && os2->sxHeight) {
876 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
877 } else {
878 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
879 if (x_glyph) {
880 FT_BBox bbox;
881 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
882 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
883 x_height = SkIntToScalar(bbox.yMax) / 64;
884 } else {
885 x_height = 0;
886 }
887 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000888
889 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000890 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000891 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
892 SkFixed x = SkFixedMul(mxy, y);
893 y = SkFixedMul(myy, y);
894 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
895 }
896
897 if (mx) {
898 mx->fTop = pts[0].fX;
899 mx->fAscent = pts[1].fX;
900 mx->fDescent = pts[2].fX;
901 mx->fBottom = pts[3].fX;
902 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000903 mx->fAvgCharWidth = pts[5].fX;
904 mx->fXMin = xmin;
905 mx->fXMax = xmax;
906 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000907 }
908 if (my) {
909 my->fTop = pts[0].fY;
910 my->fAscent = pts[1].fY;
911 my->fDescent = pts[2].fY;
912 my->fBottom = pts[3].fY;
913 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000914 my->fAvgCharWidth = pts[5].fY;
915 my->fXMin = xmin;
916 my->fXMax = xmax;
917 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000918 }
919}
920
921////////////////////////////////////////////////////////////////////////
922////////////////////////////////////////////////////////////////////////
923
924SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000925 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
926 if (!c->success()) {
927 SkDELETE(c);
928 c = NULL;
929 }
930 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000931}
932
933///////////////////////////////////////////////////////////////////////////////
934
935/* Export this so that other parts of our FonttHost port can make use of our
936 ability to extract the name+style from a stream, using FreeType's api.
937*/
938SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
939 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +0000940 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000941 name->set(NULL);
942 return SkTypeface::kNormal;
943 }
944
945 FT_Open_Args args;
946 memset(&args, 0, sizeof(args));
947
948 const void* memoryBase = stream->getMemoryBase();
949 FT_StreamRec streamRec;
950
951 if (NULL != memoryBase) {
952 args.flags = FT_OPEN_MEMORY;
953 args.memory_base = (const FT_Byte*)memoryBase;
954 args.memory_size = stream->getLength();
955 } else {
956 memset(&streamRec, 0, sizeof(streamRec));
957 streamRec.size = stream->read(NULL, 0);
958 streamRec.descriptor.pointer = stream;
959 streamRec.read = sk_stream_read;
960 streamRec.close = sk_stream_close;
961
962 args.flags = FT_OPEN_STREAM;
963 args.stream = &streamRec;
964 }
965
966 FT_Face face;
967 if (FT_Open_Face(library, &args, 0, &face)) {
968 FT_Done_FreeType(library);
969 name->set(NULL);
970 return SkTypeface::kNormal;
971 }
972
973 name->set(face->family_name);
974 int style = SkTypeface::kNormal;
975
976 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
977 style |= SkTypeface::kBold;
978 }
979 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
980 style |= SkTypeface::kItalic;
981 }
982
983 FT_Done_Face(face);
984 FT_Done_FreeType(library);
985 return (SkTypeface::Style)style;
986}