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