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