Home | History | Annotate | Download | only in ports
      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 "SkBitmap.h"
     19 #include "SkCanvas.h"
     20 #include "SkColorPriv.h"
     21 #include "SkDescriptor.h"
     22 #include "SkFDot6.h"
     23 #include "SkFontHost.h"
     24 #include "SkMask.h"
     25 #include "SkAdvancedTypefaceMetrics.h"
     26 #include "SkScalerContext.h"
     27 #include "SkStream.h"
     28 #include "SkString.h"
     29 #include "SkTemplates.h"
     30 #include "SkThread.h"
     31 
     32 #include <ft2build.h>
     33 #include FT_FREETYPE_H
     34 #include FT_OUTLINE_H
     35 #include FT_SIZES_H
     36 #include FT_TRUETYPE_TABLES_H
     37 #include FT_TYPE1_TABLES_H
     38 #include FT_BITMAP_H
     39 // In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
     40 #include FT_SYNTHESIS_H
     41 #include FT_XFREE86_H
     42 #include FT_LCD_FILTER_H
     43 
     44 #ifdef   FT_ADVANCES_H
     45 #include FT_ADVANCES_H
     46 #endif
     47 
     48 #if 0
     49 // Also include the files by name for build tools which require this.
     50 #include <freetype/freetype.h>
     51 #include <freetype/ftoutln.h>
     52 #include <freetype/ftsizes.h>
     53 #include <freetype/tttables.h>
     54 #include <freetype/ftadvanc.h>
     55 #include <freetype/ftlcdfil.h>
     56 #include <freetype/ftbitmap.h>
     57 #include <freetype/ftsynth.h>
     58 #endif
     59 
     60 //#define ENABLE_GLYPH_SPEW     // for tracing calls
     61 //#define DUMP_STRIKE_CREATION
     62 
     63 #ifdef SK_DEBUG
     64     #define SkASSERT_CONTINUE(pred)                                                         \
     65         do {                                                                                \
     66             if (!(pred))                                                                    \
     67                 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__);    \
     68         } while (false)
     69 #else
     70     #define SkASSERT_CONTINUE(pred)
     71 #endif
     72 
     73 using namespace skia_advanced_typeface_metrics_utils;
     74 
     75 // SK_FREETYPE_LCD_LERP should be 0...256
     76 //   0 means no color reduction (e.g. just as returned from FreeType)
     77 //   256 means 100% color reduction (e.g. gray)
     78 //
     79 #ifndef SK_FREETYPE_LCD_LERP
     80     #define SK_FREETYPE_LCD_LERP    96
     81 #endif
     82 
     83 //////////////////////////////////////////////////////////////////////////
     84 
     85 struct SkFaceRec;
     86 
     87 static SkMutex      gFTMutex;
     88 static int          gFTCount;
     89 static FT_Library   gFTLibrary;
     90 static SkFaceRec*   gFaceRecHead;
     91 static bool         gLCDSupportValid;  // true iff |gLCDSupport| has been set.
     92 static bool         gLCDSupport;  // true iff LCD is supported by the runtime.
     93 
     94 /////////////////////////////////////////////////////////////////////////
     95 
     96 // See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
     97 // This value was chosen by eyeballing the result in Firefox and trying to match it.
     98 static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
     99 
    100 static bool
    101 InitFreetype() {
    102     FT_Error err = FT_Init_FreeType(&gFTLibrary);
    103     if (err) {
    104         return false;
    105     }
    106 
    107     // Setup LCD filtering. This reduces colour fringes for LCD rendered
    108     // glyphs.
    109     err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
    110     gLCDSupport = err == 0;
    111     gLCDSupportValid = true;
    112 
    113     return true;
    114 }
    115 
    116 class SkScalerContext_FreeType : public SkScalerContext {
    117 public:
    118     SkScalerContext_FreeType(const SkDescriptor* desc);
    119     virtual ~SkScalerContext_FreeType();
    120 
    121     bool success() const {
    122         return fFaceRec != NULL &&
    123                fFTSize != NULL &&
    124                fFace != NULL;
    125     }
    126 
    127 protected:
    128     virtual unsigned generateGlyphCount();
    129     virtual uint16_t generateCharToGlyph(SkUnichar uni);
    130     virtual void generateAdvance(SkGlyph* glyph);
    131     virtual void generateMetrics(SkGlyph* glyph);
    132     virtual void generateImage(const SkGlyph& glyph);
    133     virtual void generatePath(const SkGlyph& glyph, SkPath* path);
    134     virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
    135                                      SkPaint::FontMetrics* my);
    136     virtual SkUnichar generateGlyphToChar(uint16_t glyph);
    137 
    138 private:
    139     SkFaceRec*  fFaceRec;
    140     FT_Face     fFace;              // reference to shared face in gFaceRecHead
    141     FT_Size     fFTSize;            // our own copy
    142     SkFixed     fScaleX, fScaleY;
    143     FT_Matrix   fMatrix22;
    144     uint32_t    fLoadGlyphFlags;
    145 
    146     FT_Error setupSize();
    147     void emboldenOutline(FT_Outline* outline);
    148 };
    149 
    150 ///////////////////////////////////////////////////////////////////////////
    151 ///////////////////////////////////////////////////////////////////////////
    152 
    153 #include "SkStream.h"
    154 
    155 struct SkFaceRec {
    156     SkFaceRec*      fNext;
    157     FT_Face         fFace;
    158     FT_StreamRec    fFTStream;
    159     SkStream*       fSkStream;
    160     uint32_t        fRefCnt;
    161     uint32_t        fFontID;
    162 
    163     // assumes ownership of the stream, will call unref() when its done
    164     SkFaceRec(SkStream* strm, uint32_t fontID);
    165     ~SkFaceRec() {
    166         fSkStream->unref();
    167     }
    168 };
    169 
    170 extern "C" {
    171     static unsigned long sk_stream_read(FT_Stream       stream,
    172                                         unsigned long   offset,
    173                                         unsigned char*  buffer,
    174                                         unsigned long   count ) {
    175         SkStream* str = (SkStream*)stream->descriptor.pointer;
    176 
    177         if (count) {
    178             if (!str->rewind()) {
    179                 return 0;
    180             } else {
    181                 unsigned long ret;
    182                 if (offset) {
    183                     ret = str->read(NULL, offset);
    184                     if (ret != offset) {
    185                         return 0;
    186                     }
    187                 }
    188                 ret = str->read(buffer, count);
    189                 if (ret != count) {
    190                     return 0;
    191                 }
    192                 count = ret;
    193             }
    194         }
    195         return count;
    196     }
    197 
    198     static void sk_stream_close( FT_Stream stream) {}
    199 }
    200 
    201 SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
    202         : fSkStream(strm), fFontID(fontID) {
    203 //    SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
    204 
    205     sk_bzero(&fFTStream, sizeof(fFTStream));
    206     fFTStream.size = fSkStream->getLength();
    207     fFTStream.descriptor.pointer = fSkStream;
    208     fFTStream.read  = sk_stream_read;
    209     fFTStream.close = sk_stream_close;
    210 }
    211 
    212 // Will return 0 on failure
    213 static SkFaceRec* ref_ft_face(uint32_t fontID) {
    214     SkFaceRec* rec = gFaceRecHead;
    215     while (rec) {
    216         if (rec->fFontID == fontID) {
    217             SkASSERT(rec->fFace);
    218             rec->fRefCnt += 1;
    219             return rec;
    220         }
    221         rec = rec->fNext;
    222     }
    223 
    224     SkStream* strm = SkFontHost::OpenStream(fontID);
    225     if (NULL == strm) {
    226         SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
    227         return 0;
    228     }
    229 
    230     // this passes ownership of strm to the rec
    231     rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
    232 
    233     FT_Open_Args    args;
    234     memset(&args, 0, sizeof(args));
    235     const void* memoryBase = strm->getMemoryBase();
    236 
    237     if (NULL != memoryBase) {
    238 //printf("mmap(%s)\n", keyString.c_str());
    239         args.flags = FT_OPEN_MEMORY;
    240         args.memory_base = (const FT_Byte*)memoryBase;
    241         args.memory_size = strm->getLength();
    242     } else {
    243 //printf("fopen(%s)\n", keyString.c_str());
    244         args.flags = FT_OPEN_STREAM;
    245         args.stream = &rec->fFTStream;
    246     }
    247 
    248     int face_index;
    249     int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
    250     FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
    251                                 &rec->fFace);
    252 
    253     if (err) {    // bad filename, try the default font
    254         fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
    255         SkDELETE(rec);
    256         return 0;
    257     } else {
    258         SkASSERT(rec->fFace);
    259         //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
    260         rec->fNext = gFaceRecHead;
    261         gFaceRecHead = rec;
    262         rec->fRefCnt = 1;
    263         return rec;
    264     }
    265 }
    266 
    267 static void unref_ft_face(FT_Face face) {
    268     SkFaceRec*  rec = gFaceRecHead;
    269     SkFaceRec*  prev = NULL;
    270     while (rec) {
    271         SkFaceRec* next = rec->fNext;
    272         if (rec->fFace == face) {
    273             if (--rec->fRefCnt == 0) {
    274                 if (prev) {
    275                     prev->fNext = next;
    276                 } else {
    277                     gFaceRecHead = next;
    278                 }
    279                 FT_Done_Face(face);
    280                 SkDELETE(rec);
    281             }
    282             return;
    283         }
    284         prev = rec;
    285         rec = next;
    286     }
    287     SkASSERT("shouldn't get here, face not in list");
    288 }
    289 
    290 ///////////////////////////////////////////////////////////////////////////
    291 
    292 // Work around for old versions of freetype.
    293 static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
    294                            FT_Int32 loadFlags, FT_Fixed* advances) {
    295 #ifdef FT_ADVANCES_H
    296     return FT_Get_Advances(face, start, count, loadFlags, advances);
    297 #else
    298     if (!face || start >= face->num_glyphs ||
    299             start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
    300         return 6;  // "Invalid argument."
    301     }
    302     if (count == 0)
    303         return 0;
    304 
    305     for (int i = 0; i < count; i++) {
    306         FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
    307         if (err)
    308             return err;
    309         advances[i] = face->glyph->advance.x;
    310     }
    311 
    312     return 0;
    313 #endif
    314 }
    315 
    316 static bool canEmbed(FT_Face face) {
    317 #ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
    318     FT_UShort fsType = FT_Get_FSType_Flags(face);
    319     return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
    320                       FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
    321 #else
    322     // No embedding is 0x2 and bitmap embedding only is 0x200.
    323     TT_OS2* os2_table;
    324     if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
    325         return (os2_table->fsType & 0x202) == 0;
    326     }
    327     return false;  // We tried, fail safe.
    328 #endif
    329 }
    330 
    331 static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
    332     const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
    333     if (!glyph_id)
    334         return false;
    335     FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
    336     FT_Outline_Get_CBox(&face->glyph->outline, bbox);
    337     return true;
    338 }
    339 
    340 static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
    341     FT_Fixed advance = 0;
    342     if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
    343         return false;
    344     }
    345     SkASSERT(data);
    346     *data = advance;
    347     return true;
    348 }
    349 
    350 static void populate_glyph_to_unicode(FT_Face& face,
    351                                       SkTDArray<SkUnichar>* glyphToUnicode) {
    352     // Check and see if we have Unicode cmaps.
    353     for (int i = 0; i < face->num_charmaps; ++i) {
    354         // CMaps known to support Unicode:
    355         // Platform ID   Encoding ID   Name
    356         // -----------   -----------   -----------------------------------
    357         // 0             0,1           Apple Unicode
    358         // 0             3             Apple Unicode 2.0 (preferred)
    359         // 3             1             Microsoft Unicode UCS-2
    360         // 3             10            Microsoft Unicode UCS-4 (preferred)
    361         //
    362         // See Apple TrueType Reference Manual
    363         // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
    364         // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
    365         // Microsoft OpenType Specification
    366         // http://www.microsoft.com/typography/otspec/cmap.htm
    367 
    368         FT_UShort platformId = face->charmaps[i]->platform_id;
    369         FT_UShort encodingId = face->charmaps[i]->encoding_id;
    370 
    371         if (platformId != 0 && platformId != 3) {
    372             continue;
    373         }
    374         if (platformId == 3 && encodingId != 1 && encodingId != 10) {
    375             continue;
    376         }
    377         bool preferredMap = ((platformId == 3 && encodingId == 10) ||
    378                              (platformId == 0 && encodingId == 3));
    379 
    380         FT_Set_Charmap(face, face->charmaps[i]);
    381         if (glyphToUnicode->isEmpty()) {
    382             glyphToUnicode->setCount(face->num_glyphs);
    383             memset(glyphToUnicode->begin(), 0,
    384                    sizeof(SkUnichar) * face->num_glyphs);
    385         }
    386 
    387         // Iterate through each cmap entry.
    388         FT_UInt glyphIndex;
    389         for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
    390              glyphIndex != 0;
    391              charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
    392             if (charCode &&
    393                     ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
    394                 (*glyphToUnicode)[glyphIndex] = charCode;
    395             }
    396         }
    397     }
    398 }
    399 
    400 // static
    401 SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
    402         uint32_t fontID,
    403         SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo) {
    404 #if defined(SK_BUILD_FOR_MAC) || defined(ANDROID)
    405     return NULL;
    406 #else
    407     SkAutoMutexAcquire ac(gFTMutex);
    408     FT_Library libInit = NULL;
    409     if (gFTCount == 0) {
    410         if (!InitFreetype())
    411             sk_throw();
    412         libInit = gFTLibrary;
    413     }
    414     SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
    415     SkFaceRec* rec = ref_ft_face(fontID);
    416     if (NULL == rec)
    417         return NULL;
    418     FT_Face face = rec->fFace;
    419 
    420     SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
    421     info->fFontName.set(FT_Get_Postscript_Name(face));
    422     info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
    423     info->fLastGlyphID = face->num_glyphs - 1;
    424     info->fEmSize = 1000;
    425 
    426     bool cid = false;
    427     const char* fontType = FT_Get_X11_Font_Format(face);
    428     if (strcmp(fontType, "Type 1") == 0) {
    429         info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
    430     } else if (strcmp(fontType, "CID Type 1") == 0) {
    431         info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
    432         cid = true;
    433     } else if (strcmp(fontType, "CFF") == 0) {
    434         info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
    435     } else if (strcmp(fontType, "TrueType") == 0) {
    436         info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
    437         cid = true;
    438         TT_Header* ttHeader;
    439         if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
    440                                                       ft_sfnt_head)) != NULL) {
    441             info->fEmSize = ttHeader->Units_Per_EM;
    442         }
    443     }
    444 
    445     info->fStyle = 0;
    446     if (FT_IS_FIXED_WIDTH(face))
    447         info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
    448     if (face->style_flags & FT_STYLE_FLAG_ITALIC)
    449         info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
    450     // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
    451     // character set is a subset of 'Adobe standard Latin.'
    452     info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
    453 
    454     PS_FontInfoRec ps_info;
    455     TT_Postscript* tt_info;
    456     if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
    457         info->fItalicAngle = ps_info.italic_angle;
    458     } else if ((tt_info =
    459                 (TT_Postscript*)FT_Get_Sfnt_Table(face,
    460                                                   ft_sfnt_post)) != NULL) {
    461         info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
    462     } else {
    463         info->fItalicAngle = 0;
    464     }
    465 
    466     info->fAscent = face->ascender;
    467     info->fDescent = face->descender;
    468 
    469     // Figure out a good guess for StemV - Min width of i, I, !, 1.
    470     // This probably isn't very good with an italic font.
    471     int16_t min_width = SHRT_MAX;
    472     info->fStemV = 0;
    473     char stem_chars[] = {'i', 'I', '!', '1'};
    474     for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
    475         FT_BBox bbox;
    476         if (GetLetterCBox(face, stem_chars[i], &bbox)) {
    477             int16_t width = bbox.xMax - bbox.xMin;
    478             if (width > 0 && width < min_width) {
    479                 min_width = width;
    480                 info->fStemV = min_width;
    481             }
    482         }
    483     }
    484 
    485     TT_PCLT* pclt_info;
    486     TT_OS2* os2_table;
    487     if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
    488         info->fCapHeight = pclt_info->CapHeight;
    489         uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
    490         if (serif_style >= 2 && serif_style <= 6)
    491             info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
    492         else if (serif_style >= 9 && serif_style <= 12)
    493             info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
    494     } else if ((os2_table =
    495                 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
    496         info->fCapHeight = os2_table->sCapHeight;
    497     } else {
    498         // Figure out a good guess for CapHeight: average the height of M and X.
    499         FT_BBox m_bbox, x_bbox;
    500         bool got_m, got_x;
    501         got_m = GetLetterCBox(face, 'M', &m_bbox);
    502         got_x = GetLetterCBox(face, 'X', &x_bbox);
    503         if (got_m && got_x) {
    504             info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
    505                     x_bbox.yMin) / 2;
    506         } else if (got_m && !got_x) {
    507             info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
    508         } else if (!got_m && got_x) {
    509             info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
    510         }
    511     }
    512 
    513     info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
    514                                     face->bbox.xMax, face->bbox.yMin);
    515 
    516     if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
    517             info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
    518         perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
    519     }
    520 
    521     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
    522         if (FT_IS_FIXED_WIDTH(face)) {
    523             appendRange(&info->fGlyphWidths, 0);
    524             int16_t advance = face->max_advance_width;
    525             info->fGlyphWidths->fAdvance.append(1, &advance);
    526             finishRange(info->fGlyphWidths.get(), 0,
    527                         SkAdvancedTypefaceMetrics::WidthRange::kDefault);
    528         } else if (!cid) {
    529             appendRange(&info->fGlyphWidths, 0);
    530             // So as to not blow out the stack, get advances in batches.
    531             for (int gID = 0; gID < face->num_glyphs; gID += 128) {
    532                 FT_Fixed advances[128];
    533                 int advanceCount = 128;
    534                 if (gID + advanceCount > face->num_glyphs)
    535                     advanceCount = face->num_glyphs - gID + 1;
    536                 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
    537                             advances);
    538                 for (int i = 0; i < advanceCount; i++) {
    539                     int16_t advance = advances[gID + i];
    540                     info->fGlyphWidths->fAdvance.append(1, &advance);
    541                 }
    542             }
    543             finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
    544                         SkAdvancedTypefaceMetrics::WidthRange::kRange);
    545         } else {
    546             info->fGlyphWidths.reset(
    547                 getAdvanceData(face, face->num_glyphs, &getWidthAdvance));
    548         }
    549     }
    550 
    551     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
    552             FT_HAS_VERTICAL(face)) {
    553         SkASSERT(false);  // Not implemented yet.
    554     }
    555 
    556     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
    557             info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
    558         // Postscript fonts may contain more than 255 glyphs, so we end up
    559         // using multiple font descriptions with a glyph ordering.  Record
    560         // the name of each glyph.
    561         info->fGlyphNames.reset(
    562                 new SkAutoTArray<SkString>(face->num_glyphs));
    563         for (int gID = 0; gID < face->num_glyphs; gID++) {
    564             char glyphName[128];  // PS limit for names is 127 bytes.
    565             FT_Get_Glyph_Name(face, gID, glyphName, 128);
    566             info->fGlyphNames->get()[gID].set(glyphName);
    567         }
    568     }
    569 
    570     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
    571            info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
    572            face->num_charmaps) {
    573         populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
    574     }
    575 
    576     if (!canEmbed(face))
    577         info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
    578 
    579     unref_ft_face(face);
    580     return info;
    581 #endif
    582 }
    583 ///////////////////////////////////////////////////////////////////////////
    584 
    585 void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
    586     if (!gLCDSupportValid) {
    587         InitFreetype();
    588         FT_Done_FreeType(gFTLibrary);
    589     }
    590 
    591     if (!gLCDSupport && (rec->isLCD() || SkMask::kLCD16_Format == rec->fMaskFormat)) {
    592         // If the runtime Freetype library doesn't support LCD mode, we disable
    593         // it here.
    594         rec->fMaskFormat = SkMask::kA8_Format;
    595     }
    596 
    597     SkPaint::Hinting h = rec->getHinting();
    598     if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
    599         // collapse full->normal hinting if we're not doing LCD
    600         h = SkPaint::kNormal_Hinting;
    601     } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
    602                SkPaint::kNo_Hinting != h) {
    603         // to do subpixel, we must have at most slight hinting
    604         h = SkPaint::kSlight_Hinting;
    605     }
    606     rec->setHinting(h);
    607 }
    608 
    609 #ifdef ANDROID
    610 uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
    611     SkAutoMutexAcquire ac(gFTMutex);
    612     SkFaceRec *rec = ref_ft_face(fontID);
    613     uint16_t unitsPerEm = 0;
    614 
    615     if (rec != NULL && rec->fFace != NULL) {
    616         unitsPerEm = rec->fFace->units_per_EM;
    617         unref_ft_face(rec->fFace);
    618     }
    619 
    620     return (uint32_t)unitsPerEm;
    621 }
    622 #endif
    623 
    624 SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
    625         : SkScalerContext(desc) {
    626     SkAutoMutexAcquire  ac(gFTMutex);
    627 
    628     if (gFTCount == 0) {
    629         if (!InitFreetype()) {
    630             sk_throw();
    631         }
    632     }
    633     ++gFTCount;
    634 
    635     // load the font file
    636     fFTSize = NULL;
    637     fFace = NULL;
    638     fFaceRec = ref_ft_face(fRec.fFontID);
    639     if (NULL == fFaceRec) {
    640         return;
    641     }
    642     fFace = fFaceRec->fFace;
    643 
    644     // compute our factors from the record
    645 
    646     SkMatrix    m;
    647 
    648     fRec.getSingleMatrix(&m);
    649 
    650 #ifdef DUMP_STRIKE_CREATION
    651     SkString     keyString;
    652     SkFontHost::GetDescriptorKeyString(desc, &keyString);
    653     printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
    654            SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
    655            SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
    656            SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
    657            fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
    658 #endif
    659 
    660     //  now compute our scale factors
    661     SkScalar    sx = m.getScaleX();
    662     SkScalar    sy = m.getScaleY();
    663 
    664     if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
    665         // sort of give up on hinting
    666         sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
    667         sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
    668         sx = sy = SkScalarAve(sx, sy);
    669 
    670         SkScalar inv = SkScalarInvert(sx);
    671 
    672         // flip the skew elements to go from our Y-down system to FreeType's
    673         fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
    674         fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
    675         fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
    676         fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
    677     } else {
    678         fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
    679         fMatrix22.xy = fMatrix22.yx = 0;
    680     }
    681 
    682     fScaleX = SkScalarToFixed(sx);
    683     fScaleY = SkScalarToFixed(sy);
    684 
    685     // compute the flags we send to Load_Glyph
    686     {
    687         FT_Int32 loadFlags = FT_LOAD_DEFAULT;
    688 
    689         if (SkMask::kBW_Format == fRec.fMaskFormat) {
    690             // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
    691             loadFlags = FT_LOAD_TARGET_MONO;
    692             if (fRec.getHinting() == SkPaint::kNo_Hinting)
    693                 loadFlags = FT_LOAD_NO_HINTING;
    694         } else {
    695             switch (fRec.getHinting()) {
    696             case SkPaint::kNo_Hinting:
    697                 loadFlags = FT_LOAD_NO_HINTING;
    698                 break;
    699             case SkPaint::kSlight_Hinting:
    700                 loadFlags = FT_LOAD_TARGET_LIGHT;  // This implies FORCE_AUTOHINT
    701                 break;
    702             case SkPaint::kNormal_Hinting:
    703                 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
    704                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
    705                 else
    706                     loadFlags = FT_LOAD_NO_AUTOHINT;
    707                 break;
    708             case SkPaint::kFull_Hinting:
    709                 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
    710                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
    711                     break;
    712                 }
    713                 loadFlags = FT_LOAD_TARGET_NORMAL;
    714                 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat ||
    715                         SkMask::kLCD16_Format == fRec.fMaskFormat) {
    716                     loadFlags = FT_LOAD_TARGET_LCD;
    717                 } else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat) {
    718                     loadFlags = FT_LOAD_TARGET_LCD_V;
    719                 }
    720                 break;
    721             default:
    722                 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
    723                 break;
    724             }
    725         }
    726 
    727         if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
    728             loadFlags |= FT_LOAD_NO_BITMAP;
    729 
    730         // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
    731         // advances, as fontconfig and cairo do.
    732         // See http://code.google.com/p/skia/issues/detail?id=222.
    733         loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
    734 
    735         fLoadGlyphFlags = loadFlags;
    736     }
    737 
    738     // now create the FT_Size
    739 
    740     {
    741         FT_Error    err;
    742 
    743         err = FT_New_Size(fFace, &fFTSize);
    744         if (err != 0) {
    745             SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
    746                         fFaceRec->fFontID, fScaleX, fScaleY, err));
    747             fFace = NULL;
    748             return;
    749         }
    750 
    751         err = FT_Activate_Size(fFTSize);
    752         if (err != 0) {
    753             SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
    754                         fFaceRec->fFontID, fScaleX, fScaleY, err));
    755             fFTSize = NULL;
    756         }
    757 
    758         err = FT_Set_Char_Size( fFace,
    759                                 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
    760                                 72, 72);
    761         if (err != 0) {
    762             SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
    763                         fFaceRec->fFontID, fScaleX, fScaleY, err));
    764             fFace = NULL;
    765             return;
    766         }
    767 
    768         FT_Set_Transform( fFace, &fMatrix22, NULL);
    769     }
    770 }
    771 
    772 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
    773     if (fFTSize != NULL) {
    774         FT_Done_Size(fFTSize);
    775     }
    776 
    777     SkAutoMutexAcquire  ac(gFTMutex);
    778 
    779     if (fFace != NULL) {
    780         unref_ft_face(fFace);
    781     }
    782     if (--gFTCount == 0) {
    783 //        SkDEBUGF(("FT_Done_FreeType\n"));
    784         FT_Done_FreeType(gFTLibrary);
    785         SkDEBUGCODE(gFTLibrary = NULL;)
    786     }
    787 }
    788 
    789 /*  We call this before each use of the fFace, since we may be sharing
    790     this face with other context (at different sizes).
    791 */
    792 FT_Error SkScalerContext_FreeType::setupSize() {
    793     /*  In the off-chance that a font has been removed, we want to error out
    794         right away, so call resolve just to be sure.
    795 
    796         TODO: perhaps we can skip this, by walking the global font cache and
    797         killing all of the contexts when we know that a given fontID is going
    798         away...
    799      */
    800     if (!SkFontHost::ValidFontID(fRec.fFontID)) {
    801         return (FT_Error)-1;
    802     }
    803 
    804     FT_Error    err = FT_Activate_Size(fFTSize);
    805 
    806     if (err != 0) {
    807         SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
    808                     fFaceRec->fFontID, fScaleX, fScaleY, err));
    809         fFTSize = NULL;
    810     } else {
    811         // seems we need to reset this every time (not sure why, but without it
    812         // I get random italics from some other fFTSize)
    813         FT_Set_Transform( fFace, &fMatrix22, NULL);
    814     }
    815     return err;
    816 }
    817 
    818 void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
    819     FT_Pos strength;
    820     strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
    821                / 24;
    822     FT_Outline_Embolden(outline, strength);
    823 }
    824 
    825 unsigned SkScalerContext_FreeType::generateGlyphCount() {
    826     return fFace->num_glyphs;
    827 }
    828 
    829 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
    830     return SkToU16(FT_Get_Char_Index( fFace, uni ));
    831 }
    832 
    833 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
    834     // iterate through each cmap entry, looking for matching glyph indices
    835     FT_UInt glyphIndex;
    836     SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
    837 
    838     while (glyphIndex != 0) {
    839         if (glyphIndex == glyph) {
    840             return charCode;
    841         }
    842         charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
    843     }
    844 
    845     return 0;
    846 }
    847 
    848 static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
    849     switch (format) {
    850         case SkMask::kHorizontalLCD_Format:
    851         case SkMask::kVerticalLCD_Format:
    852             SkASSERT(!"An LCD format should never be passed here");
    853             return FT_PIXEL_MODE_GRAY;
    854         case SkMask::kBW_Format:
    855             return FT_PIXEL_MODE_MONO;
    856         case SkMask::kA8_Format:
    857         default:
    858             return FT_PIXEL_MODE_GRAY;
    859     }
    860 }
    861 
    862 void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
    863 #ifdef FT_ADVANCES_H
    864    /* unhinted and light hinted text have linearly scaled advances
    865     * which are very cheap to compute with some font formats...
    866     */
    867     {
    868         SkAutoMutexAcquire  ac(gFTMutex);
    869 
    870         if (this->setupSize()) {
    871             glyph->zeroMetrics();
    872             return;
    873         }
    874 
    875         FT_Error    error;
    876         FT_Fixed    advance;
    877 
    878         error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
    879                                 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
    880                                 &advance );
    881         if (0 == error) {
    882             glyph->fRsbDelta = 0;
    883             glyph->fLsbDelta = 0;
    884             glyph->fAdvanceX = advance;  // advance *2/3; //DEBUG
    885             glyph->fAdvanceY = 0;
    886             return;
    887         }
    888     }
    889 #endif /* FT_ADVANCES_H */
    890     /* otherwise, we need to load/hint the glyph, which is slower */
    891     this->generateMetrics(glyph);
    892     return;
    893 }
    894 
    895 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
    896     SkAutoMutexAcquire  ac(gFTMutex);
    897 
    898     glyph->fRsbDelta = 0;
    899     glyph->fLsbDelta = 0;
    900 
    901     FT_Error    err;
    902 
    903     if (this->setupSize()) {
    904         goto ERROR;
    905     }
    906 
    907     err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
    908     if (err != 0) {
    909         SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
    910                     fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
    911     ERROR:
    912         glyph->zeroMetrics();
    913         return;
    914     }
    915 
    916     switch ( fFace->glyph->format ) {
    917       case FT_GLYPH_FORMAT_OUTLINE: {
    918         FT_BBox bbox;
    919 
    920         if (fRec.fFlags & kEmbolden_Flag) {
    921             emboldenOutline(&fFace->glyph->outline);
    922         }
    923         FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
    924 
    925         if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
    926             int dx = glyph->getSubXFixed() >> 10;
    927             int dy = glyph->getSubYFixed() >> 10;
    928             // negate dy since freetype-y-goes-up and skia-y-goes-down
    929             bbox.xMin += dx;
    930             bbox.yMin -= dy;
    931             bbox.xMax += dx;
    932             bbox.yMax -= dy;
    933         }
    934 
    935         bbox.xMin &= ~63;
    936         bbox.yMin &= ~63;
    937         bbox.xMax  = (bbox.xMax + 63) & ~63;
    938         bbox.yMax  = (bbox.yMax + 63) & ~63;
    939 
    940         glyph->fWidth   = SkToU16((bbox.xMax - bbox.xMin) >> 6);
    941         glyph->fHeight  = SkToU16((bbox.yMax - bbox.yMin) >> 6);
    942         glyph->fTop     = -SkToS16(bbox.yMax >> 6);
    943         glyph->fLeft    = SkToS16(bbox.xMin >> 6);
    944         break;
    945       }
    946 
    947       case FT_GLYPH_FORMAT_BITMAP:
    948         if (fRec.fFlags & kEmbolden_Flag) {
    949             FT_GlyphSlot_Own_Bitmap(fFace->glyph);
    950             FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
    951         }
    952         glyph->fWidth   = SkToU16(fFace->glyph->bitmap.width);
    953         glyph->fHeight  = SkToU16(fFace->glyph->bitmap.rows);
    954         glyph->fTop     = -SkToS16(fFace->glyph->bitmap_top);
    955         glyph->fLeft    = SkToS16(fFace->glyph->bitmap_left);
    956         break;
    957 
    958       default:
    959         SkASSERT(!"unknown glyph format");
    960         goto ERROR;
    961     }
    962 
    963     if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
    964         glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
    965         glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
    966         if (fRec.fFlags & kDevKernText_Flag) {
    967             glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
    968             glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
    969         }
    970     } else {
    971         glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
    972         glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
    973     }
    974 
    975 #ifdef ENABLE_GLYPH_SPEW
    976     SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
    977     SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
    978 #endif
    979 }
    980 
    981 #if defined(SK_SUPPORT_LCDTEXT)
    982 namespace skia_freetype_support {
    983 // extern functions from SkFontHost_FreeType_Subpixel
    984 extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
    985 extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
    986 }
    987 
    988 using namespace skia_freetype_support;
    989 #endif
    990 
    991 static int lerp(int start, int end) {
    992     SkASSERT((unsigned)SK_FREETYPE_LCD_LERP <= 256);
    993     return start + ((end - start) * (SK_FREETYPE_LCD_LERP) >> 8);
    994 }
    995 
    996 static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
    997     if (SK_FREETYPE_LCD_LERP) {
    998         // want (a+b+c)/3, but we approx to avoid the divide
    999         unsigned ave = (5 * (r + g + b) + b) >> 4;
   1000         r = lerp(r, ave);
   1001         g = lerp(g, ave);
   1002         b = lerp(b, ave);
   1003     }
   1004     return SkPackRGB16(r >> 3, g >> 2, b >> 3);
   1005 }
   1006 
   1007 static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap) {
   1008     SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
   1009     SkASSERT(glyph.fHeight == bitmap.rows);
   1010 
   1011     const uint8_t* src = bitmap.buffer + 3;
   1012     uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
   1013     size_t dstRB = glyph.rowBytes();
   1014     int width = glyph.fWidth;
   1015 
   1016     for (int y = 0; y < glyph.fHeight; y++) {
   1017         const uint8_t* triple = src;
   1018         for (int x = 0; x < width; x++) {
   1019             dst[x] = packTriple(triple[0], triple[1], triple[2]);
   1020             triple += 3;
   1021         }
   1022         src += bitmap.pitch;
   1023         dst = (uint16_t*)((char*)dst + dstRB);
   1024     }
   1025 }
   1026 
   1027 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
   1028     SkAutoMutexAcquire  ac(gFTMutex);
   1029 
   1030     FT_Error    err;
   1031 
   1032     if (this->setupSize()) {
   1033         goto ERROR;
   1034     }
   1035 
   1036     err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
   1037     if (err != 0) {
   1038         SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
   1039                     glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
   1040     ERROR:
   1041         memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
   1042         return;
   1043     }
   1044 
   1045     const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
   1046                                fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
   1047 
   1048     switch ( fFace->glyph->format ) {
   1049         case FT_GLYPH_FORMAT_OUTLINE: {
   1050             FT_Outline* outline = &fFace->glyph->outline;
   1051             FT_BBox     bbox;
   1052             FT_Bitmap   target;
   1053 
   1054             if (fRec.fFlags & kEmbolden_Flag) {
   1055                 emboldenOutline(outline);
   1056             }
   1057 
   1058             int dx = 0, dy = 0;
   1059             if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
   1060                 dx = glyph.getSubXFixed() >> 10;
   1061                 dy = glyph.getSubYFixed() >> 10;
   1062                 // negate dy since freetype-y-goes-up and skia-y-goes-down
   1063                 dy = -dy;
   1064             }
   1065             FT_Outline_Get_CBox(outline, &bbox);
   1066             /*
   1067                 what we really want to do for subpixel is
   1068                     offset(dx, dy)
   1069                     compute_bounds
   1070                     offset(bbox & !63)
   1071                 but that is two calls to offset, so we do the following, which
   1072                 achieves the same thing with only one offset call.
   1073             */
   1074             FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
   1075                                           dy - ((bbox.yMin + dy) & ~63));
   1076 
   1077 #if defined(SK_SUPPORT_LCDTEXT)
   1078             if (lcdRenderMode) {
   1079                 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
   1080                 // we have to call FT_Render_Glyph and memcpy the image out.
   1081                 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
   1082                 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
   1083                 FT_Render_Glyph(fFace->glyph, mode);
   1084 
   1085                 if (isVertical)
   1086                     CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
   1087                 else
   1088                     CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
   1089 
   1090                 break;
   1091             }
   1092 #endif
   1093 
   1094             if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
   1095                 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
   1096                 copyFT2LCD16(glyph, fFace->glyph->bitmap);
   1097             } else {
   1098                 target.width = glyph.fWidth;
   1099                 target.rows = glyph.fHeight;
   1100                 target.pitch = glyph.rowBytes();
   1101                 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
   1102                 target.pixel_mode = compute_pixel_mode(
   1103                                                 (SkMask::Format)fRec.fMaskFormat);
   1104                 target.num_grays = 256;
   1105 
   1106                 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
   1107                 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
   1108             }
   1109         } break;
   1110 
   1111         case FT_GLYPH_FORMAT_BITMAP: {
   1112             if (fRec.fFlags & kEmbolden_Flag) {
   1113                 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
   1114                 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
   1115             }
   1116             SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
   1117             SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
   1118             SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
   1119             SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
   1120 
   1121             const uint8_t*  src = (const uint8_t*)fFace->glyph->bitmap.buffer;
   1122             uint8_t*        dst = (uint8_t*)glyph.fImage;
   1123 
   1124             if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
   1125                 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
   1126                  glyph.fMaskFormat == SkMask::kBW_Format)) {
   1127                 unsigned    srcRowBytes = fFace->glyph->bitmap.pitch;
   1128                 unsigned    dstRowBytes = glyph.rowBytes();
   1129                 unsigned    minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
   1130                 unsigned    extraRowBytes = dstRowBytes - minRowBytes;
   1131 
   1132                 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
   1133                     memcpy(dst, src, minRowBytes);
   1134                     memset(dst + minRowBytes, 0, extraRowBytes);
   1135                     src += srcRowBytes;
   1136                     dst += dstRowBytes;
   1137                 }
   1138             } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
   1139                        (glyph.fMaskFormat == SkMask::kA8_Format ||
   1140                         glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
   1141                         glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
   1142                 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
   1143                     uint8_t byte = 0;
   1144                     int bits = 0;
   1145                     const uint8_t* src_row = src;
   1146                     uint8_t* dst_row = dst;
   1147 
   1148                     for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
   1149                         if (!bits) {
   1150                             byte = *src_row++;
   1151                             bits = 8;
   1152                         }
   1153 
   1154                         *dst_row++ = byte & 0x80 ? 0xff : 0;
   1155                         bits--;
   1156                         byte <<= 1;
   1157                     }
   1158 
   1159                     src += fFace->glyph->bitmap.pitch;
   1160                     dst += glyph.rowBytes();
   1161                 }
   1162             } else {
   1163               SkASSERT(!"unknown glyph bitmap transform needed");
   1164             }
   1165 
   1166             if (lcdRenderMode)
   1167                 glyph.expandA8ToLCD();
   1168 
   1169         } break;
   1170 
   1171     default:
   1172         SkASSERT(!"unknown glyph format");
   1173         goto ERROR;
   1174     }
   1175 }
   1176 
   1177 ///////////////////////////////////////////////////////////////////////////////
   1178 
   1179 #define ft2sk(x)    SkFixedToScalar((x) << 10)
   1180 
   1181 #if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
   1182     #define CONST_PARAM const
   1183 #else   // older freetype doesn't use const here
   1184     #define CONST_PARAM
   1185 #endif
   1186 
   1187 static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
   1188     SkPath* path = (SkPath*)ctx;
   1189     path->close();  // to close the previous contour (if any)
   1190     path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
   1191     return 0;
   1192 }
   1193 
   1194 static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
   1195     SkPath* path = (SkPath*)ctx;
   1196     path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
   1197     return 0;
   1198 }
   1199 
   1200 static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
   1201                      void* ctx) {
   1202     SkPath* path = (SkPath*)ctx;
   1203     path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
   1204     return 0;
   1205 }
   1206 
   1207 static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
   1208                       CONST_PARAM FT_Vector* pt2, void* ctx) {
   1209     SkPath* path = (SkPath*)ctx;
   1210     path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
   1211                   -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
   1212     return 0;
   1213 }
   1214 
   1215 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
   1216                                             SkPath* path) {
   1217     SkAutoMutexAcquire  ac(gFTMutex);
   1218 
   1219     SkASSERT(&glyph && path);
   1220 
   1221     if (this->setupSize()) {
   1222         path->reset();
   1223         return;
   1224     }
   1225 
   1226     uint32_t flags = fLoadGlyphFlags;
   1227     flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
   1228     flags &= ~FT_LOAD_RENDER;   // don't scan convert (we just want the outline)
   1229 
   1230     FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
   1231 
   1232     if (err != 0) {
   1233         SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
   1234                     glyph.getGlyphID(fBaseGlyphCount), flags, err));
   1235         path->reset();
   1236         return;
   1237     }
   1238 
   1239     if (fRec.fFlags & kEmbolden_Flag) {
   1240         emboldenOutline(&fFace->glyph->outline);
   1241     }
   1242 
   1243     FT_Outline_Funcs    funcs;
   1244 
   1245     funcs.move_to   = move_proc;
   1246     funcs.line_to   = line_proc;
   1247     funcs.conic_to  = quad_proc;
   1248     funcs.cubic_to  = cubic_proc;
   1249     funcs.shift     = 0;
   1250     funcs.delta     = 0;
   1251 
   1252     err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
   1253 
   1254     if (err != 0) {
   1255         SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
   1256                     glyph.getGlyphID(fBaseGlyphCount), flags, err));
   1257         path->reset();
   1258         return;
   1259     }
   1260 
   1261     path->close();
   1262 }
   1263 
   1264 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
   1265                                                    SkPaint::FontMetrics* my) {
   1266     if (NULL == mx && NULL == my) {
   1267         return;
   1268     }
   1269 
   1270     SkAutoMutexAcquire  ac(gFTMutex);
   1271 
   1272     if (this->setupSize()) {
   1273         ERROR:
   1274         if (mx) {
   1275             sk_bzero(mx, sizeof(SkPaint::FontMetrics));
   1276         }
   1277         if (my) {
   1278             sk_bzero(my, sizeof(SkPaint::FontMetrics));
   1279         }
   1280         return;
   1281     }
   1282 
   1283     FT_Face face = fFace;
   1284     int upem = face->units_per_EM;
   1285     if (upem <= 0) {
   1286         goto ERROR;
   1287     }
   1288 
   1289     SkPoint pts[6];
   1290     SkFixed ys[6];
   1291     SkFixed scaleY = fScaleY;
   1292     SkFixed mxy = fMatrix22.xy;
   1293     SkFixed myy = fMatrix22.yy;
   1294     SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
   1295     SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
   1296 
   1297     int leading = face->height - (face->ascender + -face->descender);
   1298     if (leading < 0) {
   1299         leading = 0;
   1300     }
   1301 
   1302     // Try to get the OS/2 table from the font. This contains the specific
   1303     // average font width metrics which Windows uses.
   1304     TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
   1305 
   1306     ys[0] = -face->bbox.yMax;
   1307     ys[1] = -face->ascender;
   1308     ys[2] = -face->descender;
   1309     ys[3] = -face->bbox.yMin;
   1310     ys[4] = leading;
   1311     ys[5] = os2 ? os2->xAvgCharWidth : 0;
   1312 
   1313     SkScalar x_height;
   1314     if (os2 && os2->sxHeight) {
   1315         x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
   1316     } else {
   1317         const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
   1318         if (x_glyph) {
   1319             FT_BBox bbox;
   1320             FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
   1321             if (fRec.fFlags & kEmbolden_Flag) {
   1322                 emboldenOutline(&fFace->glyph->outline);
   1323             }
   1324             FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
   1325             x_height = SkIntToScalar(bbox.yMax) / 64;
   1326         } else {
   1327             x_height = 0;
   1328         }
   1329     }
   1330 
   1331     // convert upem-y values into scalar points
   1332     for (int i = 0; i < 6; i++) {
   1333         SkFixed y = SkMulDiv(scaleY, ys[i], upem);
   1334         SkFixed x = SkFixedMul(mxy, y);
   1335         y = SkFixedMul(myy, y);
   1336         pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
   1337     }
   1338 
   1339     if (mx) {
   1340         mx->fTop = pts[0].fX;
   1341         mx->fAscent = pts[1].fX;
   1342         mx->fDescent = pts[2].fX;
   1343         mx->fBottom = pts[3].fX;
   1344         mx->fLeading = pts[4].fX;
   1345         mx->fAvgCharWidth = pts[5].fX;
   1346         mx->fXMin = xmin;
   1347         mx->fXMax = xmax;
   1348         mx->fXHeight = x_height;
   1349     }
   1350     if (my) {
   1351         my->fTop = pts[0].fY;
   1352         my->fAscent = pts[1].fY;
   1353         my->fDescent = pts[2].fY;
   1354         my->fBottom = pts[3].fY;
   1355         my->fLeading = pts[4].fY;
   1356         my->fAvgCharWidth = pts[5].fY;
   1357         my->fXMin = xmin;
   1358         my->fXMax = xmax;
   1359         my->fXHeight = x_height;
   1360     }
   1361 }
   1362 
   1363 ////////////////////////////////////////////////////////////////////////
   1364 ////////////////////////////////////////////////////////////////////////
   1365 
   1366 SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
   1367     SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
   1368     if (!c->success()) {
   1369         SkDELETE(c);
   1370         c = NULL;
   1371     }
   1372     return c;
   1373 }
   1374 
   1375 ///////////////////////////////////////////////////////////////////////////////
   1376 
   1377 /*  Export this so that other parts of our FonttHost port can make use of our
   1378     ability to extract the name+style from a stream, using FreeType's api.
   1379 */
   1380 SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
   1381                                            bool* isFixedWidth) {
   1382     FT_Library  library;
   1383     if (FT_Init_FreeType(&library)) {
   1384         name->reset();
   1385         return SkTypeface::kNormal;
   1386     }
   1387 
   1388     FT_Open_Args    args;
   1389     memset(&args, 0, sizeof(args));
   1390 
   1391     const void* memoryBase = stream->getMemoryBase();
   1392     FT_StreamRec    streamRec;
   1393 
   1394     if (NULL != memoryBase) {
   1395         args.flags = FT_OPEN_MEMORY;
   1396         args.memory_base = (const FT_Byte*)memoryBase;
   1397         args.memory_size = stream->getLength();
   1398     } else {
   1399         memset(&streamRec, 0, sizeof(streamRec));
   1400         streamRec.size = stream->read(NULL, 0);
   1401         streamRec.descriptor.pointer = stream;
   1402         streamRec.read  = sk_stream_read;
   1403         streamRec.close = sk_stream_close;
   1404 
   1405         args.flags = FT_OPEN_STREAM;
   1406         args.stream = &streamRec;
   1407     }
   1408 
   1409     FT_Face face;
   1410     if (FT_Open_Face(library, &args, 0, &face)) {
   1411         FT_Done_FreeType(library);
   1412         name->reset();
   1413         return SkTypeface::kNormal;
   1414     }
   1415 
   1416     name->set(face->family_name);
   1417     int style = SkTypeface::kNormal;
   1418 
   1419     if (face->style_flags & FT_STYLE_FLAG_BOLD) {
   1420         style |= SkTypeface::kBold;
   1421     }
   1422     if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
   1423         style |= SkTypeface::kItalic;
   1424     }
   1425     if (isFixedWidth) {
   1426         *isFixedWidth = FT_IS_FIXED_WIDTH(face);
   1427     }
   1428 
   1429     FT_Done_Face(face);
   1430     FT_Done_FreeType(library);
   1431     return (SkTypeface::Style)style;
   1432 }
   1433