3 * Copyright 2006 The Android Open Source Project
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
9 #include "SkAdvancedTypefaceMetrics.h"
12 #include "SkColorPriv.h"
13 #include "SkDescriptor.h"
15 #include "SkFloatingPoint.h"
16 #include "SkFontHost.h"
17 #include "SkFontHost_FreeType_common.h"
20 #include "SkMaskGamma.h"
21 #include "SkOTUtils.h"
23 #include "SkScalerContext.h"
26 #include "SkTemplates.h"
29 #if defined(SK_CAN_USE_DLOPEN)
33 #include FT_FREETYPE_H
36 #include FT_TRUETYPE_TABLES_H
37 #include FT_TYPE1_TABLES_H
39 // In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
40 #include FT_SYNTHESIS_H
42 #ifdef FT_LCD_FILTER_H
43 #include FT_LCD_FILTER_H
47 #include FT_ADVANCES_H
51 // Also include the files by name for build tools which require this.
52 #include <freetype/freetype.h>
53 #include <freetype/ftoutln.h>
54 #include <freetype/ftsizes.h>
55 #include <freetype/tttables.h>
56 #include <freetype/ftadvanc.h>
57 #include <freetype/ftlcdfil.h>
58 #include <freetype/ftbitmap.h>
59 #include <freetype/ftsynth.h>
62 // FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
63 // were introduced in FreeType 2.5.0.
64 // The following may be removed once FreeType 2.5.0 is required to build.
66 # define FT_LOAD_COLOR ( 1L << 20 )
67 # define FT_PIXEL_MODE_BGRA 7
70 // FT_HAS_COLOR and the corresponding FT_FACE_FLAG_COLOR
71 // were introduced in FreeType 2.5.1
72 // The following may be removed once FreeType 2.5.1 is required to build.
74 # define FT_HAS_COLOR(face) false
77 //#define ENABLE_GLYPH_SPEW // for tracing calls
78 //#define DUMP_STRIKE_CREATION
80 //#define SK_GAMMA_APPLY_TO_A8
82 using namespace skia_advanced_typeface_metrics_utils;
84 static bool isLCD(const SkScalerContext::Rec& rec) {
85 switch (rec.fMaskFormat) {
86 case SkMask::kLCD16_Format:
87 case SkMask::kLCD32_Format:
94 //////////////////////////////////////////////////////////////////////////
98 SK_DECLARE_STATIC_MUTEX(gFTMutex);
100 static FT_Library gFTLibrary;
101 static SkFaceRec* gFaceRecHead;
102 static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
103 static bool gLCDSupport; // true iff LCD is supported by the runtime.
104 static int gLCDExtra; // number of extra pixels for filtering.
106 /////////////////////////////////////////////////////////////////////////
108 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
109 // The following platforms provide FreeType of at least 2.4.0.
110 // Ubuntu >= 11.04 (previous deprecated April 2013)
111 // Debian >= 6.0 (good)
112 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
113 // Fedora >= 14 (good)
114 // Android >= Gingerbread (good)
115 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
117 // Caller must lock gFTMutex before calling this function.
118 static bool InitFreetype() {
119 FT_Error err = FT_Init_FreeType(&gFTLibrary);
124 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
125 #ifdef FT_LCD_FILTER_H
126 // Use default { 0x10, 0x40, 0x70, 0x40, 0x10 }, as it adds up to 0x110, simulating ink spread.
127 // SetLcdFilter must be called before SetLcdFilterWeights.
128 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
131 gLCDExtra = 2; //Using a filter adds one full pixel to each side.
133 #ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
134 // This also adds to 0x110 simulating ink spread, but provides better results than default.
135 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
137 #if defined(SK_FONTHOST_FREETYPE_RUNTIME_VERSION) && \
138 SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
139 err = FT_Library_SetLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
140 #elif defined(SK_CAN_USE_DLOPEN) && SK_CAN_USE_DLOPEN == 1
141 //The FreeType library is already loaded, so symbols are available in process.
142 void* self = dlopen(NULL, RTLD_LAZY);
144 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
145 //The following cast is non-standard, but safe for POSIX.
146 *reinterpret_cast<void**>(&setLcdFilterWeights) = dlsym(self, "FT_Library_SetLcdFilterWeights");
149 if (NULL != setLcdFilterWeights) {
150 err = setLcdFilterWeights(gFTLibrary, gGaussianLikeHeavyWeights);
159 gLCDSupportValid = true;
164 // Called while holding gFTMutex.
165 static void determine_lcd_support(bool* lcdSupported) {
166 if (!gLCDSupportValid) {
167 // This will determine LCD support as a side effect.
169 FT_Done_FreeType(gFTLibrary);
171 SkASSERT(gLCDSupportValid);
172 *lcdSupported = gLCDSupport;
175 // Lazy, once, wrapper to ask the FreeType Library if it can support LCD text
176 static bool is_lcd_supported() {
177 static bool lcdSupported = false;
178 SkOnce(&gLCDSupportValid, &gFTMutex, determine_lcd_support, &lcdSupported);
182 class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
184 SkScalerContext_FreeType(SkTypeface*, const SkDescriptor* desc);
185 virtual ~SkScalerContext_FreeType();
187 bool success() const {
188 return fFaceRec != NULL &&
194 virtual unsigned generateGlyphCount() SK_OVERRIDE;
195 virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE;
196 virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE;
197 virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE;
198 virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE;
199 virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE;
200 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
201 SkPaint::FontMetrics* my) SK_OVERRIDE;
202 virtual SkUnichar generateGlyphToChar(uint16_t glyph) SK_OVERRIDE;
206 FT_Face fFace; // reference to shared face in gFaceRecHead
207 FT_Size fFTSize; // our own copy
209 SkFixed fScaleX, fScaleY;
211 uint32_t fLoadGlyphFlags;
212 bool fDoLinearMetrics;
215 // Need scalar versions for generateFontMetrics
217 SkMatrix fMatrix22Scalar;
219 FT_Error setupSize();
220 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
221 bool snapToPixelBoundary = false);
222 bool getCBoxForLetter(char letter, FT_BBox* bbox);
223 // Caller must lock gFTMutex before calling this function.
224 void updateGlyphIfLCD(SkGlyph* glyph);
225 // Caller must lock gFTMutex before calling this function.
226 // update FreeType2 glyph slot with glyph emboldened
227 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
230 ///////////////////////////////////////////////////////////////////////////
231 ///////////////////////////////////////////////////////////////////////////
236 FT_StreamRec fFTStream;
241 // assumes ownership of the stream, will call unref() when its done
242 SkFaceRec(SkStream* strm, uint32_t fontID);
249 static unsigned long sk_stream_read(FT_Stream stream,
250 unsigned long offset,
251 unsigned char* buffer,
252 unsigned long count ) {
253 SkStream* str = (SkStream*)stream->descriptor.pointer;
256 if (!str->rewind()) {
261 ret = str->read(NULL, offset);
266 ret = str->read(buffer, count);
276 static void sk_stream_close(FT_Stream) {}
279 SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
280 : fNext(NULL), fSkStream(strm), fRefCnt(1), fFontID(fontID) {
281 // SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
283 sk_bzero(&fFTStream, sizeof(fFTStream));
284 fFTStream.size = fSkStream->getLength();
285 fFTStream.descriptor.pointer = fSkStream;
286 fFTStream.read = sk_stream_read;
287 fFTStream.close = sk_stream_close;
290 // Will return 0 on failure
291 // Caller must lock gFTMutex before calling this function.
292 static SkFaceRec* ref_ft_face(const SkTypeface* typeface) {
293 const SkFontID fontID = typeface->uniqueID();
294 SkFaceRec* rec = gFaceRecHead;
296 if (rec->fFontID == fontID) {
297 SkASSERT(rec->fFace);
305 SkStream* strm = typeface->openStream(&face_index);
310 // this passes ownership of strm to the rec
311 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
314 memset(&args, 0, sizeof(args));
315 const void* memoryBase = strm->getMemoryBase();
317 if (NULL != memoryBase) {
318 //printf("mmap(%s)\n", keyString.c_str());
319 args.flags = FT_OPEN_MEMORY;
320 args.memory_base = (const FT_Byte*)memoryBase;
321 args.memory_size = strm->getLength();
323 //printf("fopen(%s)\n", keyString.c_str());
324 args.flags = FT_OPEN_STREAM;
325 args.stream = &rec->fFTStream;
328 FT_Error err = FT_Open_Face(gFTLibrary, &args, face_index, &rec->fFace);
329 if (err) { // bad filename, try the default font
330 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
334 SkASSERT(rec->fFace);
335 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
336 rec->fNext = gFaceRecHead;
342 // Caller must lock gFTMutex before calling this function.
343 static void unref_ft_face(FT_Face face) {
344 SkFaceRec* rec = gFaceRecHead;
345 SkFaceRec* prev = NULL;
347 SkFaceRec* next = rec->fNext;
348 if (rec->fFace == face) {
349 if (--rec->fRefCnt == 0) {
363 SkDEBUGFAIL("shouldn't get here, face not in list");
368 AutoFTAccess(const SkTypeface* tf) : fRec(NULL), fFace(NULL) {
370 if (1 == ++gFTCount) {
371 if (!InitFreetype()) {
375 fRec = ref_ft_face(tf);
383 unref_ft_face(fFace);
385 if (0 == --gFTCount) {
386 FT_Done_FreeType(gFTLibrary);
391 SkFaceRec* rec() { return fRec; }
392 FT_Face face() { return fFace; }
399 ///////////////////////////////////////////////////////////////////////////
401 // Work around for old versions of freetype.
402 static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
403 FT_Int32 loadFlags, FT_Fixed* advances) {
405 return FT_Get_Advances(face, start, count, loadFlags, advances);
407 if (!face || start >= face->num_glyphs ||
408 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
409 return 6; // "Invalid argument."
414 for (int i = 0; i < count; i++) {
415 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
418 advances[i] = face->glyph->advance.x;
425 static bool canEmbed(FT_Face face) {
426 #ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
427 FT_UShort fsType = FT_Get_FSType_Flags(face);
428 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
429 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
431 // No embedding is 0x2 and bitmap embedding only is 0x200.
433 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
434 return (os2_table->fsType & 0x202) == 0;
436 return false; // We tried, fail safe.
440 static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
441 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
444 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
446 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
450 static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
451 FT_Fixed advance = 0;
452 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
460 static void populate_glyph_to_unicode(FT_Face& face,
461 SkTDArray<SkUnichar>* glyphToUnicode) {
462 // Check and see if we have Unicode cmaps.
463 for (int i = 0; i < face->num_charmaps; ++i) {
464 // CMaps known to support Unicode:
465 // Platform ID Encoding ID Name
466 // ----------- ----------- -----------------------------------
467 // 0 0,1 Apple Unicode
468 // 0 3 Apple Unicode 2.0 (preferred)
469 // 3 1 Microsoft Unicode UCS-2
470 // 3 10 Microsoft Unicode UCS-4 (preferred)
472 // See Apple TrueType Reference Manual
473 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
474 // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
475 // Microsoft OpenType Specification
476 // http://www.microsoft.com/typography/otspec/cmap.htm
478 FT_UShort platformId = face->charmaps[i]->platform_id;
479 FT_UShort encodingId = face->charmaps[i]->encoding_id;
481 if (platformId != 0 && platformId != 3) {
484 if (platformId == 3 && encodingId != 1 && encodingId != 10) {
487 bool preferredMap = ((platformId == 3 && encodingId == 10) ||
488 (platformId == 0 && encodingId == 3));
490 FT_Set_Charmap(face, face->charmaps[i]);
491 if (glyphToUnicode->isEmpty()) {
492 glyphToUnicode->setCount(face->num_glyphs);
493 memset(glyphToUnicode->begin(), 0,
494 sizeof(SkUnichar) * face->num_glyphs);
497 // Iterate through each cmap entry.
499 for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
501 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
503 ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
504 (*glyphToUnicode)[glyphIndex] = charCode;
510 SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
511 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
512 const uint32_t* glyphIDs,
513 uint32_t glyphIDsCount) const {
514 #if defined(SK_BUILD_FOR_MAC)
517 AutoFTAccess fta(this);
518 FT_Face face = fta.face();
523 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
524 info->fFontName.set(FT_Get_Postscript_Name(face));
525 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
526 info->fLastGlyphID = face->num_glyphs - 1;
527 info->fEmSize = 1000;
530 const char* fontType = FT_Get_X11_Font_Format(face);
531 if (strcmp(fontType, "Type 1") == 0) {
532 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
533 } else if (strcmp(fontType, "CID Type 1") == 0) {
534 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
536 } else if (strcmp(fontType, "CFF") == 0) {
537 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
538 } else if (strcmp(fontType, "TrueType") == 0) {
539 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
542 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
543 ft_sfnt_head)) != NULL) {
544 info->fEmSize = ttHeader->Units_Per_EM;
547 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
551 if (FT_IS_FIXED_WIDTH(face))
552 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
553 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
554 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
556 PS_FontInfoRec ps_info;
557 TT_Postscript* tt_info;
558 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
559 info->fItalicAngle = ps_info.italic_angle;
560 } else if ((tt_info =
561 (TT_Postscript*)FT_Get_Sfnt_Table(face,
562 ft_sfnt_post)) != NULL) {
563 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
565 info->fItalicAngle = 0;
568 info->fAscent = face->ascender;
569 info->fDescent = face->descender;
571 // Figure out a good guess for StemV - Min width of i, I, !, 1.
572 // This probably isn't very good with an italic font.
573 int16_t min_width = SHRT_MAX;
575 char stem_chars[] = {'i', 'I', '!', '1'};
576 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
578 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
579 int16_t width = bbox.xMax - bbox.xMin;
580 if (width > 0 && width < min_width) {
582 info->fStemV = min_width;
589 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
590 info->fCapHeight = pclt_info->CapHeight;
591 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
592 if (serif_style >= 2 && serif_style <= 6)
593 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
594 else if (serif_style >= 9 && serif_style <= 12)
595 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
596 } else if (((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) &&
597 // sCapHeight is available only when version 2 or later.
598 os2_table->version != 0xFFFF &&
599 os2_table->version >= 2) {
600 info->fCapHeight = os2_table->sCapHeight;
602 // Figure out a good guess for CapHeight: average the height of M and X.
603 FT_BBox m_bbox, x_bbox;
605 got_m = GetLetterCBox(face, 'M', &m_bbox);
606 got_x = GetLetterCBox(face, 'X', &x_bbox);
607 if (got_m && got_x) {
608 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
610 } else if (got_m && !got_x) {
611 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
612 } else if (!got_m && got_x) {
613 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
615 // Last resort, use the ascent.
616 info->fCapHeight = info->fAscent;
620 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
621 face->bbox.xMax, face->bbox.yMin);
623 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
624 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
625 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
628 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
629 if (FT_IS_FIXED_WIDTH(face)) {
630 appendRange(&info->fGlyphWidths, 0);
631 int16_t advance = face->max_advance_width;
632 info->fGlyphWidths->fAdvance.append(1, &advance);
633 finishRange(info->fGlyphWidths.get(), 0,
634 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
636 appendRange(&info->fGlyphWidths, 0);
637 // So as to not blow out the stack, get advances in batches.
638 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
639 FT_Fixed advances[128];
640 int advanceCount = 128;
641 if (gID + advanceCount > face->num_glyphs)
642 advanceCount = face->num_glyphs - gID;
643 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
645 for (int i = 0; i < advanceCount; i++) {
646 int16_t advance = advances[i];
647 info->fGlyphWidths->fAdvance.append(1, &advance);
650 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
651 SkAdvancedTypefaceMetrics::WidthRange::kRange);
653 info->fGlyphWidths.reset(
662 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
663 FT_HAS_VERTICAL(face)) {
664 SkASSERT(false); // Not implemented yet.
667 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
668 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
669 // Postscript fonts may contain more than 255 glyphs, so we end up
670 // using multiple font descriptions with a glyph ordering. Record
671 // the name of each glyph.
672 info->fGlyphNames.reset(
673 new SkAutoTArray<SkString>(face->num_glyphs));
674 for (int gID = 0; gID < face->num_glyphs; gID++) {
675 char glyphName[128]; // PS limit for names is 127 bytes.
676 FT_Get_Glyph_Name(face, gID, glyphName, 128);
677 info->fGlyphNames->get()[gID].set(glyphName);
681 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
682 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
683 face->num_charmaps) {
684 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
688 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
694 ///////////////////////////////////////////////////////////////////////////
696 #define BLACK_LUMINANCE_LIMIT 0x40
697 #define WHITE_LUMINANCE_LIMIT 0xA0
699 static bool bothZero(SkScalar a, SkScalar b) {
700 return 0 == a && 0 == b;
703 // returns false if there is any non-90-rotation or skew
704 static bool isAxisAligned(const SkScalerContext::Rec& rec) {
705 return 0 == rec.fPreSkewX &&
706 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
707 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
710 SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(
711 const SkDescriptor* desc) const {
712 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType,
713 (const_cast<SkTypeface_FreeType*>(this),
722 void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
723 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
724 //Cap the requested size as larger sizes give bogus values.
725 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
726 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
727 rec->fTextSize = SkIntToScalar(1 << 14);
730 if (!is_lcd_supported() && isLCD(*rec)) {
731 // If the runtime Freetype library doesn't support LCD mode, we disable
733 rec->fMaskFormat = SkMask::kA8_Format;
736 SkPaint::Hinting h = rec->getHinting();
737 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
738 // collapse full->normal hinting if we're not doing LCD
739 h = SkPaint::kNormal_Hinting;
741 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
742 if (SkPaint::kNo_Hinting != h) {
743 h = SkPaint::kSlight_Hinting;
747 // rotated text looks bad with hinting, so we disable it as needed
748 if (!isAxisAligned(*rec)) {
749 h = SkPaint::kNo_Hinting;
753 #ifndef SK_GAMMA_APPLY_TO_A8
755 rec->ignorePreBlend();
760 int SkTypeface_FreeType::onGetUPEM() const {
761 AutoFTAccess fta(this);
762 FT_Face face = fta.face();
763 return face ? face->units_per_EM : 0;
766 bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
767 int count, int32_t adjustments[]) const {
768 AutoFTAccess fta(this);
769 FT_Face face = fta.face();
770 if (!face || !FT_HAS_KERNING(face)) {
774 for (int i = 0; i < count - 1; ++i) {
776 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
777 FT_KERNING_UNSCALED, &delta);
781 adjustments[i] = delta.x;
786 static FT_Int chooseBitmapStrike(FT_Face face, SkFixed scaleY) {
787 // early out if face is bad
789 SkDEBUGF(("chooseBitmapStrike aborted due to NULL face\n"));
792 // determine target ppem
793 FT_Pos targetPPEM = SkFixedToFDot6(scaleY);
794 // find a bitmap strike equal to or just larger than the requested size
795 FT_Int chosenStrikeIndex = -1;
796 FT_Pos chosenPPEM = 0;
797 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
798 FT_Pos thisPPEM = face->available_sizes[strikeIndex].y_ppem;
799 if (thisPPEM == targetPPEM) {
800 // exact match - our search stops here
801 chosenPPEM = thisPPEM;
802 chosenStrikeIndex = strikeIndex;
804 } else if (chosenPPEM < targetPPEM) {
805 // attempt to increase chosenPPEM
806 if (thisPPEM > chosenPPEM) {
807 chosenPPEM = thisPPEM;
808 chosenStrikeIndex = strikeIndex;
811 // attempt to decrease chosenPPEM, but not below targetPPEM
812 if (thisPPEM < chosenPPEM && thisPPEM > targetPPEM) {
813 chosenPPEM = thisPPEM;
814 chosenStrikeIndex = strikeIndex;
818 if (chosenStrikeIndex != -1) {
819 // use the chosen strike
820 FT_Error err = FT_Select_Size(face, chosenStrikeIndex);
822 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x\n", face->family_name,
823 chosenStrikeIndex, err));
824 chosenStrikeIndex = -1;
827 return chosenStrikeIndex;
830 SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
831 const SkDescriptor* desc)
832 : SkScalerContext_FreeType_Base(typeface, desc) {
833 SkAutoMutexAcquire ac(gFTMutex);
836 if (!InitFreetype()) {
842 // load the font file
846 fFaceRec = ref_ft_face(typeface);
847 if (NULL == fFaceRec) {
850 fFace = fFaceRec->fFace;
852 // compute our factors from the record
856 fRec.getSingleMatrix(&m);
858 #ifdef DUMP_STRIKE_CREATION
860 SkFontHost::GetDescriptorKeyString(desc, &keyString);
861 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
862 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
863 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
864 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
865 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
868 // now compute our scale factors
869 SkScalar sx = m.getScaleX();
870 SkScalar sy = m.getScaleY();
872 fMatrix22Scalar.reset();
874 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
875 // sort of give up on hinting
876 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
877 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
878 sx = sy = SkScalarAve(sx, sy);
880 SkScalar inv = SkScalarInvert(sx);
882 // flip the skew elements to go from our Y-down system to FreeType's
883 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
884 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
885 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
886 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
888 fMatrix22Scalar.setScaleX(SkScalarMul(m.getScaleX(), inv));
889 fMatrix22Scalar.setSkewX(-SkScalarMul(m.getSkewX(), inv));
890 fMatrix22Scalar.setSkewY(-SkScalarMul(m.getSkewY(), inv));
891 fMatrix22Scalar.setScaleY(SkScalarMul(m.getScaleY(), inv));
893 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
894 fMatrix22.xy = fMatrix22.yx = 0;
897 fScaleX = SkScalarToFixed(sx);
898 fScaleY = SkScalarToFixed(sy);
900 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
902 // compute the flags we send to Load_Glyph
903 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
905 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
907 if (SkMask::kBW_Format == fRec.fMaskFormat) {
908 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
909 loadFlags = FT_LOAD_TARGET_MONO;
910 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
911 loadFlags = FT_LOAD_NO_HINTING;
912 linearMetrics = true;
915 switch (fRec.getHinting()) {
916 case SkPaint::kNo_Hinting:
917 loadFlags = FT_LOAD_NO_HINTING;
918 linearMetrics = true;
920 case SkPaint::kSlight_Hinting:
921 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
923 case SkPaint::kNormal_Hinting:
924 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
925 loadFlags = FT_LOAD_FORCE_AUTOHINT;
928 case SkPaint::kFull_Hinting:
929 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
930 loadFlags = FT_LOAD_FORCE_AUTOHINT;
933 loadFlags = FT_LOAD_TARGET_NORMAL;
936 loadFlags = FT_LOAD_TARGET_LCD_V;
938 loadFlags = FT_LOAD_TARGET_LCD;
943 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
948 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
949 loadFlags |= FT_LOAD_NO_BITMAP;
952 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
953 // advances, as fontconfig and cairo do.
954 // See http://code.google.com/p/skia/issues/detail?id=222.
955 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
957 // Use vertical layout if requested.
958 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
959 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
962 loadFlags |= FT_LOAD_COLOR;
964 fLoadGlyphFlags = loadFlags;
967 FT_Error err = FT_New_Size(fFace, &fFTSize);
969 SkDEBUGF(("FT_New_Size returned %x for face %s\n", err, fFace->family_name));
973 err = FT_Activate_Size(fFTSize);
975 SkDEBUGF(("FT_Activate_Size(%08x, 0x%x, 0x%x) returned 0x%x\n", fFace, fScaleX, fScaleY,
981 if (FT_IS_SCALABLE(fFace)) {
982 err = FT_Set_Char_Size(fFace, SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY), 72, 72);
984 SkDEBUGF(("FT_Set_CharSize(%08x, 0x%x, 0x%x) returned 0x%x\n",
985 fFace, fScaleX, fScaleY, err));
989 FT_Set_Transform(fFace, &fMatrix22, NULL);
990 } else if (FT_HAS_FIXED_SIZES(fFace)) {
991 fStrikeIndex = chooseBitmapStrike(fFace, fScaleY);
992 if (fStrikeIndex == -1) {
993 SkDEBUGF(("no glyphs for font \"%s\" size %f?\n",
994 fFace->family_name, SkFixedToScalar(fScaleY)));
996 // FreeType does no provide linear metrics for bitmap fonts.
997 linearMetrics = false;
999 // FreeType documentation says:
1000 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
1001 // Bitmap-only fonts ignore this flag.
1003 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
1004 // Force this flag off for bitmap only fonts.
1005 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
1008 SkDEBUGF(("unknown kind of font \"%s\" size %f?\n",
1009 fFace->family_name, SkFixedToScalar(fScaleY)));
1012 fDoLinearMetrics = linearMetrics;
1015 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
1016 SkAutoMutexAcquire ac(gFTMutex);
1018 if (fFTSize != NULL) {
1019 FT_Done_Size(fFTSize);
1022 if (fFace != NULL) {
1023 unref_ft_face(fFace);
1025 if (--gFTCount == 0) {
1026 FT_Done_FreeType(gFTLibrary);
1027 SkDEBUGCODE(gFTLibrary = NULL;)
1031 /* We call this before each use of the fFace, since we may be sharing
1032 this face with other context (at different sizes).
1034 FT_Error SkScalerContext_FreeType::setupSize() {
1035 FT_Error err = FT_Activate_Size(fFTSize);
1037 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
1038 fFaceRec->fFontID, fScaleX, fScaleY, err));
1043 // seems we need to reset this every time (not sure why, but without it
1044 // I get random italics from some other fFTSize)
1045 FT_Set_Transform(fFace, &fMatrix22, NULL);
1049 unsigned SkScalerContext_FreeType::generateGlyphCount() {
1050 return fFace->num_glyphs;
1053 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
1054 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1057 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
1058 // iterate through each cmap entry, looking for matching glyph indices
1060 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1062 while (glyphIndex != 0) {
1063 if (glyphIndex == glyph) {
1066 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1072 void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
1073 #ifdef FT_ADVANCES_H
1074 /* unhinted and light hinted text have linearly scaled advances
1075 * which are very cheap to compute with some font formats...
1077 if (fDoLinearMetrics) {
1078 SkAutoMutexAcquire ac(gFTMutex);
1080 if (this->setupSize()) {
1081 glyph->zeroMetrics();
1088 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
1089 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1092 glyph->fRsbDelta = 0;
1093 glyph->fLsbDelta = 0;
1094 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);
1095 glyph->fAdvanceY = - SkFixedMul(fMatrix22.yx, advance);
1099 #endif /* FT_ADVANCES_H */
1100 /* otherwise, we need to load/hint the glyph, which is slower */
1101 this->generateMetrics(glyph);
1105 void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1107 bool snapToPixelBoundary) {
1109 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1111 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
1112 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1113 int dy = SkFixedToFDot6(glyph->getSubYFixed());
1114 // negate dy since freetype-y-goes-up and skia-y-goes-down
1121 // outset the box to integral boundaries
1122 if (snapToPixelBoundary) {
1125 bbox->xMax = (bbox->xMax + 63) & ~63;
1126 bbox->yMax = (bbox->yMax + 63) & ~63;
1129 // Must come after snapToPixelBoundary so that the width and height are
1130 // consistent. Otherwise asserts will fire later on when generating the
1132 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1134 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1135 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1136 FT_Vector_Transform(&vector, &fMatrix22);
1137 bbox->xMin += vector.x;
1138 bbox->xMax += vector.x;
1139 bbox->yMin += vector.y;
1140 bbox->yMax += vector.y;
1144 bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1145 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
1148 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0)
1150 emboldenIfNeeded(fFace, fFace->glyph);
1151 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1155 void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1158 glyph->fHeight += gLCDExtra;
1159 glyph->fTop -= gLCDExtra >> 1;
1161 glyph->fWidth += gLCDExtra;
1162 glyph->fLeft -= gLCDExtra >> 1;
1167 inline void scaleGlyphMetrics(SkGlyph& glyph, SkScalar scale) {
1168 glyph.fWidth *= scale;
1169 glyph.fHeight *= scale;
1170 glyph.fTop *= scale;
1171 glyph.fLeft *= scale;
1173 SkFixed fixedScale = SkScalarToFixed(scale);
1174 glyph.fAdvanceX = SkFixedMul(glyph.fAdvanceX, fixedScale);
1175 glyph.fAdvanceY = SkFixedMul(glyph.fAdvanceY, fixedScale);
1178 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1179 SkAutoMutexAcquire ac(gFTMutex);
1181 glyph->fRsbDelta = 0;
1182 glyph->fLsbDelta = 0;
1186 if (this->setupSize()) {
1190 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1193 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%x) returned 0x%x\n",
1194 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
1197 glyph->zeroMetrics();
1200 emboldenIfNeeded(fFace, fFace->glyph);
1202 switch ( fFace->glyph->format ) {
1203 case FT_GLYPH_FORMAT_OUTLINE:
1204 if (0 == fFace->glyph->outline.n_contours) {
1211 getBBoxForCurrentGlyph(glyph, &bbox, true);
1213 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1214 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1215 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1216 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1218 updateGlyphIfLCD(glyph);
1222 case FT_GLYPH_FORMAT_BITMAP:
1223 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1225 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1226 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1227 FT_Vector_Transform(&vector, &fMatrix22);
1228 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1229 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1232 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1233 glyph->fMaskFormat = SkMask::kARGB32_Format;
1236 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
1237 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
1238 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
1239 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
1243 SkDEBUGFAIL("unknown glyph format");
1247 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1248 if (fDoLinearMetrics) {
1249 glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1250 glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1252 glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1253 glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1256 if (fDoLinearMetrics) {
1257 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1258 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1260 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1261 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1263 if (fRec.fFlags & kDevKernText_Flag) {
1264 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1265 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1270 if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP && fScaleY && fFace->size->metrics.y_ppem) {
1271 // NOTE: both dimensions are scaled by y_ppem. this is WAI.
1272 scaleGlyphMetrics(*glyph, SkScalarDiv(SkFixedToScalar(fScaleY),
1273 SkIntToScalar(fFace->size->metrics.y_ppem)));
1276 #ifdef ENABLE_GLYPH_SPEW
1277 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1278 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1283 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1284 SkAutoMutexAcquire ac(gFTMutex);
1288 if (this->setupSize()) {
1292 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1294 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1295 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1297 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1301 emboldenIfNeeded(fFace, fFace->glyph);
1302 generateGlyphImage(fFace, glyph);
1306 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1308 SkAutoMutexAcquire ac(gFTMutex);
1310 SkASSERT(&glyph && path);
1312 if (this->setupSize()) {
1317 uint32_t flags = fLoadGlyphFlags;
1318 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1319 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1321 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1324 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1325 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1329 emboldenIfNeeded(fFace, fFace->glyph);
1331 generateGlyphPath(fFace, path);
1333 // The path's origin from FreeType is always the horizontal layout origin.
1334 // Offset the path so that it is relative to the vertical origin if needed.
1335 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1337 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1338 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1339 FT_Vector_Transform(&vector, &fMatrix22);
1340 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1344 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1345 SkPaint::FontMetrics* my) {
1346 if (NULL == mx && NULL == my) {
1350 SkAutoMutexAcquire ac(gFTMutex);
1352 if (this->setupSize()) {
1355 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
1358 sk_bzero(my, sizeof(SkPaint::FontMetrics));
1363 FT_Face face = fFace;
1364 SkScalar scaleX = fScale.x();
1365 SkScalar scaleY = fScale.y();
1366 SkScalar mxy = fMatrix22Scalar.getSkewX() * scaleY;
1367 SkScalar myy = fMatrix22Scalar.getScaleY() * scaleY;
1369 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1370 SkScalar upem = SkIntToScalar(face->units_per_EM);
1372 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1374 upem = SkIntToScalar(ttHeader->Units_Per_EM);
1378 // use the os/2 table as a source of reasonable defaults.
1379 SkScalar x_height = 0.0f;
1380 SkScalar avgCharWidth = 0.0f;
1381 SkScalar cap_height = 0.0f;
1382 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1384 x_height = scaleX * SkIntToScalar(os2->sxHeight) / upem;
1385 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
1386 if (os2->version != 0xFFFF && os2->version >= 2) {
1387 cap_height = scaleX * SkIntToScalar(os2->sCapHeight) / upem;
1391 // pull from format-specific metrics as needed
1392 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
1393 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
1394 ascent = -SkIntToScalar(face->ascender) / upem;
1395 descent = -SkIntToScalar(face->descender) / upem;
1396 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1397 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1398 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1399 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1400 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
1401 // we may be able to synthesize x_height and cap_height from outline
1404 if (getCBoxForLetter('x', &bbox)) {
1405 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1410 if (getCBoxForLetter('H', &bbox)) {
1411 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1414 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1415 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1416 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1417 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1418 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1419 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f))
1422 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1423 ymin = descent + leading;
1424 ymax = ascent - descent;
1429 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1433 if (!avgCharWidth) {
1434 avgCharWidth = xmax - xmin;
1437 cap_height = -ascent;
1440 // disallow negative linespacing
1441 if (leading < 0.0f) {
1446 mx->fTop = ymax * mxy;
1447 mx->fAscent = ascent * mxy;
1448 mx->fDescent = descent * mxy;
1449 mx->fBottom = ymin * mxy;
1450 mx->fLeading = leading * mxy;
1451 mx->fAvgCharWidth = avgCharWidth * mxy;
1454 mx->fXHeight = x_height;
1455 mx->fCapHeight = cap_height;
1458 my->fTop = ymax * myy;
1459 my->fAscent = ascent * myy;
1460 my->fDescent = descent * myy;
1461 my->fBottom = ymin * myy;
1462 my->fLeading = leading * myy;
1463 my->fAvgCharWidth = avgCharWidth * myy;
1466 my->fXHeight = x_height;
1467 my->fCapHeight = cap_height;
1471 void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1473 if (fRec.fFlags & SkScalerContext::kEmbolden_Flag) {
1474 switch ( glyph->format ) {
1475 case FT_GLYPH_FORMAT_OUTLINE:
1477 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale) / 24;
1478 FT_Outline_Embolden(&glyph->outline, strength);
1480 case FT_GLYPH_FORMAT_BITMAP:
1481 FT_GlyphSlot_Own_Bitmap(glyph);
1482 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1485 SkDEBUGFAIL("unknown glyph format");
1490 ///////////////////////////////////////////////////////////////////////////////
1492 #include "SkUtils.h"
1494 static SkUnichar next_utf8(const void** chars) {
1495 return SkUTF8_NextUnichar((const char**)chars);
1498 static SkUnichar next_utf16(const void** chars) {
1499 return SkUTF16_NextUnichar((const uint16_t**)chars);
1502 static SkUnichar next_utf32(const void** chars) {
1503 const SkUnichar** uniChars = (const SkUnichar**)chars;
1504 SkUnichar uni = **uniChars;
1509 typedef SkUnichar (*EncodingProc)(const void**);
1511 static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1512 static const EncodingProc gProcs[] = {
1513 next_utf8, next_utf16, next_utf32
1515 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1519 int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1520 uint16_t glyphs[], int glyphCount) const {
1521 AutoFTAccess fta(this);
1522 FT_Face face = fta.face();
1525 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1530 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1532 if (NULL == glyphs) {
1533 for (int i = 0; i < glyphCount; ++i) {
1534 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1540 int first = glyphCount;
1541 for (int i = 0; i < glyphCount; ++i) {
1542 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1543 glyphs[i] = SkToU16(id);
1544 if (0 == id && i < first) {
1552 int SkTypeface_FreeType::onCountGlyphs() const {
1553 // we cache this value, using -1 as a sentinel for "not computed"
1554 if (fGlyphCount < 0) {
1555 AutoFTAccess fta(this);
1556 FT_Face face = fta.face();
1557 // if the face failed, we still assign a non-negative value
1558 fGlyphCount = face ? face->num_glyphs : 0;
1563 SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
1564 SkTypeface::LocalizedStrings* nameIter =
1565 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1566 if (NULL == nameIter) {
1567 SkString familyName;
1568 this->getFamilyName(&familyName);
1569 SkString language("und"); //undetermined
1570 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1575 int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1576 AutoFTAccess fta(this);
1577 FT_Face face = fta.face();
1579 FT_ULong tableCount = 0;
1582 // When 'tag' is NULL, returns number of tables in 'length'.
1583 error = FT_Sfnt_Table_Info(face, 0, NULL, &tableCount);
1589 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1591 FT_ULong tablelength;
1592 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1596 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1602 size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1603 size_t length, void* data) const
1605 AutoFTAccess fta(this);
1606 FT_Face face = fta.face();
1608 FT_ULong tableLength = 0;
1611 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1612 error = FT_Load_Sfnt_Table(face, tag, 0, NULL, &tableLength);
1617 if (offset > tableLength) {
1620 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
1622 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1631 ///////////////////////////////////////////////////////////////////////////////
1632 ///////////////////////////////////////////////////////////////////////////////
1634 /* Export this so that other parts of our FonttHost port can make use of our
1635 ability to extract the name+style from a stream, using FreeType's api.
1637 bool find_name_and_attributes(SkStream* stream, SkString* name,
1638 SkTypeface::Style* style, bool* isFixedPitch) {
1640 if (FT_Init_FreeType(&library)) {
1645 memset(&args, 0, sizeof(args));
1647 const void* memoryBase = stream->getMemoryBase();
1648 FT_StreamRec streamRec;
1650 if (NULL != memoryBase) {
1651 args.flags = FT_OPEN_MEMORY;
1652 args.memory_base = (const FT_Byte*)memoryBase;
1653 args.memory_size = stream->getLength();
1655 memset(&streamRec, 0, sizeof(streamRec));
1656 streamRec.size = stream->getLength();
1657 streamRec.descriptor.pointer = stream;
1658 streamRec.read = sk_stream_read;
1659 streamRec.close = sk_stream_close;
1661 args.flags = FT_OPEN_STREAM;
1662 args.stream = &streamRec;
1666 if (FT_Open_Face(library, &args, 0, &face)) {
1667 FT_Done_FreeType(library);
1671 int tempStyle = SkTypeface::kNormal;
1672 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1673 tempStyle |= SkTypeface::kBold;
1675 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1676 tempStyle |= SkTypeface::kItalic;
1680 name->set(face->family_name);
1683 *style = (SkTypeface::Style) tempStyle;
1686 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
1690 FT_Done_FreeType(library);