blob: 253541bded8d0eb5793acec99d73b6ad7a5ea30c [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
reed@android.com36a4c2a2009-07-22 19:52:11 +0000265void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
266 // collapse full->normaling hinting if we're not doing LCD
267 SkPaint::Hinting h = rec->getHinting();
268 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
269 rec->setHinting(SkPaint::kNormal_Hinting);
270 }
271}
272
reed@android.com8a1c16f2008-12-17 15:59:43 +0000273SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000274 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000275 SkAutoMutexAcquire ac(gFTMutex);
276
reed@android.com8a1c16f2008-12-17 15:59:43 +0000277 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000278 if (!InitFreetype()) {
279 sk_throw();
280 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000281 }
282 ++gFTCount;
283
284 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000285 fFTSize = NULL;
286 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000287 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000288 if (NULL == fFaceRec) {
289 return;
290 }
291 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000292
293 // compute our factors from the record
294
295 SkMatrix m;
296
297 fRec.getSingleMatrix(&m);
298
299#ifdef DUMP_STRIKE_CREATION
300 SkString keyString;
301 SkFontHost::GetDescriptorKeyString(desc, &keyString);
302 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
303 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
304 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
305 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000306 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000307#endif
308
309 // now compute our scale factors
310 SkScalar sx = m.getScaleX();
311 SkScalar sy = m.getScaleY();
312
313 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
314 // sort of give up on hinting
315 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
316 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
317 sx = sy = SkScalarAve(sx, sy);
318
319 SkScalar inv = SkScalarInvert(sx);
320
321 // flip the skew elements to go from our Y-down system to FreeType's
322 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
323 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
324 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
325 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
326 } else {
327 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
328 fMatrix22.xy = fMatrix22.yx = 0;
329 }
330
331 fScaleX = SkScalarToFixed(sx);
332 fScaleY = SkScalarToFixed(sy);
333
334 // compute the flags we send to Load_Glyph
335 {
agl@chromium.org309485b2009-07-21 17:41:32 +0000336 FT_Int32 hintingFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000337
agl@chromium.org309485b2009-07-21 17:41:32 +0000338 switch (fRec.getHinting()) {
339 case SkPaint::kNo_Hinting:
340 hintingFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000341 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000342 case SkPaint::kSlight_Hinting:
343 hintingFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000344 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000345 case SkPaint::kNormal_Hinting:
346 hintingFlags |= FT_LOAD_TARGET_NORMAL;
347 break;
348 case SkPaint::kFull_Hinting:
349 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
350 hintingFlags = FT_LOAD_TARGET_LCD;
351 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
352 hintingFlags = FT_LOAD_TARGET_LCD_V;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000353 break;
354 }
355
agl@chromium.org309485b2009-07-21 17:41:32 +0000356 fLoadGlyphFlags = hintingFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000357 }
358
359 // now create the FT_Size
360
361 {
362 FT_Error err;
363
364 err = FT_New_Size(fFace, &fFTSize);
365 if (err != 0) {
366 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
367 fFaceRec->fFontID, fScaleX, fScaleY, err));
368 fFace = NULL;
369 return;
370 }
371
372 err = FT_Activate_Size(fFTSize);
373 if (err != 0) {
374 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
375 fFaceRec->fFontID, fScaleX, fScaleY, err));
376 fFTSize = NULL;
377 }
378
379 err = FT_Set_Char_Size( fFace,
380 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
381 72, 72);
382 if (err != 0) {
383 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
384 fFaceRec->fFontID, fScaleX, fScaleY, err));
385 fFace = NULL;
386 return;
387 }
388
389 FT_Set_Transform( fFace, &fMatrix22, NULL);
390 }
391}
392
393SkScalerContext_FreeType::~SkScalerContext_FreeType() {
394 if (fFTSize != NULL) {
395 FT_Done_Size(fFTSize);
396 }
397
398 SkAutoMutexAcquire ac(gFTMutex);
399
400 if (fFace != NULL) {
401 unref_ft_face(fFace);
402 }
403 if (--gFTCount == 0) {
404// SkDEBUGF(("FT_Done_FreeType\n"));
405 FT_Done_FreeType(gFTLibrary);
406 SkDEBUGCODE(gFTLibrary = NULL;)
407 }
408}
409
410/* We call this before each use of the fFace, since we may be sharing
411 this face with other context (at different sizes).
412*/
413FT_Error SkScalerContext_FreeType::setupSize() {
414 /* In the off-chance that a font has been removed, we want to error out
415 right away, so call resolve just to be sure.
416
417 TODO: perhaps we can skip this, by walking the global font cache and
418 killing all of the contexts when we know that a given fontID is going
419 away...
420 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000421 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000422 return (FT_Error)-1;
423 }
424
425 FT_Error err = FT_Activate_Size(fFTSize);
426
427 if (err != 0) {
428 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
429 fFaceRec->fFontID, fScaleX, fScaleY, err));
430 fFTSize = NULL;
431 } else {
432 // seems we need to reset this every time (not sure why, but without it
433 // I get random italics from some other fFTSize)
434 FT_Set_Transform( fFace, &fMatrix22, NULL);
435 }
436 return err;
437}
438
439unsigned SkScalerContext_FreeType::generateGlyphCount() const {
440 return fFace->num_glyphs;
441}
442
443uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
444 return SkToU16(FT_Get_Char_Index( fFace, uni ));
445}
446
447static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
448 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000449 case SkMask::kHorizontalLCD_Format:
450 case SkMask::kVerticalLCD_Format:
451 SkASSERT(!"An LCD format should never be passed here");
452 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000453 case SkMask::kBW_Format:
454 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000455 case SkMask::kA8_Format:
456 default:
457 return FT_PIXEL_MODE_GRAY;
458 }
459}
460
reed@android.com8a1c16f2008-12-17 15:59:43 +0000461void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
462#ifdef FT_ADVANCES_H
463 /* unhinted and light hinted text have linearly scaled advances
464 * which are very cheap to compute with some font formats...
465 */
466 {
467 SkAutoMutexAcquire ac(gFTMutex);
468
469 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000470 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000471 return;
472 }
473
474 FT_Error error;
475 FT_Fixed advance;
476
477 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
478 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
479 &advance );
480 if (0 == error) {
481 glyph->fRsbDelta = 0;
482 glyph->fLsbDelta = 0;
483 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
484 glyph->fAdvanceY = 0;
485 return;
486 }
487 }
488#endif /* FT_ADVANCES_H */
489 /* otherwise, we need to load/hint the glyph, which is slower */
490 this->generateMetrics(glyph);
491 return;
492}
493
494void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
495 SkAutoMutexAcquire ac(gFTMutex);
496
497 glyph->fRsbDelta = 0;
498 glyph->fLsbDelta = 0;
499
500 FT_Error err;
501
502 if (this->setupSize()) {
503 goto ERROR;
504 }
505
506 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
507 if (err != 0) {
508 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
509 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
510 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000511 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000512 return;
513 }
514
515 switch ( fFace->glyph->format ) {
516 case FT_GLYPH_FORMAT_OUTLINE:
517 FT_BBox bbox;
518
519 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
520
agl@chromium.org309485b2009-07-21 17:41:32 +0000521 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000522 int dx = glyph->getSubXFixed() >> 10;
523 int dy = glyph->getSubYFixed() >> 10;
524 // negate dy since freetype-y-goes-up and skia-y-goes-down
525 bbox.xMin += dx;
526 bbox.yMin -= dy;
527 bbox.xMax += dx;
528 bbox.yMax -= dy;
529 }
530
531 bbox.xMin &= ~63;
532 bbox.yMin &= ~63;
533 bbox.xMax = (bbox.xMax + 63) & ~63;
534 bbox.yMax = (bbox.yMax + 63) & ~63;
535
536 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
537 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
538 glyph->fTop = -SkToS16(bbox.yMax >> 6);
539 glyph->fLeft = SkToS16(bbox.xMin >> 6);
540 break;
541
542 case FT_GLYPH_FORMAT_BITMAP:
543 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
544 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
545 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
546 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
547 break;
548
549 default:
550 SkASSERT(!"unknown glyph format");
551 goto ERROR;
552 }
553
agl@chromium.org309485b2009-07-21 17:41:32 +0000554 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000555 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
556 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
557 if (fRec.fFlags & kDevKernText_Flag) {
558 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
559 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
560 }
561 } else {
562 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
563 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
564 }
565
566#ifdef ENABLE_GLYPH_SPEW
567 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
568 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
569#endif
570}
571
reed@android.comf5493692009-07-22 19:21:01 +0000572#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000573namespace skia_freetype_support {
574// extern functions from SkFontHost_FreeType_Subpixel
575extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
576extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
577}
578
579using namespace skia_freetype_support;
580#endif
581
reed@android.com8a1c16f2008-12-17 15:59:43 +0000582void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
583 SkAutoMutexAcquire ac(gFTMutex);
584
585 FT_Error err;
586
587 if (this->setupSize()) {
588 goto ERROR;
589 }
590
591 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
592 if (err != 0) {
593 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
594 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
595 ERROR:
596 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
597 return;
598 }
599
agl@chromium.org309485b2009-07-21 17:41:32 +0000600 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
601 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
602
reed@android.com8a1c16f2008-12-17 15:59:43 +0000603 switch ( fFace->glyph->format ) {
604 case FT_GLYPH_FORMAT_OUTLINE: {
605 FT_Outline* outline = &fFace->glyph->outline;
606 FT_BBox bbox;
607 FT_Bitmap target;
608
609 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000610 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000611 dx = glyph.getSubXFixed() >> 10;
612 dy = glyph.getSubYFixed() >> 10;
613 // negate dy since freetype-y-goes-up and skia-y-goes-down
614 dy = -dy;
615 }
616 FT_Outline_Get_CBox(outline, &bbox);
617 /*
618 what we really want to do for subpixel is
619 offset(dx, dy)
620 compute_bounds
621 offset(bbox & !63)
622 but that is two calls to offset, so we do the following, which
623 achieves the same thing with only one offset call.
624 */
625 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
626 dy - ((bbox.yMin + dy) & ~63));
627
reed@android.comf5493692009-07-22 19:21:01 +0000628#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000629 if (lcdRenderMode) {
630 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
631 // we have to call FT_Render_Glyph and memcpy the image out.
632 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
633 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
634 FT_Render_Glyph(fFace->glyph, mode);
635
636 if (isVertical)
637 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
638 else
639 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
640
641 break;
642 }
643#endif
644
reed@android.com8a1c16f2008-12-17 15:59:43 +0000645 target.width = glyph.fWidth;
646 target.rows = glyph.fHeight;
647 target.pitch = glyph.rowBytes();
648 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
649 target.pixel_mode = compute_pixel_mode(
650 (SkMask::Format)fRec.fMaskFormat);
651 target.num_grays = 256;
652
653 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
654 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
655 } break;
656
657 case FT_GLYPH_FORMAT_BITMAP: {
658 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
659 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
660 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
661 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
662
663 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
664 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000665
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000666 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
667 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
668 unsigned dstRowBytes = glyph.rowBytes();
669 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
670 unsigned extraRowBytes = dstRowBytes - minRowBytes;
671
672 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
673 memcpy(dst, src, minRowBytes);
674 memset(dst + minRowBytes, 0, extraRowBytes);
675 src += srcRowBytes;
676 dst += dstRowBytes;
677 }
678 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
679 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
680 uint8_t byte = 0;
681 int bits = 0;
682 const uint8_t* src_row = src;
683 uint8_t* dst_row = dst;
684
685 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
686 if (!bits) {
687 byte = *src_row++;
688 bits = 8;
689 }
690
691 *dst_row++ = byte & 0x80 ? 0xff : 0;
692 bits--;
693 byte <<= 1;
694 }
695
696 src += fFace->glyph->bitmap.pitch;
697 dst += glyph.rowBytes();
698 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000699 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000700
701 if (lcdRenderMode)
702 glyph.expandA8ToLCD();
703
reed@android.com8a1c16f2008-12-17 15:59:43 +0000704 } break;
705
706 default:
707 SkASSERT(!"unknown glyph format");
708 goto ERROR;
709 }
710}
711
712///////////////////////////////////////////////////////////////////////////////
713
714#define ft2sk(x) SkFixedToScalar((x) << 10)
715
reed@android.com6f252972009-01-14 16:46:16 +0000716#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000717 #define CONST_PARAM const
718#else // older freetype doesn't use const here
719 #define CONST_PARAM
720#endif
721
722static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
723 SkPath* path = (SkPath*)ctx;
724 path->close(); // to close the previous contour (if any)
725 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
726 return 0;
727}
728
729static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
730 SkPath* path = (SkPath*)ctx;
731 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
732 return 0;
733}
734
735static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
736 void* ctx) {
737 SkPath* path = (SkPath*)ctx;
738 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
739 return 0;
740}
741
742static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
743 CONST_PARAM FT_Vector* pt2, void* ctx) {
744 SkPath* path = (SkPath*)ctx;
745 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
746 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
747 return 0;
748}
749
750void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
751 SkPath* path) {
752 SkAutoMutexAcquire ac(gFTMutex);
753
754 SkASSERT(&glyph && path);
755
756 if (this->setupSize()) {
757 path->reset();
758 return;
759 }
760
761 uint32_t flags = fLoadGlyphFlags;
762 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
763 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
764
765 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
766
767 if (err != 0) {
768 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
769 glyph.getGlyphID(fBaseGlyphCount), flags, err));
770 path->reset();
771 return;
772 }
773
774 FT_Outline_Funcs funcs;
775
776 funcs.move_to = move_proc;
777 funcs.line_to = line_proc;
778 funcs.conic_to = quad_proc;
779 funcs.cubic_to = cubic_proc;
780 funcs.shift = 0;
781 funcs.delta = 0;
782
783 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
784
785 if (err != 0) {
786 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
787 glyph.getGlyphID(fBaseGlyphCount), flags, err));
788 path->reset();
789 return;
790 }
791
792 path->close();
793}
794
795void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
796 SkPaint::FontMetrics* my) {
797 if (NULL == mx && NULL == my) {
798 return;
799 }
800
801 SkAutoMutexAcquire ac(gFTMutex);
802
803 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000804 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000805 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000806 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000807 }
808 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000809 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000810 }
811 return;
812 }
813
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000814 FT_Face face = fFace;
815 int upem = face->units_per_EM;
816 if (upem <= 0) {
817 goto ERROR;
818 }
819
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000820 SkPoint pts[6];
821 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822 SkFixed scaleY = fScaleY;
823 SkFixed mxy = fMatrix22.xy;
824 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000825 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
826 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000827
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000828 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000829 if (leading < 0) {
830 leading = 0;
831 }
832
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000833 // Try to get the OS/2 table from the font. This contains the specific
834 // average font width metrics which Windows uses.
835 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
836
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837 ys[0] = -face->bbox.yMax;
838 ys[1] = -face->ascender;
839 ys[2] = -face->descender;
840 ys[3] = -face->bbox.yMin;
841 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000842 ys[5] = os2 ? os2->xAvgCharWidth : 0;
843
844 SkScalar x_height;
845 if (os2 && os2->sxHeight) {
846 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
847 } else {
848 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
849 if (x_glyph) {
850 FT_BBox bbox;
851 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
852 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
853 x_height = SkIntToScalar(bbox.yMax) / 64;
854 } else {
855 x_height = 0;
856 }
857 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000858
859 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000860 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000861 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
862 SkFixed x = SkFixedMul(mxy, y);
863 y = SkFixedMul(myy, y);
864 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
865 }
866
867 if (mx) {
868 mx->fTop = pts[0].fX;
869 mx->fAscent = pts[1].fX;
870 mx->fDescent = pts[2].fX;
871 mx->fBottom = pts[3].fX;
872 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000873 mx->fAvgCharWidth = pts[5].fX;
874 mx->fXMin = xmin;
875 mx->fXMax = xmax;
876 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000877 }
878 if (my) {
879 my->fTop = pts[0].fY;
880 my->fAscent = pts[1].fY;
881 my->fDescent = pts[2].fY;
882 my->fBottom = pts[3].fY;
883 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000884 my->fAvgCharWidth = pts[5].fY;
885 my->fXMin = xmin;
886 my->fXMax = xmax;
887 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000888 }
889}
890
891////////////////////////////////////////////////////////////////////////
892////////////////////////////////////////////////////////////////////////
893
894SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000895 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
896 if (!c->success()) {
897 SkDELETE(c);
898 c = NULL;
899 }
900 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000901}
902
903///////////////////////////////////////////////////////////////////////////////
904
905/* Export this so that other parts of our FonttHost port can make use of our
906 ability to extract the name+style from a stream, using FreeType's api.
907*/
908SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
909 FT_Library library;
agl@chromium.org309485b2009-07-21 17:41:32 +0000910 if (!InitFreetype()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000911 name->set(NULL);
912 return SkTypeface::kNormal;
913 }
914
915 FT_Open_Args args;
916 memset(&args, 0, sizeof(args));
917
918 const void* memoryBase = stream->getMemoryBase();
919 FT_StreamRec streamRec;
920
921 if (NULL != memoryBase) {
922 args.flags = FT_OPEN_MEMORY;
923 args.memory_base = (const FT_Byte*)memoryBase;
924 args.memory_size = stream->getLength();
925 } else {
926 memset(&streamRec, 0, sizeof(streamRec));
927 streamRec.size = stream->read(NULL, 0);
928 streamRec.descriptor.pointer = stream;
929 streamRec.read = sk_stream_read;
930 streamRec.close = sk_stream_close;
931
932 args.flags = FT_OPEN_STREAM;
933 args.stream = &streamRec;
934 }
935
936 FT_Face face;
937 if (FT_Open_Face(library, &args, 0, &face)) {
938 FT_Done_FreeType(library);
939 name->set(NULL);
940 return SkTypeface::kNormal;
941 }
942
943 name->set(face->family_name);
944 int style = SkTypeface::kNormal;
945
946 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
947 style |= SkTypeface::kBold;
948 }
949 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
950 style |= SkTypeface::kItalic;
951 }
952
953 FT_Done_Face(face);
954 FT_Done_FreeType(library);
955 return (SkTypeface::Style)style;
956}