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 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
119
120 private:
121 SkFaceRec* fFaceRec;
122 FT_Face fFace; // reference to shared face in gFaceRecHead
123 FT_Size fFTSize; // our own copy
124 SkFixed fScaleX, fScaleY;
125 FT_Matrix fMatrix22;
126 uint32_t fLoadGlyphFlags;
127
128 FT_Error setupSize();
129 void emboldenOutline(FT_Outline* outline);
130 };
131
132 ///////////////////////////////////////////////////////////////////////////
133 ///////////////////////////////////////////////////////////////////////////
134
135 #include "SkStream.h"
136
137 struct SkFaceRec {
138 SkFaceRec* fNext;
139 FT_Face fFace;
140 FT_StreamRec fFTStream;
141 SkStream* fSkStream;
142 uint32_t fRefCnt;
143 uint32_t fFontID;
144
145 // assumes ownership of the stream, will call unref() when its done
146 SkFaceRec(SkStream* strm, uint32_t fontID);
~SkFaceRecSkFaceRec147 ~SkFaceRec() {
148 fSkStream->unref();
149 }
150 };
151
152 extern "C" {
sk_stream_read(FT_Stream stream,unsigned long offset,unsigned char * buffer,unsigned long count)153 static unsigned long sk_stream_read(FT_Stream stream,
154 unsigned long offset,
155 unsigned char* buffer,
156 unsigned long count ) {
157 SkStream* str = (SkStream*)stream->descriptor.pointer;
158
159 if (count) {
160 if (!str->rewind()) {
161 return 0;
162 } else {
163 unsigned long ret;
164 if (offset) {
165 ret = str->read(NULL, offset);
166 if (ret != offset) {
167 return 0;
168 }
169 }
170 ret = str->read(buffer, count);
171 if (ret != count) {
172 return 0;
173 }
174 count = ret;
175 }
176 }
177 return count;
178 }
179
sk_stream_close(FT_Stream stream)180 static void sk_stream_close( FT_Stream stream) {}
181 }
182
SkFaceRec(SkStream * strm,uint32_t fontID)183 SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
184 : fSkStream(strm), fFontID(fontID) {
185 // SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
186
187 sk_bzero(&fFTStream, sizeof(fFTStream));
188 fFTStream.size = fSkStream->getLength();
189 fFTStream.descriptor.pointer = fSkStream;
190 fFTStream.read = sk_stream_read;
191 fFTStream.close = sk_stream_close;
192 }
193
194 // Will return 0 on failure
ref_ft_face(uint32_t fontID)195 static SkFaceRec* ref_ft_face(uint32_t fontID) {
196 SkFaceRec* rec = gFaceRecHead;
197 while (rec) {
198 if (rec->fFontID == fontID) {
199 SkASSERT(rec->fFace);
200 rec->fRefCnt += 1;
201 return rec;
202 }
203 rec = rec->fNext;
204 }
205
206 SkStream* strm = SkFontHost::OpenStream(fontID);
207 if (NULL == strm) {
208 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
209 return 0;
210 }
211
212 // this passes ownership of strm to the rec
213 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
214
215 FT_Open_Args args;
216 memset(&args, 0, sizeof(args));
217 const void* memoryBase = strm->getMemoryBase();
218
219 if (NULL != memoryBase) {
220 //printf("mmap(%s)\n", keyString.c_str());
221 args.flags = FT_OPEN_MEMORY;
222 args.memory_base = (const FT_Byte*)memoryBase;
223 args.memory_size = strm->getLength();
224 } else {
225 //printf("fopen(%s)\n", keyString.c_str());
226 args.flags = FT_OPEN_STREAM;
227 args.stream = &rec->fFTStream;
228 }
229
230 if (gFTCount == 0) {
231 if (!InitFreetype()) {
232 return 0;
233 }
234 }
235 ++gFTCount;
236
237 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
238
239 if (err) { // bad filename, try the default font
240 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
241 SkDELETE(rec);
242 return 0;
243 } else {
244 SkASSERT(rec->fFace);
245 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
246 rec->fNext = gFaceRecHead;
247 gFaceRecHead = rec;
248 rec->fRefCnt = 1;
249 return rec;
250 }
251 }
252
unref_ft_face(FT_Face face)253 static void unref_ft_face(FT_Face face) {
254 SkFaceRec* rec = gFaceRecHead;
255 SkFaceRec* prev = NULL;
256 while (rec) {
257 SkFaceRec* next = rec->fNext;
258 if (rec->fFace == face) {
259 if (--rec->fRefCnt == 0) {
260 if (prev) {
261 prev->fNext = next;
262 } else {
263 gFaceRecHead = next;
264 }
265 FT_Done_Face(face);
266 SkDELETE(rec);
267
268 if (--gFTCount == 0) {
269 FT_Done_FreeType(gFTLibrary);
270 }
271 }
272 return;
273 }
274 prev = rec;
275 rec = next;
276 }
277 SkASSERT("shouldn't get here, face not in list");
278 }
279
280 ///////////////////////////////////////////////////////////////////////////
281
FilterRec(SkScalerContext::Rec * rec)282 void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
283 if (!gLCDSupportValid) {
284 InitFreetype();
285 FT_Done_FreeType(gFTLibrary);
286 }
287
288 if (!gLCDSupport && rec->isLCD()) {
289 // If the runtime Freetype library doesn't support LCD mode, we disable
290 // it here.
291 rec->fMaskFormat = SkMask::kA8_Format;
292 }
293
294 SkPaint::Hinting h = rec->getHinting();
295 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
296 // collapse full->normal hinting if we're not doing LCD
297 h = SkPaint::kNormal_Hinting;
298 } else if (rec->fSubpixelPositioning && SkPaint::kNo_Hinting != h) {
299 // to do subpixel, we must have at most slight hinting
300 h = SkPaint::kSlight_Hinting;
301 }
302 rec->setHinting(h);
303 }
304
GetUnitsPerEm(SkFontID fontID)305 uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
306 SkAutoMutexAcquire ac(gFTMutex);
307 SkFaceRec *rec = ref_ft_face(fontID);
308 uint16_t unitsPerEm = 0;
309
310 if (rec != NULL && rec->fFace != NULL) {
311 unitsPerEm = rec->fFace->units_per_EM;
312 unref_ft_face(rec->fFace);
313 }
314
315 return (uint32_t)unitsPerEm;
316 }
317
SkScalerContext_FreeType(const SkDescriptor * desc)318 SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
319 : SkScalerContext(desc) {
320 SkAutoMutexAcquire ac(gFTMutex);
321
322 if (gFTCount == 0) {
323 if (!InitFreetype()) {
324 sk_throw();
325 }
326 }
327 ++gFTCount;
328
329 // load the font file
330 fFTSize = NULL;
331 fFace = NULL;
332 fFaceRec = ref_ft_face(fRec.fFontID);
333 if (NULL == fFaceRec) {
334 return;
335 }
336 fFace = fFaceRec->fFace;
337
338 // compute our factors from the record
339
340 SkMatrix m;
341
342 fRec.getSingleMatrix(&m);
343
344 #ifdef DUMP_STRIKE_CREATION
345 SkString keyString;
346 SkFontHost::GetDescriptorKeyString(desc, &keyString);
347 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
348 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
349 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
350 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
351 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
352 #endif
353
354 // now compute our scale factors
355 SkScalar sx = m.getScaleX();
356 SkScalar sy = m.getScaleY();
357
358 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
359 // sort of give up on hinting
360 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
361 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
362 sx = sy = SkScalarAve(sx, sy);
363
364 SkScalar inv = SkScalarInvert(sx);
365
366 // flip the skew elements to go from our Y-down system to FreeType's
367 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
368 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
369 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
370 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
371 } else {
372 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
373 fMatrix22.xy = fMatrix22.yx = 0;
374 }
375
376 fScaleX = SkScalarToFixed(sx);
377 fScaleY = SkScalarToFixed(sy);
378
379 // compute the flags we send to Load_Glyph
380 {
381 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
382
383 switch (fRec.getHinting()) {
384 case SkPaint::kNo_Hinting:
385 loadFlags = FT_LOAD_NO_HINTING;
386 break;
387 case SkPaint::kSlight_Hinting:
388 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
389 break;
390 case SkPaint::kNormal_Hinting:
391 loadFlags = FT_LOAD_TARGET_NORMAL;
392 break;
393 case SkPaint::kFull_Hinting:
394 loadFlags = FT_LOAD_TARGET_NORMAL;
395 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
396 loadFlags = FT_LOAD_TARGET_LCD;
397 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
398 loadFlags = FT_LOAD_TARGET_LCD_V;
399 break;
400 default:
401 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
402 break;
403 }
404
405 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
406 loadFlags |= FT_LOAD_NO_BITMAP;
407
408 fLoadGlyphFlags = loadFlags;
409 }
410
411 // now create the FT_Size
412
413 {
414 FT_Error err;
415
416 err = FT_New_Size(fFace, &fFTSize);
417 if (err != 0) {
418 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
419 fFaceRec->fFontID, fScaleX, fScaleY, err));
420 fFace = NULL;
421 return;
422 }
423
424 err = FT_Activate_Size(fFTSize);
425 if (err != 0) {
426 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
427 fFaceRec->fFontID, fScaleX, fScaleY, err));
428 fFTSize = NULL;
429 }
430
431 err = FT_Set_Char_Size( fFace,
432 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
433 72, 72);
434 if (err != 0) {
435 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
436 fFaceRec->fFontID, fScaleX, fScaleY, err));
437 fFace = NULL;
438 return;
439 }
440
441 FT_Set_Transform( fFace, &fMatrix22, NULL);
442 }
443 }
444
~SkScalerContext_FreeType()445 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
446 if (fFTSize != NULL) {
447 FT_Done_Size(fFTSize);
448 }
449
450 SkAutoMutexAcquire ac(gFTMutex);
451
452 if (fFace != NULL) {
453 unref_ft_face(fFace);
454 }
455 if (--gFTCount == 0) {
456 // SkDEBUGF(("FT_Done_FreeType\n"));
457 FT_Done_FreeType(gFTLibrary);
458 SkDEBUGCODE(gFTLibrary = NULL;)
459 }
460 }
461
462 /* We call this before each use of the fFace, since we may be sharing
463 this face with other context (at different sizes).
464 */
setupSize()465 FT_Error SkScalerContext_FreeType::setupSize() {
466 /* In the off-chance that a font has been removed, we want to error out
467 right away, so call resolve just to be sure.
468
469 TODO: perhaps we can skip this, by walking the global font cache and
470 killing all of the contexts when we know that a given fontID is going
471 away...
472 */
473 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
474 return (FT_Error)-1;
475 }
476
477 FT_Error err = FT_Activate_Size(fFTSize);
478
479 if (err != 0) {
480 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
481 fFaceRec->fFontID, fScaleX, fScaleY, err));
482 fFTSize = NULL;
483 } else {
484 // seems we need to reset this every time (not sure why, but without it
485 // I get random italics from some other fFTSize)
486 FT_Set_Transform( fFace, &fMatrix22, NULL);
487 }
488 return err;
489 }
490
emboldenOutline(FT_Outline * outline)491 void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
492 FT_Pos strength;
493 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
494 / 24;
495 FT_Outline_Embolden(outline, strength);
496 }
497
generateGlyphCount() const498 unsigned SkScalerContext_FreeType::generateGlyphCount() const {
499 return fFace->num_glyphs;
500 }
501
generateCharToGlyph(SkUnichar uni)502 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
503 return SkToU16(FT_Get_Char_Index( fFace, uni ));
504 }
505
generateGlyphToChar(uint16_t glyph)506 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
507 // iterate through each cmap entry, looking for matching glyph indices
508 FT_UInt glyphIndex;
509 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
510
511 while (glyphIndex != 0) {
512 if (glyphIndex == glyph) {
513 return charCode;
514 }
515 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
516 }
517
518 return 0;
519 }
520
compute_pixel_mode(SkMask::Format format)521 static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
522 switch (format) {
523 case SkMask::kHorizontalLCD_Format:
524 case SkMask::kVerticalLCD_Format:
525 SkASSERT(!"An LCD format should never be passed here");
526 return FT_PIXEL_MODE_GRAY;
527 case SkMask::kBW_Format:
528 return FT_PIXEL_MODE_MONO;
529 case SkMask::kA8_Format:
530 default:
531 return FT_PIXEL_MODE_GRAY;
532 }
533 }
534
generateAdvance(SkGlyph * glyph)535 void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
536 #ifdef FT_ADVANCES_H
537 /* unhinted and light hinted text have linearly scaled advances
538 * which are very cheap to compute with some font formats...
539 */
540 {
541 SkAutoMutexAcquire ac(gFTMutex);
542
543 if (this->setupSize()) {
544 glyph->zeroMetrics();
545 return;
546 }
547
548 FT_Error error;
549 FT_Fixed advance;
550
551 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
552 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
553 &advance );
554 if (0 == error) {
555 glyph->fRsbDelta = 0;
556 glyph->fLsbDelta = 0;
557 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
558 glyph->fAdvanceY = 0;
559 return;
560 }
561 }
562 #endif /* FT_ADVANCES_H */
563 /* otherwise, we need to load/hint the glyph, which is slower */
564 this->generateMetrics(glyph);
565 return;
566 }
567
generateMetrics(SkGlyph * glyph)568 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
569 SkAutoMutexAcquire ac(gFTMutex);
570
571 glyph->fRsbDelta = 0;
572 glyph->fLsbDelta = 0;
573
574 FT_Error err;
575
576 if (this->setupSize()) {
577 goto ERROR;
578 }
579
580 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
581 if (err != 0) {
582 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
583 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
584 ERROR:
585 glyph->zeroMetrics();
586 return;
587 }
588
589 switch ( fFace->glyph->format ) {
590 case FT_GLYPH_FORMAT_OUTLINE:
591 FT_BBox bbox;
592
593 if (fRec.fFlags & kEmbolden_Flag) {
594 emboldenOutline(&fFace->glyph->outline);
595 }
596 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
597
598 if (fRec.fSubpixelPositioning) {
599 int dx = glyph->getSubXFixed() >> 10;
600 int dy = glyph->getSubYFixed() >> 10;
601 // negate dy since freetype-y-goes-up and skia-y-goes-down
602 bbox.xMin += dx;
603 bbox.yMin -= dy;
604 bbox.xMax += dx;
605 bbox.yMax -= dy;
606 }
607
608 bbox.xMin &= ~63;
609 bbox.yMin &= ~63;
610 bbox.xMax = (bbox.xMax + 63) & ~63;
611 bbox.yMax = (bbox.yMax + 63) & ~63;
612
613 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
614 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
615 glyph->fTop = -SkToS16(bbox.yMax >> 6);
616 glyph->fLeft = SkToS16(bbox.xMin >> 6);
617 break;
618
619 case FT_GLYPH_FORMAT_BITMAP:
620 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
621 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
622 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
623 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
624 break;
625
626 default:
627 SkASSERT(!"unknown glyph format");
628 goto ERROR;
629 }
630
631 if (!fRec.fSubpixelPositioning) {
632 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
633 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
634 if (fRec.fFlags & kDevKernText_Flag) {
635 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
636 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
637 }
638 } else {
639 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
640 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
641 }
642
643 #ifdef ENABLE_GLYPH_SPEW
644 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
645 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
646 #endif
647 }
648
649 #if defined(SK_SUPPORT_LCDTEXT)
650 namespace skia_freetype_support {
651 // extern functions from SkFontHost_FreeType_Subpixel
652 extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
653 extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
654 }
655
656 using namespace skia_freetype_support;
657 #endif
658
generateImage(const SkGlyph & glyph)659 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
660 SkAutoMutexAcquire ac(gFTMutex);
661
662 FT_Error err;
663
664 if (this->setupSize()) {
665 goto ERROR;
666 }
667
668 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
669 if (err != 0) {
670 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
671 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
672 ERROR:
673 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
674 return;
675 }
676
677 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
678 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
679
680 switch ( fFace->glyph->format ) {
681 case FT_GLYPH_FORMAT_OUTLINE: {
682 FT_Outline* outline = &fFace->glyph->outline;
683 FT_BBox bbox;
684 FT_Bitmap target;
685
686 if (fRec.fFlags & kEmbolden_Flag) {
687 emboldenOutline(outline);
688 }
689
690 int dx = 0, dy = 0;
691 if (fRec.fSubpixelPositioning) {
692 dx = glyph.getSubXFixed() >> 10;
693 dy = glyph.getSubYFixed() >> 10;
694 // negate dy since freetype-y-goes-up and skia-y-goes-down
695 dy = -dy;
696 }
697 FT_Outline_Get_CBox(outline, &bbox);
698 /*
699 what we really want to do for subpixel is
700 offset(dx, dy)
701 compute_bounds
702 offset(bbox & !63)
703 but that is two calls to offset, so we do the following, which
704 achieves the same thing with only one offset call.
705 */
706 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
707 dy - ((bbox.yMin + dy) & ~63));
708
709 #if defined(SK_SUPPORT_LCDTEXT)
710 if (lcdRenderMode) {
711 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
712 // we have to call FT_Render_Glyph and memcpy the image out.
713 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
714 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
715 FT_Render_Glyph(fFace->glyph, mode);
716
717 if (isVertical)
718 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
719 else
720 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
721
722 break;
723 }
724 #endif
725
726 target.width = glyph.fWidth;
727 target.rows = glyph.fHeight;
728 target.pitch = glyph.rowBytes();
729 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
730 target.pixel_mode = compute_pixel_mode(
731 (SkMask::Format)fRec.fMaskFormat);
732 target.num_grays = 256;
733
734 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
735 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
736 } break;
737
738 case FT_GLYPH_FORMAT_BITMAP: {
739 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
740 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
741 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
742 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
743
744 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
745 uint8_t* dst = (uint8_t*)glyph.fImage;
746
747 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
748 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
749 glyph.fMaskFormat == SkMask::kBW_Format)) {
750 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
751 unsigned dstRowBytes = glyph.rowBytes();
752 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
753 unsigned extraRowBytes = dstRowBytes - minRowBytes;
754
755 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
756 memcpy(dst, src, minRowBytes);
757 memset(dst + minRowBytes, 0, extraRowBytes);
758 src += srcRowBytes;
759 dst += dstRowBytes;
760 }
761 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
762 (glyph.fMaskFormat == SkMask::kA8_Format ||
763 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
764 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
765 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
766 uint8_t byte = 0;
767 int bits = 0;
768 const uint8_t* src_row = src;
769 uint8_t* dst_row = dst;
770
771 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
772 if (!bits) {
773 byte = *src_row++;
774 bits = 8;
775 }
776
777 *dst_row++ = byte & 0x80 ? 0xff : 0;
778 bits--;
779 byte <<= 1;
780 }
781
782 src += fFace->glyph->bitmap.pitch;
783 dst += glyph.rowBytes();
784 }
785 } else {
786 SkASSERT(!"unknown glyph bitmap transform needed");
787 }
788
789 if (lcdRenderMode)
790 glyph.expandA8ToLCD();
791
792 } break;
793
794 default:
795 SkASSERT(!"unknown glyph format");
796 goto ERROR;
797 }
798 }
799
800 ///////////////////////////////////////////////////////////////////////////////
801
802 #define ft2sk(x) SkFixedToScalar((x) << 10)
803
804 #if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
805 #define CONST_PARAM const
806 #else // older freetype doesn't use const here
807 #define CONST_PARAM
808 #endif
809
move_proc(CONST_PARAM FT_Vector * pt,void * ctx)810 static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
811 SkPath* path = (SkPath*)ctx;
812 path->close(); // to close the previous contour (if any)
813 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
814 return 0;
815 }
816
line_proc(CONST_PARAM FT_Vector * pt,void * ctx)817 static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
818 SkPath* path = (SkPath*)ctx;
819 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
820 return 0;
821 }
822
quad_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,void * ctx)823 static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
824 void* ctx) {
825 SkPath* path = (SkPath*)ctx;
826 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
827 return 0;
828 }
829
cubic_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,CONST_PARAM FT_Vector * pt2,void * ctx)830 static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
831 CONST_PARAM FT_Vector* pt2, void* ctx) {
832 SkPath* path = (SkPath*)ctx;
833 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
834 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
835 return 0;
836 }
837
generatePath(const SkGlyph & glyph,SkPath * path)838 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
839 SkPath* path) {
840 SkAutoMutexAcquire ac(gFTMutex);
841
842 SkASSERT(&glyph && path);
843
844 if (this->setupSize()) {
845 path->reset();
846 return;
847 }
848
849 uint32_t flags = fLoadGlyphFlags;
850 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
851 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
852
853 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
854
855 if (err != 0) {
856 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
857 glyph.getGlyphID(fBaseGlyphCount), flags, err));
858 path->reset();
859 return;
860 }
861
862 if (fRec.fFlags & kEmbolden_Flag) {
863 emboldenOutline(&fFace->glyph->outline);
864 }
865
866 FT_Outline_Funcs funcs;
867
868 funcs.move_to = move_proc;
869 funcs.line_to = line_proc;
870 funcs.conic_to = quad_proc;
871 funcs.cubic_to = cubic_proc;
872 funcs.shift = 0;
873 funcs.delta = 0;
874
875 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
876
877 if (err != 0) {
878 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
879 glyph.getGlyphID(fBaseGlyphCount), flags, err));
880 path->reset();
881 return;
882 }
883
884 path->close();
885 }
886
generateFontMetrics(SkPaint::FontMetrics * mx,SkPaint::FontMetrics * my)887 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
888 SkPaint::FontMetrics* my) {
889 if (NULL == mx && NULL == my) {
890 return;
891 }
892
893 SkAutoMutexAcquire ac(gFTMutex);
894
895 if (this->setupSize()) {
896 ERROR:
897 if (mx) {
898 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
899 }
900 if (my) {
901 sk_bzero(my, sizeof(SkPaint::FontMetrics));
902 }
903 return;
904 }
905
906 FT_Face face = fFace;
907 int upem = face->units_per_EM;
908 if (upem <= 0) {
909 goto ERROR;
910 }
911
912 SkPoint pts[6];
913 SkFixed ys[6];
914 SkFixed scaleY = fScaleY;
915 SkFixed mxy = fMatrix22.xy;
916 SkFixed myy = fMatrix22.yy;
917 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
918 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
919
920 int leading = face->height - (face->ascender + -face->descender);
921 if (leading < 0) {
922 leading = 0;
923 }
924
925 // Try to get the OS/2 table from the font. This contains the specific
926 // average font width metrics which Windows uses.
927 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
928
929 ys[0] = -face->bbox.yMax;
930 ys[1] = -face->ascender;
931 ys[2] = -face->descender;
932 ys[3] = -face->bbox.yMin;
933 ys[4] = leading;
934 ys[5] = os2 ? os2->xAvgCharWidth : 0;
935
936 SkScalar x_height;
937 if (os2 && os2->sxHeight) {
938 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
939 } else {
940 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
941 if (x_glyph) {
942 FT_BBox bbox;
943 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
944 if (fRec.fFlags & kEmbolden_Flag) {
945 emboldenOutline(&fFace->glyph->outline);
946 }
947 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
948 x_height = SkIntToScalar(bbox.yMax) / 64;
949 } else {
950 x_height = 0;
951 }
952 }
953
954 // convert upem-y values into scalar points
955 for (int i = 0; i < 6; i++) {
956 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
957 SkFixed x = SkFixedMul(mxy, y);
958 y = SkFixedMul(myy, y);
959 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
960 }
961
962 if (mx) {
963 mx->fTop = pts[0].fX;
964 mx->fAscent = pts[1].fX;
965 mx->fDescent = pts[2].fX;
966 mx->fBottom = pts[3].fX;
967 mx->fLeading = pts[4].fX;
968 mx->fAvgCharWidth = pts[5].fX;
969 mx->fXMin = xmin;
970 mx->fXMax = xmax;
971 mx->fXHeight = x_height;
972 }
973 if (my) {
974 my->fTop = pts[0].fY;
975 my->fAscent = pts[1].fY;
976 my->fDescent = pts[2].fY;
977 my->fBottom = pts[3].fY;
978 my->fLeading = pts[4].fY;
979 my->fAvgCharWidth = pts[5].fY;
980 my->fXMin = xmin;
981 my->fXMax = xmax;
982 my->fXHeight = x_height;
983 }
984 }
985
986 ////////////////////////////////////////////////////////////////////////
987 ////////////////////////////////////////////////////////////////////////
988
CreateScalerContext(const SkDescriptor * desc)989 SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
990 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
991 if (!c->success()) {
992 SkDELETE(c);
993 c = NULL;
994 }
995 return c;
996 }
997
998 ///////////////////////////////////////////////////////////////////////////////
999
1000 /* Export this so that other parts of our FonttHost port can make use of our
1001 ability to extract the name+style from a stream, using FreeType's api.
1002 */
find_name_and_style(SkStream * stream,SkString * name,SkTypeface::Style * style)1003 bool find_name_and_style(SkStream* stream, SkString* name, SkTypeface::Style* style) {
1004 FT_Library library;
1005 if (FT_Init_FreeType(&library)) {
1006 name->set(NULL);
1007 return false;
1008 }
1009
1010 FT_Open_Args args;
1011 memset(&args, 0, sizeof(args));
1012
1013 const void* memoryBase = stream->getMemoryBase();
1014 FT_StreamRec streamRec;
1015
1016 if (NULL != memoryBase) {
1017 args.flags = FT_OPEN_MEMORY;
1018 args.memory_base = (const FT_Byte*)memoryBase;
1019 args.memory_size = stream->getLength();
1020 } else {
1021 memset(&streamRec, 0, sizeof(streamRec));
1022 streamRec.size = stream->read(NULL, 0);
1023 streamRec.descriptor.pointer = stream;
1024 streamRec.read = sk_stream_read;
1025 streamRec.close = sk_stream_close;
1026
1027 args.flags = FT_OPEN_STREAM;
1028 args.stream = &streamRec;
1029 }
1030
1031 FT_Face face;
1032 if (FT_Open_Face(library, &args, 0, &face)) {
1033 FT_Done_FreeType(library);
1034 name->set(NULL);
1035 return false;
1036 }
1037
1038 name->set(face->family_name);
1039 int tempStyle = SkTypeface::kNormal;
1040
1041 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1042 tempStyle |= SkTypeface::kBold;
1043 }
1044 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1045 tempStyle |= SkTypeface::kItalic;
1046 }
1047
1048 *style = (SkTypeface::Style)tempStyle;
1049 FT_Done_Face(face);
1050 FT_Done_FreeType(library);
1051 return true;
1052 }
1053