blob: fa10362d4e543f8042fd94e7b159d62691249fe2 [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;
76
77/////////////////////////////////////////////////////////////////////////
78
agl@chromium.org309485b2009-07-21 17:41:32 +000079static bool
80InitFreetype() {
81 FT_Error err = FT_Init_FreeType(&gFTLibrary);
82 if (err)
83 return false;
84
reed@android.comf5493692009-07-22 19:21:01 +000085#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000086 // Setup LCD filtering. This reduces colour fringes for LCD rendered
87 // glyphs.
88 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
89#endif
90
91 return true;
92}
93
reed@android.com8a1c16f2008-12-17 15:59:43 +000094class SkScalerContext_FreeType : public SkScalerContext {
95public:
96 SkScalerContext_FreeType(const SkDescriptor* desc);
97 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000098
reed@android.com62900b42009-02-11 15:07:19 +000099 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000100 return fFaceRec != NULL &&
101 fFTSize != NULL &&
102 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000103 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000104
105protected:
106 virtual unsigned generateGlyphCount() const;
107 virtual uint16_t generateCharToGlyph(SkUnichar uni);
108 virtual void generateAdvance(SkGlyph* glyph);
109 virtual void generateMetrics(SkGlyph* glyph);
110 virtual void generateImage(const SkGlyph& glyph);
111 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
112 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
113 SkPaint::FontMetrics* my);
114
115private:
116 SkFaceRec* fFaceRec;
117 FT_Face fFace; // reference to shared face in gFaceRecHead
118 FT_Size fFTSize; // our own copy
119 SkFixed fScaleX, fScaleY;
120 FT_Matrix fMatrix22;
121 uint32_t fLoadGlyphFlags;
122
123 FT_Error setupSize();
124};
125
126///////////////////////////////////////////////////////////////////////////
127///////////////////////////////////////////////////////////////////////////
128
129#include "SkStream.h"
130
131struct SkFaceRec {
132 SkFaceRec* fNext;
133 FT_Face fFace;
134 FT_StreamRec fFTStream;
135 SkStream* fSkStream;
136 uint32_t fRefCnt;
137 uint32_t fFontID;
138
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000139 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000140 SkFaceRec(SkStream* strm, uint32_t fontID);
141 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000142 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000143 }
144};
145
146extern "C" {
147 static unsigned long sk_stream_read(FT_Stream stream,
148 unsigned long offset,
149 unsigned char* buffer,
150 unsigned long count ) {
151 SkStream* str = (SkStream*)stream->descriptor.pointer;
152
153 if (count) {
154 if (!str->rewind()) {
155 return 0;
156 } else {
157 unsigned long ret;
158 if (offset) {
159 ret = str->read(NULL, offset);
160 if (ret != offset) {
161 return 0;
162 }
163 }
164 ret = str->read(buffer, count);
165 if (ret != count) {
166 return 0;
167 }
168 count = ret;
169 }
170 }
171 return count;
172 }
173
174 static void sk_stream_close( FT_Stream stream) {}
175}
176
177SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
178 : fSkStream(strm), fFontID(fontID) {
179// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
180
reed@android.com4516f472009-06-29 16:25:36 +0000181 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182 fFTStream.size = fSkStream->getLength();
183 fFTStream.descriptor.pointer = fSkStream;
184 fFTStream.read = sk_stream_read;
185 fFTStream.close = sk_stream_close;
186}
187
reed@android.com62900b42009-02-11 15:07:19 +0000188// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000189static SkFaceRec* ref_ft_face(uint32_t fontID) {
190 SkFaceRec* rec = gFaceRecHead;
191 while (rec) {
192 if (rec->fFontID == fontID) {
193 SkASSERT(rec->fFace);
194 rec->fRefCnt += 1;
195 return rec;
196 }
197 rec = rec->fNext;
198 }
199
200 SkStream* strm = SkFontHost::OpenStream(fontID);
201 if (NULL == strm) {
202 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000203 return 0;
204 }
205
206 // this passes ownership of strm to the rec
207 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
208
209 FT_Open_Args args;
210 memset(&args, 0, sizeof(args));
211 const void* memoryBase = strm->getMemoryBase();
212
213 if (NULL != memoryBase) {
214//printf("mmap(%s)\n", keyString.c_str());
215 args.flags = FT_OPEN_MEMORY;
216 args.memory_base = (const FT_Byte*)memoryBase;
217 args.memory_size = strm->getLength();
218 } else {
219//printf("fopen(%s)\n", keyString.c_str());
220 args.flags = FT_OPEN_STREAM;
221 args.stream = &rec->fFTStream;
222 }
223
224 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
225
226 if (err) { // bad filename, try the default font
227 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
228 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000229 return 0;
230 } else {
231 SkASSERT(rec->fFace);
232 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
233 rec->fNext = gFaceRecHead;
234 gFaceRecHead = rec;
235 rec->fRefCnt = 1;
236 return rec;
237 }
238}
239
240static void unref_ft_face(FT_Face face) {
241 SkFaceRec* rec = gFaceRecHead;
242 SkFaceRec* prev = NULL;
243 while (rec) {
244 SkFaceRec* next = rec->fNext;
245 if (rec->fFace == face) {
246 if (--rec->fRefCnt == 0) {
247 if (prev) {
248 prev->fNext = next;
249 } else {
250 gFaceRecHead = next;
251 }
252 FT_Done_Face(face);
253 SkDELETE(rec);
254 }
255 return;
256 }
257 prev = rec;
258 rec = next;
259 }
260 SkASSERT("shouldn't get here, face not in list");
261}
262
263///////////////////////////////////////////////////////////////////////////
264
265SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000266 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000267 SkAutoMutexAcquire ac(gFTMutex);
268
269 FT_Error err;
270
271 if (gFTCount == 0) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000272 const bool success = InitFreetype();
273 SkASSERT(success);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000274 }
275 ++gFTCount;
276
277 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000278 fFTSize = NULL;
279 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000280 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000281 if (NULL == fFaceRec) {
282 return;
283 }
284 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000285
286 // compute our factors from the record
287
288 SkMatrix m;
289
290 fRec.getSingleMatrix(&m);
291
292#ifdef DUMP_STRIKE_CREATION
293 SkString keyString;
294 SkFontHost::GetDescriptorKeyString(desc, &keyString);
295 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
296 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
297 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
298 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000299 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000300#endif
301
302 // now compute our scale factors
303 SkScalar sx = m.getScaleX();
304 SkScalar sy = m.getScaleY();
305
306 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
307 // sort of give up on hinting
308 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
309 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
310 sx = sy = SkScalarAve(sx, sy);
311
312 SkScalar inv = SkScalarInvert(sx);
313
314 // flip the skew elements to go from our Y-down system to FreeType's
315 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
316 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
317 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
318 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
319 } else {
320 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
321 fMatrix22.xy = fMatrix22.yx = 0;
322 }
323
324 fScaleX = SkScalarToFixed(sx);
325 fScaleY = SkScalarToFixed(sy);
326
327 // compute the flags we send to Load_Glyph
328 {
agl@chromium.org309485b2009-07-21 17:41:32 +0000329 FT_Int32 hintingFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000330
agl@chromium.org309485b2009-07-21 17:41:32 +0000331 switch (fRec.getHinting()) {
332 case SkPaint::kNo_Hinting:
333 hintingFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000334 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000335 case SkPaint::kSlight_Hinting:
336 hintingFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000337 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000338 case SkPaint::kNormal_Hinting:
339 hintingFlags |= FT_LOAD_TARGET_NORMAL;
340 break;
341 case SkPaint::kFull_Hinting:
342 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
343 hintingFlags = FT_LOAD_TARGET_LCD;
344 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
345 hintingFlags = FT_LOAD_TARGET_LCD_V;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000346 break;
347 }
348
agl@chromium.org309485b2009-07-21 17:41:32 +0000349 fLoadGlyphFlags = hintingFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000350 }
351
352 // now create the FT_Size
353
354 {
355 FT_Error err;
356
357 err = FT_New_Size(fFace, &fFTSize);
358 if (err != 0) {
359 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
360 fFaceRec->fFontID, fScaleX, fScaleY, err));
361 fFace = NULL;
362 return;
363 }
364
365 err = FT_Activate_Size(fFTSize);
366 if (err != 0) {
367 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
368 fFaceRec->fFontID, fScaleX, fScaleY, err));
369 fFTSize = NULL;
370 }
371
372 err = FT_Set_Char_Size( fFace,
373 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
374 72, 72);
375 if (err != 0) {
376 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
377 fFaceRec->fFontID, fScaleX, fScaleY, err));
378 fFace = NULL;
379 return;
380 }
381
382 FT_Set_Transform( fFace, &fMatrix22, NULL);
383 }
384}
385
386SkScalerContext_FreeType::~SkScalerContext_FreeType() {
387 if (fFTSize != NULL) {
388 FT_Done_Size(fFTSize);
389 }
390
391 SkAutoMutexAcquire ac(gFTMutex);
392
393 if (fFace != NULL) {
394 unref_ft_face(fFace);
395 }
396 if (--gFTCount == 0) {
397// SkDEBUGF(("FT_Done_FreeType\n"));
398 FT_Done_FreeType(gFTLibrary);
399 SkDEBUGCODE(gFTLibrary = NULL;)
400 }
401}
402
403/* We call this before each use of the fFace, since we may be sharing
404 this face with other context (at different sizes).
405*/
406FT_Error SkScalerContext_FreeType::setupSize() {
407 /* In the off-chance that a font has been removed, we want to error out
408 right away, so call resolve just to be sure.
409
410 TODO: perhaps we can skip this, by walking the global font cache and
411 killing all of the contexts when we know that a given fontID is going
412 away...
413 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000414 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000415 return (FT_Error)-1;
416 }
417
418 FT_Error err = FT_Activate_Size(fFTSize);
419
420 if (err != 0) {
421 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
422 fFaceRec->fFontID, fScaleX, fScaleY, err));
423 fFTSize = NULL;
424 } else {
425 // seems we need to reset this every time (not sure why, but without it
426 // I get random italics from some other fFTSize)
427 FT_Set_Transform( fFace, &fMatrix22, NULL);
428 }
429 return err;
430}
431
432unsigned SkScalerContext_FreeType::generateGlyphCount() const {
433 return fFace->num_glyphs;
434}
435
436uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
437 return SkToU16(FT_Get_Char_Index( fFace, uni ));
438}
439
440static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
441 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000442 case SkMask::kHorizontalLCD_Format:
443 case SkMask::kVerticalLCD_Format:
444 SkASSERT(!"An LCD format should never be passed here");
445 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000446 case SkMask::kBW_Format:
447 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000448 case SkMask::kA8_Format:
449 default:
450 return FT_PIXEL_MODE_GRAY;
451 }
452}
453
reed@android.com8a1c16f2008-12-17 15:59:43 +0000454void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
455#ifdef FT_ADVANCES_H
456 /* unhinted and light hinted text have linearly scaled advances
457 * which are very cheap to compute with some font formats...
458 */
459 {
460 SkAutoMutexAcquire ac(gFTMutex);
461
462 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000463 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000464 return;
465 }
466
467 FT_Error error;
468 FT_Fixed advance;
469
470 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
471 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
472 &advance );
473 if (0 == error) {
474 glyph->fRsbDelta = 0;
475 glyph->fLsbDelta = 0;
476 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
477 glyph->fAdvanceY = 0;
478 return;
479 }
480 }
481#endif /* FT_ADVANCES_H */
482 /* otherwise, we need to load/hint the glyph, which is slower */
483 this->generateMetrics(glyph);
484 return;
485}
486
487void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
488 SkAutoMutexAcquire ac(gFTMutex);
489
490 glyph->fRsbDelta = 0;
491 glyph->fLsbDelta = 0;
492
493 FT_Error err;
494
495 if (this->setupSize()) {
496 goto ERROR;
497 }
498
499 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
500 if (err != 0) {
501 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
502 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
503 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000504 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000505 return;
506 }
507
508 switch ( fFace->glyph->format ) {
509 case FT_GLYPH_FORMAT_OUTLINE:
510 FT_BBox bbox;
511
512 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
513
agl@chromium.org309485b2009-07-21 17:41:32 +0000514 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000515 int dx = glyph->getSubXFixed() >> 10;
516 int dy = glyph->getSubYFixed() >> 10;
517 // negate dy since freetype-y-goes-up and skia-y-goes-down
518 bbox.xMin += dx;
519 bbox.yMin -= dy;
520 bbox.xMax += dx;
521 bbox.yMax -= dy;
522 }
523
524 bbox.xMin &= ~63;
525 bbox.yMin &= ~63;
526 bbox.xMax = (bbox.xMax + 63) & ~63;
527 bbox.yMax = (bbox.yMax + 63) & ~63;
528
529 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
530 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
531 glyph->fTop = -SkToS16(bbox.yMax >> 6);
532 glyph->fLeft = SkToS16(bbox.xMin >> 6);
533 break;
534
535 case FT_GLYPH_FORMAT_BITMAP:
536 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
537 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
538 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
539 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
540 break;
541
542 default:
543 SkASSERT(!"unknown glyph format");
544 goto ERROR;
545 }
546
agl@chromium.org309485b2009-07-21 17:41:32 +0000547 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000548 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
549 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
550 if (fRec.fFlags & kDevKernText_Flag) {
551 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
552 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
553 }
554 } else {
555 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
556 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
557 }
558
559#ifdef ENABLE_GLYPH_SPEW
560 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
561 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
562#endif
563}
564
reed@android.comf5493692009-07-22 19:21:01 +0000565#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000566namespace skia_freetype_support {
567// extern functions from SkFontHost_FreeType_Subpixel
568extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
569extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
570}
571
572using namespace skia_freetype_support;
573#endif
574
reed@android.com8a1c16f2008-12-17 15:59:43 +0000575void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
576 SkAutoMutexAcquire ac(gFTMutex);
577
578 FT_Error err;
579
580 if (this->setupSize()) {
581 goto ERROR;
582 }
583
584 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
585 if (err != 0) {
586 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
587 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
588 ERROR:
589 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
590 return;
591 }
592
agl@chromium.org309485b2009-07-21 17:41:32 +0000593 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
594 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
595
reed@android.com8a1c16f2008-12-17 15:59:43 +0000596 switch ( fFace->glyph->format ) {
597 case FT_GLYPH_FORMAT_OUTLINE: {
598 FT_Outline* outline = &fFace->glyph->outline;
599 FT_BBox bbox;
600 FT_Bitmap target;
601
602 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000603 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000604 dx = glyph.getSubXFixed() >> 10;
605 dy = glyph.getSubYFixed() >> 10;
606 // negate dy since freetype-y-goes-up and skia-y-goes-down
607 dy = -dy;
608 }
609 FT_Outline_Get_CBox(outline, &bbox);
610 /*
611 what we really want to do for subpixel is
612 offset(dx, dy)
613 compute_bounds
614 offset(bbox & !63)
615 but that is two calls to offset, so we do the following, which
616 achieves the same thing with only one offset call.
617 */
618 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
619 dy - ((bbox.yMin + dy) & ~63));
620
reed@android.comf5493692009-07-22 19:21:01 +0000621#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000622 if (lcdRenderMode) {
623 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
624 // we have to call FT_Render_Glyph and memcpy the image out.
625 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
626 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
627 FT_Render_Glyph(fFace->glyph, mode);
628
629 if (isVertical)
630 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
631 else
632 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
633
634 break;
635 }
636#endif
637
reed@android.com8a1c16f2008-12-17 15:59:43 +0000638 target.width = glyph.fWidth;
639 target.rows = glyph.fHeight;
640 target.pitch = glyph.rowBytes();
641 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
642 target.pixel_mode = compute_pixel_mode(
643 (SkMask::Format)fRec.fMaskFormat);
644 target.num_grays = 256;
645
646 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
647 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
648 } break;
649
650 case FT_GLYPH_FORMAT_BITMAP: {
651 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
652 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
653 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
654 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
655
656 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
657 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000658
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000659 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
660 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
661 unsigned dstRowBytes = glyph.rowBytes();
662 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
663 unsigned extraRowBytes = dstRowBytes - minRowBytes;
664
665 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
666 memcpy(dst, src, minRowBytes);
667 memset(dst + minRowBytes, 0, extraRowBytes);
668 src += srcRowBytes;
669 dst += dstRowBytes;
670 }
671 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
672 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
673 uint8_t byte = 0;
674 int bits = 0;
675 const uint8_t* src_row = src;
676 uint8_t* dst_row = dst;
677
678 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
679 if (!bits) {
680 byte = *src_row++;
681 bits = 8;
682 }
683
684 *dst_row++ = byte & 0x80 ? 0xff : 0;
685 bits--;
686 byte <<= 1;
687 }
688
689 src += fFace->glyph->bitmap.pitch;
690 dst += glyph.rowBytes();
691 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000692 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000693
694 if (lcdRenderMode)
695 glyph.expandA8ToLCD();
696
reed@android.com8a1c16f2008-12-17 15:59:43 +0000697 } break;
698
699 default:
700 SkASSERT(!"unknown glyph format");
701 goto ERROR;
702 }
703}
704
705///////////////////////////////////////////////////////////////////////////////
706
707#define ft2sk(x) SkFixedToScalar((x) << 10)
708
reed@android.com6f252972009-01-14 16:46:16 +0000709#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000710 #define CONST_PARAM const
711#else // older freetype doesn't use const here
712 #define CONST_PARAM
713#endif
714
715static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
716 SkPath* path = (SkPath*)ctx;
717 path->close(); // to close the previous contour (if any)
718 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
719 return 0;
720}
721
722static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
723 SkPath* path = (SkPath*)ctx;
724 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
725 return 0;
726}
727
728static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
729 void* ctx) {
730 SkPath* path = (SkPath*)ctx;
731 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
732 return 0;
733}
734
735static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
736 CONST_PARAM FT_Vector* pt2, void* ctx) {
737 SkPath* path = (SkPath*)ctx;
738 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
739 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
740 return 0;
741}
742
743void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
744 SkPath* path) {
745 SkAutoMutexAcquire ac(gFTMutex);
746
747 SkASSERT(&glyph && path);
748
749 if (this->setupSize()) {
750 path->reset();
751 return;
752 }
753
754 uint32_t flags = fLoadGlyphFlags;
755 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
756 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
757
758 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
759
760 if (err != 0) {
761 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
762 glyph.getGlyphID(fBaseGlyphCount), flags, err));
763 path->reset();
764 return;
765 }
766
767 FT_Outline_Funcs funcs;
768
769 funcs.move_to = move_proc;
770 funcs.line_to = line_proc;
771 funcs.conic_to = quad_proc;
772 funcs.cubic_to = cubic_proc;
773 funcs.shift = 0;
774 funcs.delta = 0;
775
776 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
777
778 if (err != 0) {
779 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
780 glyph.getGlyphID(fBaseGlyphCount), flags, err));
781 path->reset();
782 return;
783 }
784
785 path->close();
786}
787
788void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
789 SkPaint::FontMetrics* my) {
790 if (NULL == mx && NULL == my) {
791 return;
792 }
793
794 SkAutoMutexAcquire ac(gFTMutex);
795
796 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000797 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000798 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000799 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000800 }
801 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000802 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000803 }
804 return;
805 }
806
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000807 FT_Face face = fFace;
808 int upem = face->units_per_EM;
809 if (upem <= 0) {
810 goto ERROR;
811 }
812
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000813 SkPoint pts[6];
814 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000815 SkFixed scaleY = fScaleY;
816 SkFixed mxy = fMatrix22.xy;
817 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000818 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
819 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000820
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000821 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822 if (leading < 0) {
823 leading = 0;
824 }
825
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000826 // Try to get the OS/2 table from the font. This contains the specific
827 // average font width metrics which Windows uses.
828 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
829
reed@android.com8a1c16f2008-12-17 15:59:43 +0000830 ys[0] = -face->bbox.yMax;
831 ys[1] = -face->ascender;
832 ys[2] = -face->descender;
833 ys[3] = -face->bbox.yMin;
834 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000835 ys[5] = os2 ? os2->xAvgCharWidth : 0;
836
837 SkScalar x_height;
838 if (os2 && os2->sxHeight) {
839 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
840 } else {
841 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
842 if (x_glyph) {
843 FT_BBox bbox;
844 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
845 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
846 x_height = SkIntToScalar(bbox.yMax) / 64;
847 } else {
848 x_height = 0;
849 }
850 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000851
852 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000853 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000854 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
855 SkFixed x = SkFixedMul(mxy, y);
856 y = SkFixedMul(myy, y);
857 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
858 }
859
860 if (mx) {
861 mx->fTop = pts[0].fX;
862 mx->fAscent = pts[1].fX;
863 mx->fDescent = pts[2].fX;
864 mx->fBottom = pts[3].fX;
865 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000866 mx->fAvgCharWidth = pts[5].fX;
867 mx->fXMin = xmin;
868 mx->fXMax = xmax;
869 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000870 }
871 if (my) {
872 my->fTop = pts[0].fY;
873 my->fAscent = pts[1].fY;
874 my->fDescent = pts[2].fY;
875 my->fBottom = pts[3].fY;
876 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000877 my->fAvgCharWidth = pts[5].fY;
878 my->fXMin = xmin;
879 my->fXMax = xmax;
880 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000881 }
882}
883
884////////////////////////////////////////////////////////////////////////
885////////////////////////////////////////////////////////////////////////
886
887SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000888 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
889 if (!c->success()) {
890 SkDELETE(c);
891 c = NULL;
892 }
893 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000894}
895
896///////////////////////////////////////////////////////////////////////////////
897
898/* Export this so that other parts of our FonttHost port can make use of our
899 ability to extract the name+style from a stream, using FreeType's api.
900*/
901SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
902 FT_Library library;
agl@chromium.org309485b2009-07-21 17:41:32 +0000903 if (!InitFreetype()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000904 name->set(NULL);
905 return SkTypeface::kNormal;
906 }
907
908 FT_Open_Args args;
909 memset(&args, 0, sizeof(args));
910
911 const void* memoryBase = stream->getMemoryBase();
912 FT_StreamRec streamRec;
913
914 if (NULL != memoryBase) {
915 args.flags = FT_OPEN_MEMORY;
916 args.memory_base = (const FT_Byte*)memoryBase;
917 args.memory_size = stream->getLength();
918 } else {
919 memset(&streamRec, 0, sizeof(streamRec));
920 streamRec.size = stream->read(NULL, 0);
921 streamRec.descriptor.pointer = stream;
922 streamRec.read = sk_stream_read;
923 streamRec.close = sk_stream_close;
924
925 args.flags = FT_OPEN_STREAM;
926 args.stream = &streamRec;
927 }
928
929 FT_Face face;
930 if (FT_Open_Face(library, &args, 0, &face)) {
931 FT_Done_FreeType(library);
932 name->set(NULL);
933 return SkTypeface::kNormal;
934 }
935
936 name->set(face->family_name);
937 int style = SkTypeface::kNormal;
938
939 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
940 style |= SkTypeface::kBold;
941 }
942 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
943 style |= SkTypeface::kItalic;
944 }
945
946 FT_Done_Face(face);
947 FT_Done_FreeType(library);
948 return (SkTypeface::Style)style;
949}