1 /* 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
18 #include "SkColorPriv.h"
19 #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
35 #include FT_TRUETYPE_TABLES_H
36
37 #if defined(SK_SUPPORT_LCDTEXT)
38 #include FT_LCD_FILTER_H
39 #endif
40
41 #ifdef FT_ADVANCES_H
42 #include FT_ADVANCES_H
43 #endif
44
45 #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>
52 #include <freetype/ftlcdfil.h>
53 #endif
54
55 //#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
70 struct SkFaceRec;
71
72 static SkMutex gFTMutex;
73 static int gFTCount;
74 static FT_Library gFTLibrary;
75 static SkFaceRec* gFaceRecHead;
76 static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
77 static bool gLCDSupport; // true iff LCD is supported by the runtime.
78
79 /////////////////////////////////////////////////////////////////////////
80
81 static bool
InitFreetype()82 InitFreetype() {
83 FT_Error err = FT_Init_FreeType(&gFTLibrary);
84 if (err)
85 return false;
86
87 #if defined(SK_SUPPORT_LCDTEXT)
88 // Setup LCD filtering. This reduces colour fringes for LCD rendered
89 // glyphs.
90 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
91 gLCDSupport = err == 0;
92 #endif
93 gLCDSupportValid = true;
94
95 return true;
96 }
97
98 class SkScalerContext_FreeType : public SkScalerContext {
99 public:
100 SkScalerContext_FreeType(const SkDescriptor* desc);
101 virtual ~SkScalerContext_FreeType();
102
success() const103 bool success() const {
104 return fFaceRec != NULL &&
105 fFTSize != NULL &&
106 fFace != NULL;
107 }
108
109 protected:
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
119 private:
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
135 struct SkFaceRec {
136 SkFaceRec* fNext;
137 FT_Face fFace;
138 FT_StreamRec fFTStream;
139 SkStream* fSkStream;
140 uint32_t fRefCnt;
141 uint32_t fFontID;
142
143 // assumes ownership of the stream, will call unref() when its done
144 SkFaceRec(SkStream* strm, uint32_t fontID);
~SkFaceRecSkFaceRec145 ~SkFaceRec() {
146 fSkStream->unref();
147 }
148 };
149
150 extern "C" {
sk_stream_read(FT_Stream stream,unsigned long offset,unsigned char * buffer,unsigned long count)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
sk_stream_close(FT_Stream stream)178 static void sk_stream_close( FT_Stream stream) {}
179 }
180
SkFaceRec(SkStream * strm,uint32_t fontID)181 SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
182 : fSkStream(strm), fFontID(fontID) {
183 // SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
184
185 sk_bzero(&fFTStream, sizeof(fFTStream));
186 fFTStream.size = fSkStream->getLength();
187 fFTStream.descriptor.pointer = fSkStream;
188 fFTStream.read = sk_stream_read;
189 fFTStream.close = sk_stream_close;
190 }
191
192 // Will return 0 on failure
ref_ft_face(uint32_t fontID)193 static 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));
207 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);
233 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
unref_ft_face(FT_Face face)244 static 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
FilterRec(SkScalerContext::Rec * rec)269 void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
270 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
281 SkPaint::Hinting h = rec->getHinting();
282 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
283 // 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;
288 }
289 rec->setHinting(h);
290 }
291
SkScalerContext_FreeType(const SkDescriptor * desc)292 SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
293 : SkScalerContext(desc) {
294 SkAutoMutexAcquire ac(gFTMutex);
295
296 if (gFTCount == 0) {
297 if (!InitFreetype()) {
298 sk_throw();
299 }
300 }
301 ++gFTCount;
302
303 // load the font file
304 fFTSize = NULL;
305 fFace = NULL;
306 fFaceRec = ref_ft_face(fRec.fFontID);
307 if (NULL == fFaceRec) {
308 return;
309 }
310 fFace = fFaceRec->fFace;
311
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]),
325 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
326 #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 {
355 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
356
357 switch (fRec.getHinting()) {
358 case SkPaint::kNo_Hinting:
359 loadFlags = FT_LOAD_NO_HINTING;
360 break;
361 case SkPaint::kSlight_Hinting:
362 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
363 break;
364 case SkPaint::kNormal_Hinting:
365 loadFlags = FT_LOAD_TARGET_NORMAL;
366 break;
367 case SkPaint::kFull_Hinting:
368 loadFlags = FT_LOAD_TARGET_NORMAL;
369 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
370 loadFlags = FT_LOAD_TARGET_LCD;
371 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
372 loadFlags = FT_LOAD_TARGET_LCD_V;
373 break;
374 default:
375 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
376 break;
377 }
378
379 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
386 fLoadGlyphFlags = loadFlags;
387 }
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
~SkScalerContext_FreeType()423 SkScalerContext_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 */
setupSize()443 FT_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 */
451 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
452 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
generateGlyphCount() const469 unsigned SkScalerContext_FreeType::generateGlyphCount() const {
470 return fFace->num_glyphs;
471 }
472
generateCharToGlyph(SkUnichar uni)473 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
474 return SkToU16(FT_Get_Char_Index( fFace, uni ));
475 }
476
compute_pixel_mode(SkMask::Format format)477 static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
478 switch (format) {
479 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;
483 case SkMask::kBW_Format:
484 return FT_PIXEL_MODE_MONO;
485 case SkMask::kA8_Format:
486 default:
487 return FT_PIXEL_MODE_GRAY;
488 }
489 }
490
generateAdvance(SkGlyph * glyph)491 void 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()) {
500 glyph->zeroMetrics();
501 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
generateMetrics(SkGlyph * glyph)524 void 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:
541 glyph->zeroMetrics();
542 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
551 if (fRec.fSubpixelPositioning) {
552 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
584 if (!fRec.fSubpixelPositioning) {
585 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
602 #if defined(SK_SUPPORT_LCDTEXT)
603 namespace skia_freetype_support {
604 // extern functions from SkFontHost_FreeType_Subpixel
605 extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
606 extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
607 }
608
609 using namespace skia_freetype_support;
610 #endif
611
generateImage(const SkGlyph & glyph)612 void 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
630 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
631 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
632
633 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;
640 if (fRec.fSubpixelPositioning) {
641 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
658 #if defined(SK_SUPPORT_LCDTEXT)
659 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
675 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;
695
696 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
697 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
698 glyph.fMaskFormat == SkMask::kBW_Format)) {
699 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
700 unsigned dstRowBytes = glyph.rowBytes();
701 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
702 unsigned extraRowBytes = dstRowBytes - minRowBytes;
703
704 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
705 memcpy(dst, src, minRowBytes);
706 memset(dst + minRowBytes, 0, extraRowBytes);
707 src += srcRowBytes;
708 dst += dstRowBytes;
709 }
710 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
711 glyph.fMaskFormat == SkMask::kA8_Format) {
712 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
713 uint8_t byte = 0;
714 int bits = 0;
715 const uint8_t* src_row = src;
716 uint8_t* dst_row = dst;
717
718 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
719 if (!bits) {
720 byte = *src_row++;
721 bits = 8;
722 }
723
724 *dst_row++ = byte & 0x80 ? 0xff : 0;
725 bits--;
726 byte <<= 1;
727 }
728
729 src += fFace->glyph->bitmap.pitch;
730 dst += glyph.rowBytes();
731 }
732 } else {
733 SkASSERT(!"unknown glyph bitmap transform needed");
734 }
735
736 if (lcdRenderMode)
737 glyph.expandA8ToLCD();
738
739 } break;
740
741 default:
742 SkASSERT(!"unknown glyph format");
743 goto ERROR;
744 }
745 }
746
747 ///////////////////////////////////////////////////////////////////////////////
748
749 #define ft2sk(x) SkFixedToScalar((x) << 10)
750
751 #if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
752 #define CONST_PARAM const
753 #else // older freetype doesn't use const here
754 #define CONST_PARAM
755 #endif
756
move_proc(CONST_PARAM FT_Vector * pt,void * ctx)757 static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
758 SkPath* path = (SkPath*)ctx;
759 path->close(); // to close the previous contour (if any)
760 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
761 return 0;
762 }
763
line_proc(CONST_PARAM FT_Vector * pt,void * ctx)764 static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
765 SkPath* path = (SkPath*)ctx;
766 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
767 return 0;
768 }
769
quad_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,void * ctx)770 static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
771 void* ctx) {
772 SkPath* path = (SkPath*)ctx;
773 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
774 return 0;
775 }
776
cubic_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,CONST_PARAM FT_Vector * pt2,void * ctx)777 static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
778 CONST_PARAM FT_Vector* pt2, void* ctx) {
779 SkPath* path = (SkPath*)ctx;
780 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
781 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
782 return 0;
783 }
784
generatePath(const SkGlyph & glyph,SkPath * path)785 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
786 SkPath* path) {
787 SkAutoMutexAcquire ac(gFTMutex);
788
789 SkASSERT(&glyph && path);
790
791 if (this->setupSize()) {
792 path->reset();
793 return;
794 }
795
796 uint32_t flags = fLoadGlyphFlags;
797 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
798 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
799
800 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
801
802 if (err != 0) {
803 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
804 glyph.getGlyphID(fBaseGlyphCount), flags, err));
805 path->reset();
806 return;
807 }
808
809 FT_Outline_Funcs funcs;
810
811 funcs.move_to = move_proc;
812 funcs.line_to = line_proc;
813 funcs.conic_to = quad_proc;
814 funcs.cubic_to = cubic_proc;
815 funcs.shift = 0;
816 funcs.delta = 0;
817
818 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
819
820 if (err != 0) {
821 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
822 glyph.getGlyphID(fBaseGlyphCount), flags, err));
823 path->reset();
824 return;
825 }
826
827 path->close();
828 }
829
generateFontMetrics(SkPaint::FontMetrics * mx,SkPaint::FontMetrics * my)830 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
831 SkPaint::FontMetrics* my) {
832 if (NULL == mx && NULL == my) {
833 return;
834 }
835
836 SkAutoMutexAcquire ac(gFTMutex);
837
838 if (this->setupSize()) {
839 ERROR:
840 if (mx) {
841 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
842 }
843 if (my) {
844 sk_bzero(my, sizeof(SkPaint::FontMetrics));
845 }
846 return;
847 }
848
849 FT_Face face = fFace;
850 int upem = face->units_per_EM;
851 if (upem <= 0) {
852 goto ERROR;
853 }
854
855 SkPoint pts[6];
856 SkFixed ys[6];
857 SkFixed scaleY = fScaleY;
858 SkFixed mxy = fMatrix22.xy;
859 SkFixed myy = fMatrix22.yy;
860 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
861 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
862
863 int leading = face->height - (face->ascender + -face->descender);
864 if (leading < 0) {
865 leading = 0;
866 }
867
868 // Try to get the OS/2 table from the font. This contains the specific
869 // average font width metrics which Windows uses.
870 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
871
872 ys[0] = -face->bbox.yMax;
873 ys[1] = -face->ascender;
874 ys[2] = -face->descender;
875 ys[3] = -face->bbox.yMin;
876 ys[4] = leading;
877 ys[5] = os2 ? os2->xAvgCharWidth : 0;
878
879 SkScalar x_height;
880 if (os2 && os2->sxHeight) {
881 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
882 } else {
883 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
884 if (x_glyph) {
885 FT_BBox bbox;
886 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
887 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
888 x_height = SkIntToScalar(bbox.yMax) / 64;
889 } else {
890 x_height = 0;
891 }
892 }
893
894 // convert upem-y values into scalar points
895 for (int i = 0; i < 6; i++) {
896 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
897 SkFixed x = SkFixedMul(mxy, y);
898 y = SkFixedMul(myy, y);
899 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
900 }
901
902 if (mx) {
903 mx->fTop = pts[0].fX;
904 mx->fAscent = pts[1].fX;
905 mx->fDescent = pts[2].fX;
906 mx->fBottom = pts[3].fX;
907 mx->fLeading = pts[4].fX;
908 mx->fAvgCharWidth = pts[5].fX;
909 mx->fXMin = xmin;
910 mx->fXMax = xmax;
911 mx->fXHeight = x_height;
912 }
913 if (my) {
914 my->fTop = pts[0].fY;
915 my->fAscent = pts[1].fY;
916 my->fDescent = pts[2].fY;
917 my->fBottom = pts[3].fY;
918 my->fLeading = pts[4].fY;
919 my->fAvgCharWidth = pts[5].fY;
920 my->fXMin = xmin;
921 my->fXMax = xmax;
922 my->fXHeight = x_height;
923 }
924 }
925
926 ////////////////////////////////////////////////////////////////////////
927 ////////////////////////////////////////////////////////////////////////
928
CreateScalerContext(const SkDescriptor * desc)929 SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
930 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
931 if (!c->success()) {
932 SkDELETE(c);
933 c = NULL;
934 }
935 return c;
936 }
937
938 ///////////////////////////////////////////////////////////////////////////////
939
940 /* Export this so that other parts of our FonttHost port can make use of our
941 ability to extract the name+style from a stream, using FreeType's api.
942 */
find_name_and_style(SkStream * stream,SkString * name)943 SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
944 FT_Library library;
945 if (FT_Init_FreeType(&library)) {
946 name->set(NULL);
947 return SkTypeface::kNormal;
948 }
949
950 FT_Open_Args args;
951 memset(&args, 0, sizeof(args));
952
953 const void* memoryBase = stream->getMemoryBase();
954 FT_StreamRec streamRec;
955
956 if (NULL != memoryBase) {
957 args.flags = FT_OPEN_MEMORY;
958 args.memory_base = (const FT_Byte*)memoryBase;
959 args.memory_size = stream->getLength();
960 } else {
961 memset(&streamRec, 0, sizeof(streamRec));
962 streamRec.size = stream->read(NULL, 0);
963 streamRec.descriptor.pointer = stream;
964 streamRec.read = sk_stream_read;
965 streamRec.close = sk_stream_close;
966
967 args.flags = FT_OPEN_STREAM;
968 args.stream = &streamRec;
969 }
970
971 FT_Face face;
972 if (FT_Open_Face(library, &args, 0, &face)) {
973 FT_Done_FreeType(library);
974 name->set(NULL);
975 return SkTypeface::kNormal;
976 }
977
978 name->set(face->family_name);
979 int style = SkTypeface::kNormal;
980
981 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
982 style |= SkTypeface::kBold;
983 }
984 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
985 style |= SkTypeface::kItalic;
986 }
987
988 FT_Done_Face(face);
989 FT_Done_FreeType(library);
990 return (SkTypeface::Style)style;
991 }
992