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