• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
10 #include "SkBitmap.h"
11 #include "SkCanvas.h"
12 #include "SkColorPriv.h"
13 #include "SkDescriptor.h"
14 #include "SkFDot6.h"
15 #include "SkFontHost.h"
16 #include "SkMask.h"
17 #include "SkAdvancedTypefaceMetrics.h"
18 #include "SkScalerContext.h"
19 #include "SkStream.h"
20 #include "SkString.h"
21 #include "SkTemplates.h"
22 #include "SkThread.h"
23 
24 #include <ft2build.h>
25 #include FT_FREETYPE_H
26 #include FT_OUTLINE_H
27 #include FT_SIZES_H
28 #include FT_TRUETYPE_TABLES_H
29 #include FT_TYPE1_TABLES_H
30 #include FT_BITMAP_H
31 // In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
32 #include FT_SYNTHESIS_H
33 #include FT_XFREE86_H
34 #ifdef FT_LCD_FILTER_H
35 #include FT_LCD_FILTER_H
36 #endif
37 
38 #ifdef   FT_ADVANCES_H
39 #include FT_ADVANCES_H
40 #endif
41 
42 #if 0
43 // Also include the files by name for build tools which require this.
44 #include <freetype/freetype.h>
45 #include <freetype/ftoutln.h>
46 #include <freetype/ftsizes.h>
47 #include <freetype/tttables.h>
48 #include <freetype/ftadvanc.h>
49 #include <freetype/ftlcdfil.h>
50 #include <freetype/ftbitmap.h>
51 #include <freetype/ftsynth.h>
52 #endif
53 
54 //#define ENABLE_GLYPH_SPEW     // for tracing calls
55 //#define DUMP_STRIKE_CREATION
56 
57 //#define SK_GAMMA_APPLY_TO_A8
58 
59 #ifndef SK_GAMMA_CONTRAST
60     #define SK_GAMMA_CONTRAST   0x66
61 #endif
62 #ifndef SK_GAMMA_EXPONENT
63     #define SK_GAMMA_EXPONENT   2.2
64 #endif
65 
66 // hand-tuned value to reduce outline embolden strength
67 #ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
68     #ifdef SK_BUILD_FOR_ANDROID
69         #define SK_OUTLINE_EMBOLDEN_DIVISOR   34
70     #else
71         #define SK_OUTLINE_EMBOLDEN_DIVISOR   24
72     #endif
73 #endif
74 
75 
76 #ifdef SK_DEBUG
77     #define SkASSERT_CONTINUE(pred)                                                         \
78         do {                                                                                \
79             if (!(pred))                                                                    \
80                 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__);    \
81         } while (false)
82 #else
83     #define SkASSERT_CONTINUE(pred)
84 #endif
85 
86 using namespace skia_advanced_typeface_metrics_utils;
87 
isLCD(const SkScalerContext::Rec & rec)88 static bool isLCD(const SkScalerContext::Rec& rec) {
89     switch (rec.fMaskFormat) {
90         case SkMask::kLCD16_Format:
91         case SkMask::kLCD32_Format:
92             return true;
93         default:
94             return false;
95     }
96 }
97 
98 //////////////////////////////////////////////////////////////////////////
99 
100 struct SkFaceRec;
101 
102 SK_DECLARE_STATIC_MUTEX(gFTMutex);
103 static int          gFTCount;
104 static FT_Library   gFTLibrary;
105 static SkFaceRec*   gFaceRecHead;
106 static bool         gLCDSupportValid;  // true iff |gLCDSupport| has been set.
107 static bool         gLCDSupport;  // true iff LCD is supported by the runtime.
108 static int          gLCDExtra;  // number of extra pixels for filtering.
109 
110 static const uint8_t* gGammaTables[2];
111 
112 /////////////////////////////////////////////////////////////////////////
113 
114 // See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
115 // This value was chosen by eyeballing the result in Firefox and trying to match it.
116 static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
117 
118 // convert from Skia's fixed (16.16) to FreeType's fixed (26.6) representation
FixedToDot6(SkFixed x)119 static inline int FixedToDot6(SkFixed x) { return x >> 10; }
120 // convert from FreeType's fixed (26.6) to Skia's fixed (16.16) representation
Dot6ToFixed(int x)121 static inline SkFixed Dot6ToFixed(int x) { return x << 10; }
122 
123 static bool
InitFreetype()124 InitFreetype() {
125     FT_Error err = FT_Init_FreeType(&gFTLibrary);
126     if (err) {
127         return false;
128     }
129 
130     // Setup LCD filtering. This reduces colour fringes for LCD rendered
131     // glyphs.
132 #ifdef FT_LCD_FILTER_H
133 //    err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
134     err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_LIGHT);
135     gLCDSupport = err == 0;
136     if (gLCDSupport) {
137         gLCDExtra = 2; //DEFAULT and LIGHT add one pixel to each side.
138     }
139 #else
140     gLCDSupport = false;
141 #endif
142     gLCDSupportValid = true;
143 
144     return true;
145 }
146 
147 class SkScalerContext_FreeType : public SkScalerContext {
148 public:
149     SkScalerContext_FreeType(const SkDescriptor* desc);
150     virtual ~SkScalerContext_FreeType();
151 
success() const152     bool success() const {
153         return fFaceRec != NULL &&
154                fFTSize != NULL &&
155                fFace != NULL;
156     }
157 
158 protected:
159     virtual unsigned generateGlyphCount();
160     virtual uint16_t generateCharToGlyph(SkUnichar uni);
161     virtual void generateAdvance(SkGlyph* glyph);
162     virtual void generateMetrics(SkGlyph* glyph);
163     virtual void generateImage(const SkGlyph& glyph);
164     virtual void generatePath(const SkGlyph& glyph, SkPath* path);
165     virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
166                                      SkPaint::FontMetrics* my);
167     virtual SkUnichar generateGlyphToChar(uint16_t glyph);
168 
169 private:
170     SkFaceRec*  fFaceRec;
171     FT_Face     fFace;              // reference to shared face in gFaceRecHead
172     FT_Size     fFTSize;            // our own copy
173     SkFixed     fScaleX, fScaleY;
174     FT_Matrix   fMatrix22;
175     uint32_t    fLoadGlyphFlags;
176     bool        fDoLinearMetrics;
177     bool        fUseVertMetrics;
178 
179     FT_Error setupSize();
180     void emboldenOutline(FT_Outline* outline);
181     void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
182                                 bool snapToPixelBoundary = false);
183     void updateGlyphIfLCD(SkGlyph* glyph);
184 };
185 
186 ///////////////////////////////////////////////////////////////////////////
187 ///////////////////////////////////////////////////////////////////////////
188 
189 #include "SkStream.h"
190 
191 struct SkFaceRec {
192     SkFaceRec*      fNext;
193     FT_Face         fFace;
194     FT_StreamRec    fFTStream;
195     SkStream*       fSkStream;
196     uint32_t        fRefCnt;
197     uint32_t        fFontID;
198 
199     // assumes ownership of the stream, will call unref() when its done
200     SkFaceRec(SkStream* strm, uint32_t fontID);
~SkFaceRecSkFaceRec201     ~SkFaceRec() {
202         fSkStream->unref();
203     }
204 };
205 
206 extern "C" {
sk_stream_read(FT_Stream stream,unsigned long offset,unsigned char * buffer,unsigned long count)207     static unsigned long sk_stream_read(FT_Stream       stream,
208                                         unsigned long   offset,
209                                         unsigned char*  buffer,
210                                         unsigned long   count ) {
211         SkStream* str = (SkStream*)stream->descriptor.pointer;
212 
213         if (count) {
214             if (!str->rewind()) {
215                 return 0;
216             } else {
217                 unsigned long ret;
218                 if (offset) {
219                     ret = str->read(NULL, offset);
220                     if (ret != offset) {
221                         return 0;
222                     }
223                 }
224                 ret = str->read(buffer, count);
225                 if (ret != count) {
226                     return 0;
227                 }
228                 count = ret;
229             }
230         }
231         return count;
232     }
233 
sk_stream_close(FT_Stream stream)234     static void sk_stream_close( FT_Stream stream) {}
235 }
236 
SkFaceRec(SkStream * strm,uint32_t fontID)237 SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
238         : fSkStream(strm), fFontID(fontID) {
239 //    SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
240 
241     sk_bzero(&fFTStream, sizeof(fFTStream));
242     fFTStream.size = fSkStream->getLength();
243     fFTStream.descriptor.pointer = fSkStream;
244     fFTStream.read  = sk_stream_read;
245     fFTStream.close = sk_stream_close;
246 }
247 
248 // Will return 0 on failure
ref_ft_face(uint32_t fontID)249 static SkFaceRec* ref_ft_face(uint32_t fontID) {
250     SkFaceRec* rec = gFaceRecHead;
251     while (rec) {
252         if (rec->fFontID == fontID) {
253             SkASSERT(rec->fFace);
254             rec->fRefCnt += 1;
255             return rec;
256         }
257         rec = rec->fNext;
258     }
259 
260     SkStream* strm = SkFontHost::OpenStream(fontID);
261     if (NULL == strm) {
262         SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
263         return 0;
264     }
265 
266     // this passes ownership of strm to the rec
267     rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
268 
269     FT_Open_Args    args;
270     memset(&args, 0, sizeof(args));
271     const void* memoryBase = strm->getMemoryBase();
272 
273     if (NULL != memoryBase) {
274 //printf("mmap(%s)\n", keyString.c_str());
275         args.flags = FT_OPEN_MEMORY;
276         args.memory_base = (const FT_Byte*)memoryBase;
277         args.memory_size = strm->getLength();
278     } else {
279 //printf("fopen(%s)\n", keyString.c_str());
280         args.flags = FT_OPEN_STREAM;
281         args.stream = &rec->fFTStream;
282     }
283 
284     int face_index;
285     int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
286     FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
287                                 &rec->fFace);
288 
289     if (err) {    // bad filename, try the default font
290         fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
291         SkDELETE(rec);
292         return 0;
293     } else {
294         SkASSERT(rec->fFace);
295         //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
296         rec->fNext = gFaceRecHead;
297         gFaceRecHead = rec;
298         rec->fRefCnt = 1;
299         return rec;
300     }
301 }
302 
unref_ft_face(FT_Face face)303 static void unref_ft_face(FT_Face face) {
304     SkFaceRec*  rec = gFaceRecHead;
305     SkFaceRec*  prev = NULL;
306     while (rec) {
307         SkFaceRec* next = rec->fNext;
308         if (rec->fFace == face) {
309             if (--rec->fRefCnt == 0) {
310                 if (prev) {
311                     prev->fNext = next;
312                 } else {
313                     gFaceRecHead = next;
314                 }
315                 FT_Done_Face(face);
316                 SkDELETE(rec);
317             }
318             return;
319         }
320         prev = rec;
321         rec = next;
322     }
323     SkDEBUGFAIL("shouldn't get here, face not in list");
324 }
325 
326 ///////////////////////////////////////////////////////////////////////////
327 
328 // Work around for old versions of freetype.
getAdvances(FT_Face face,FT_UInt start,FT_UInt count,FT_Int32 loadFlags,FT_Fixed * advances)329 static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
330                            FT_Int32 loadFlags, FT_Fixed* advances) {
331 #ifdef FT_ADVANCES_H
332     return FT_Get_Advances(face, start, count, loadFlags, advances);
333 #else
334     if (!face || start >= face->num_glyphs ||
335             start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
336         return 6;  // "Invalid argument."
337     }
338     if (count == 0)
339         return 0;
340 
341     for (int i = 0; i < count; i++) {
342         FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
343         if (err)
344             return err;
345         advances[i] = face->glyph->advance.x;
346     }
347 
348     return 0;
349 #endif
350 }
351 
canEmbed(FT_Face face)352 static bool canEmbed(FT_Face face) {
353 #ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
354     FT_UShort fsType = FT_Get_FSType_Flags(face);
355     return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
356                       FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
357 #else
358     // No embedding is 0x2 and bitmap embedding only is 0x200.
359     TT_OS2* os2_table;
360     if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
361         return (os2_table->fsType & 0x202) == 0;
362     }
363     return false;  // We tried, fail safe.
364 #endif
365 }
366 
GetLetterCBox(FT_Face face,char letter,FT_BBox * bbox)367 static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
368     const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
369     if (!glyph_id)
370         return false;
371     FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
372     FT_Outline_Get_CBox(&face->glyph->outline, bbox);
373     return true;
374 }
375 
getWidthAdvance(FT_Face face,int gId,int16_t * data)376 static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
377     FT_Fixed advance = 0;
378     if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
379         return false;
380     }
381     SkASSERT(data);
382     *data = advance;
383     return true;
384 }
385 
populate_glyph_to_unicode(FT_Face & face,SkTDArray<SkUnichar> * glyphToUnicode)386 static void populate_glyph_to_unicode(FT_Face& face,
387                                       SkTDArray<SkUnichar>* glyphToUnicode) {
388     // Check and see if we have Unicode cmaps.
389     for (int i = 0; i < face->num_charmaps; ++i) {
390         // CMaps known to support Unicode:
391         // Platform ID   Encoding ID   Name
392         // -----------   -----------   -----------------------------------
393         // 0             0,1           Apple Unicode
394         // 0             3             Apple Unicode 2.0 (preferred)
395         // 3             1             Microsoft Unicode UCS-2
396         // 3             10            Microsoft Unicode UCS-4 (preferred)
397         //
398         // See Apple TrueType Reference Manual
399         // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6cmap.html
400         // http://developer.apple.com/fonts/TTRefMan/RM06/Chap6name.html#ID
401         // Microsoft OpenType Specification
402         // http://www.microsoft.com/typography/otspec/cmap.htm
403 
404         FT_UShort platformId = face->charmaps[i]->platform_id;
405         FT_UShort encodingId = face->charmaps[i]->encoding_id;
406 
407         if (platformId != 0 && platformId != 3) {
408             continue;
409         }
410         if (platformId == 3 && encodingId != 1 && encodingId != 10) {
411             continue;
412         }
413         bool preferredMap = ((platformId == 3 && encodingId == 10) ||
414                              (platformId == 0 && encodingId == 3));
415 
416         FT_Set_Charmap(face, face->charmaps[i]);
417         if (glyphToUnicode->isEmpty()) {
418             glyphToUnicode->setCount(face->num_glyphs);
419             memset(glyphToUnicode->begin(), 0,
420                    sizeof(SkUnichar) * face->num_glyphs);
421         }
422 
423         // Iterate through each cmap entry.
424         FT_UInt glyphIndex;
425         for (SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
426              glyphIndex != 0;
427              charCode = FT_Get_Next_Char(face, charCode, &glyphIndex)) {
428             if (charCode &&
429                     ((*glyphToUnicode)[glyphIndex] == 0 || preferredMap)) {
430                 (*glyphToUnicode)[glyphIndex] = charCode;
431             }
432         }
433     }
434 }
435 
436 // static
GetAdvancedTypefaceMetrics(uint32_t fontID,SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,const uint32_t * glyphIDs,uint32_t glyphIDsCount)437 SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
438         uint32_t fontID,
439         SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
440         const uint32_t* glyphIDs,
441         uint32_t glyphIDsCount) {
442 #if defined(SK_BUILD_FOR_MAC)
443     return NULL;
444 #else
445     SkAutoMutexAcquire ac(gFTMutex);
446     FT_Library libInit = NULL;
447     if (gFTCount == 0) {
448         if (!InitFreetype())
449             sk_throw();
450         libInit = gFTLibrary;
451     }
452     SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
453     SkFaceRec* rec = ref_ft_face(fontID);
454     if (NULL == rec)
455         return NULL;
456     FT_Face face = rec->fFace;
457 
458     SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
459     info->fFontName.set(FT_Get_Postscript_Name(face));
460     info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
461     info->fLastGlyphID = face->num_glyphs - 1;
462     info->fEmSize = 1000;
463 
464     bool cid = false;
465     const char* fontType = FT_Get_X11_Font_Format(face);
466     if (strcmp(fontType, "Type 1") == 0) {
467         info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
468     } else if (strcmp(fontType, "CID Type 1") == 0) {
469         info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
470         cid = true;
471     } else if (strcmp(fontType, "CFF") == 0) {
472         info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
473     } else if (strcmp(fontType, "TrueType") == 0) {
474         info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
475         cid = true;
476         TT_Header* ttHeader;
477         if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
478                                                       ft_sfnt_head)) != NULL) {
479             info->fEmSize = ttHeader->Units_Per_EM;
480         }
481     }
482 
483     info->fStyle = 0;
484     if (FT_IS_FIXED_WIDTH(face))
485         info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
486     if (face->style_flags & FT_STYLE_FLAG_ITALIC)
487         info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
488     // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
489     // character set is a subset of 'Adobe standard Latin.'
490     info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
491 
492     PS_FontInfoRec ps_info;
493     TT_Postscript* tt_info;
494     if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
495         info->fItalicAngle = ps_info.italic_angle;
496     } else if ((tt_info =
497                 (TT_Postscript*)FT_Get_Sfnt_Table(face,
498                                                   ft_sfnt_post)) != NULL) {
499         info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
500     } else {
501         info->fItalicAngle = 0;
502     }
503 
504     info->fAscent = face->ascender;
505     info->fDescent = face->descender;
506 
507     // Figure out a good guess for StemV - Min width of i, I, !, 1.
508     // This probably isn't very good with an italic font.
509     int16_t min_width = SHRT_MAX;
510     info->fStemV = 0;
511     char stem_chars[] = {'i', 'I', '!', '1'};
512     for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
513         FT_BBox bbox;
514         if (GetLetterCBox(face, stem_chars[i], &bbox)) {
515             int16_t width = bbox.xMax - bbox.xMin;
516             if (width > 0 && width < min_width) {
517                 min_width = width;
518                 info->fStemV = min_width;
519             }
520         }
521     }
522 
523     TT_PCLT* pclt_info;
524     TT_OS2* os2_table;
525     if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
526         info->fCapHeight = pclt_info->CapHeight;
527         uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
528         if (serif_style >= 2 && serif_style <= 6)
529             info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
530         else if (serif_style >= 9 && serif_style <= 12)
531             info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
532     } else if ((os2_table =
533                 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
534         info->fCapHeight = os2_table->sCapHeight;
535     } else {
536         // Figure out a good guess for CapHeight: average the height of M and X.
537         FT_BBox m_bbox, x_bbox;
538         bool got_m, got_x;
539         got_m = GetLetterCBox(face, 'M', &m_bbox);
540         got_x = GetLetterCBox(face, 'X', &x_bbox);
541         if (got_m && got_x) {
542             info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
543                     x_bbox.yMin) / 2;
544         } else if (got_m && !got_x) {
545             info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
546         } else if (!got_m && got_x) {
547             info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
548         }
549     }
550 
551     info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
552                                     face->bbox.xMax, face->bbox.yMin);
553 
554     if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
555             info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
556         perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
557     }
558 
559     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
560         if (FT_IS_FIXED_WIDTH(face)) {
561             appendRange(&info->fGlyphWidths, 0);
562             int16_t advance = face->max_advance_width;
563             info->fGlyphWidths->fAdvance.append(1, &advance);
564             finishRange(info->fGlyphWidths.get(), 0,
565                         SkAdvancedTypefaceMetrics::WidthRange::kDefault);
566         } else if (!cid) {
567             appendRange(&info->fGlyphWidths, 0);
568             // So as to not blow out the stack, get advances in batches.
569             for (int gID = 0; gID < face->num_glyphs; gID += 128) {
570                 FT_Fixed advances[128];
571                 int advanceCount = 128;
572                 if (gID + advanceCount > face->num_glyphs)
573                     advanceCount = face->num_glyphs - gID + 1;
574                 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
575                             advances);
576                 for (int i = 0; i < advanceCount; i++) {
577                     int16_t advance = advances[gID + i];
578                     info->fGlyphWidths->fAdvance.append(1, &advance);
579                 }
580             }
581             finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
582                         SkAdvancedTypefaceMetrics::WidthRange::kRange);
583         } else {
584             info->fGlyphWidths.reset(
585                 getAdvanceData(face,
586                                face->num_glyphs,
587                                glyphIDs,
588                                glyphIDsCount,
589                                &getWidthAdvance));
590         }
591     }
592 
593     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
594             FT_HAS_VERTICAL(face)) {
595         SkASSERT(false);  // Not implemented yet.
596     }
597 
598     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
599             info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
600         // Postscript fonts may contain more than 255 glyphs, so we end up
601         // using multiple font descriptions with a glyph ordering.  Record
602         // the name of each glyph.
603         info->fGlyphNames.reset(
604                 new SkAutoTArray<SkString>(face->num_glyphs));
605         for (int gID = 0; gID < face->num_glyphs; gID++) {
606             char glyphName[128];  // PS limit for names is 127 bytes.
607             FT_Get_Glyph_Name(face, gID, glyphName, 128);
608             info->fGlyphNames->get()[gID].set(glyphName);
609         }
610     }
611 
612     if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo &&
613            info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
614            face->num_charmaps) {
615         populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
616     }
617 
618     if (!canEmbed(face))
619         info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
620 
621     unref_ft_face(face);
622     return info;
623 #endif
624 }
625 
626 ///////////////////////////////////////////////////////////////////////////
627 
628 #define BLACK_LUMINANCE_LIMIT   0x40
629 #define WHITE_LUMINANCE_LIMIT   0xA0
630 
bothZero(SkScalar a,SkScalar b)631 static bool bothZero(SkScalar a, SkScalar b) {
632     return 0 == a && 0 == b;
633 }
634 
635 // returns false if there is any non-90-rotation or skew
isAxisAligned(const SkScalerContext::Rec & rec)636 static bool isAxisAligned(const SkScalerContext::Rec& rec) {
637     return 0 == rec.fPreSkewX &&
638            (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
639             bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
640 }
641 
FilterRec(SkScalerContext::Rec * rec)642 void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
643     if (!gLCDSupportValid) {
644         InitFreetype();
645         FT_Done_FreeType(gFTLibrary);
646     }
647 
648     if (!gLCDSupport && isLCD(*rec)) {
649         // If the runtime Freetype library doesn't support LCD mode, we disable
650         // it here.
651         rec->fMaskFormat = SkMask::kA8_Format;
652     }
653 
654     SkPaint::Hinting h = rec->getHinting();
655     if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
656         // collapse full->normal hinting if we're not doing LCD
657         h = SkPaint::kNormal_Hinting;
658     }
659     if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) || isLCD(*rec)) {
660         if (SkPaint::kNo_Hinting != h) {
661             h = SkPaint::kSlight_Hinting;
662         }
663     }
664 
665 #ifndef SK_IGNORE_ROTATED_FREETYPE_FIX
666     // rotated text looks bad with hinting, so we disable it as needed
667     if (!isAxisAligned(*rec)) {
668         h = SkPaint::kNo_Hinting;
669     }
670 #endif
671     rec->setHinting(h);
672 
673 #ifndef SK_USE_COLOR_LUMINANCE
674     // for compatibility at the moment, discretize luminance to 3 settings
675     // black, white, gray. This helps with fontcache utilization, since we
676     // won't create multiple entries that in the end map to the same results.
677     {
678         unsigned lum = rec->getLuminanceByte();
679         if (gGammaTables[0] || gGammaTables[1]) {
680             if (lum <= BLACK_LUMINANCE_LIMIT) {
681                 lum = 0;
682             } else if (lum >= WHITE_LUMINANCE_LIMIT) {
683                 lum = SkScalerContext::kLuminance_Max;
684             } else {
685                 lum = SkScalerContext::kLuminance_Max >> 1;
686             }
687         } else {
688             lum = 0;    // no gamma correct, so use 0 since SkPaint uses that
689                         // when measuring text w/o regard for luminance
690         }
691         rec->setLuminanceBits(lum);
692     }
693 #endif
694 }
695 
696 #ifdef SK_BUILD_FOR_ANDROID
GetUnitsPerEm(SkFontID fontID)697 uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
698     SkAutoMutexAcquire ac(gFTMutex);
699     FT_Library libInit = NULL;
700     if (gFTCount == 0) {
701         if (!InitFreetype())
702             sk_throw();
703         libInit = gFTLibrary;
704     }
705     SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
706     SkFaceRec *rec = ref_ft_face(fontID);
707     uint16_t unitsPerEm = 0;
708 
709     if (rec != NULL && rec->fFace != NULL) {
710         unitsPerEm = rec->fFace->units_per_EM;
711         unref_ft_face(rec->fFace);
712     }
713 
714     return (uint32_t)unitsPerEm;
715 }
716 #endif
717 
SkScalerContext_FreeType(const SkDescriptor * desc)718 SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
719         : SkScalerContext(desc) {
720     SkAutoMutexAcquire  ac(gFTMutex);
721 
722     if (gFTCount == 0) {
723         if (!InitFreetype()) {
724             sk_throw();
725         }
726         SkFontHost::GetGammaTables(gGammaTables);
727     }
728     ++gFTCount;
729 
730     // load the font file
731     fFTSize = NULL;
732     fFace = NULL;
733     fFaceRec = ref_ft_face(fRec.fFontID);
734     if (NULL == fFaceRec) {
735         return;
736     }
737     fFace = fFaceRec->fFace;
738 
739     // compute our factors from the record
740 
741     SkMatrix    m;
742 
743     fRec.getSingleMatrix(&m);
744 
745 #ifdef DUMP_STRIKE_CREATION
746     SkString     keyString;
747     SkFontHost::GetDescriptorKeyString(desc, &keyString);
748     printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
749            SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
750            SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
751            SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
752            fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
753 #endif
754 
755     //  now compute our scale factors
756     SkScalar    sx = m.getScaleX();
757     SkScalar    sy = m.getScaleY();
758 
759     if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
760         // sort of give up on hinting
761         sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
762         sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
763         sx = sy = SkScalarAve(sx, sy);
764 
765         SkScalar inv = SkScalarInvert(sx);
766 
767         // flip the skew elements to go from our Y-down system to FreeType's
768         fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
769         fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
770         fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
771         fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
772     } else {
773         fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
774         fMatrix22.xy = fMatrix22.yx = 0;
775     }
776 
777     fScaleX = SkScalarToFixed(sx);
778     fScaleY = SkScalarToFixed(sy);
779 
780     // compute the flags we send to Load_Glyph
781     fUseVertMetrics = false;
782     {
783         FT_Int32 loadFlags = FT_LOAD_DEFAULT;
784         bool linearMetrics = false;
785 
786         if (SkMask::kBW_Format == fRec.fMaskFormat) {
787             // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
788             loadFlags = FT_LOAD_TARGET_MONO;
789             if (fRec.getHinting() == SkPaint::kNo_Hinting) {
790                 loadFlags = FT_LOAD_NO_HINTING;
791                 linearMetrics = true;
792             }
793         } else {
794             switch (fRec.getHinting()) {
795             case SkPaint::kNo_Hinting:
796                 loadFlags = FT_LOAD_NO_HINTING;
797                 linearMetrics = true;
798                 break;
799             case SkPaint::kSlight_Hinting:
800                 loadFlags = FT_LOAD_TARGET_LIGHT;  // This implies FORCE_AUTOHINT
801                 linearMetrics = true;
802                 break;
803             case SkPaint::kNormal_Hinting:
804                 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
805                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
806                 else
807                     loadFlags = FT_LOAD_NO_AUTOHINT;
808                 break;
809             case SkPaint::kFull_Hinting:
810                 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
811                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
812                     break;
813                 }
814                 loadFlags = FT_LOAD_TARGET_NORMAL;
815                 if (isLCD(fRec)) {
816                     if (fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag) {
817                         loadFlags = FT_LOAD_TARGET_LCD_V;
818                     } else {
819                         loadFlags = FT_LOAD_TARGET_LCD;
820                     }
821                 }
822                 break;
823             default:
824                 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
825                 break;
826             }
827         }
828 
829         if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
830             loadFlags |= FT_LOAD_NO_BITMAP;
831         }
832 
833         // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
834         // advances, as fontconfig and cairo do.
835         // See http://code.google.com/p/skia/issues/detail?id=222.
836         loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
837 
838         // Use vertical layout if requested and supported.
839         if ((fRec.fFlags & SkScalerContext::kVertical_Flag) && FT_HAS_VERTICAL(fFace)) {
840             loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
841             fUseVertMetrics = true;
842         }
843 
844         fLoadGlyphFlags = loadFlags;
845         fDoLinearMetrics = linearMetrics;
846     }
847 
848     // now create the FT_Size
849 
850     {
851         FT_Error    err;
852 
853         err = FT_New_Size(fFace, &fFTSize);
854         if (err != 0) {
855             SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
856                         fFaceRec->fFontID, fScaleX, fScaleY, err));
857             fFace = NULL;
858             return;
859         }
860 
861         err = FT_Activate_Size(fFTSize);
862         if (err != 0) {
863             SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
864                         fFaceRec->fFontID, fScaleX, fScaleY, err));
865             fFTSize = NULL;
866         }
867 
868         err = FT_Set_Char_Size( fFace,
869                                 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
870                                 72, 72);
871         if (err != 0) {
872             SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
873                         fFaceRec->fFontID, fScaleX, fScaleY, err));
874             fFace = NULL;
875             return;
876         }
877 
878         FT_Set_Transform( fFace, &fMatrix22, NULL);
879     }
880 }
881 
~SkScalerContext_FreeType()882 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
883     if (fFTSize != NULL) {
884         FT_Done_Size(fFTSize);
885     }
886 
887     SkAutoMutexAcquire  ac(gFTMutex);
888 
889     if (fFace != NULL) {
890         unref_ft_face(fFace);
891     }
892     if (--gFTCount == 0) {
893 //        SkDEBUGF(("FT_Done_FreeType\n"));
894         FT_Done_FreeType(gFTLibrary);
895         SkDEBUGCODE(gFTLibrary = NULL;)
896     }
897 }
898 
899 /*  We call this before each use of the fFace, since we may be sharing
900     this face with other context (at different sizes).
901 */
setupSize()902 FT_Error SkScalerContext_FreeType::setupSize() {
903     FT_Error    err = FT_Activate_Size(fFTSize);
904 
905     if (err != 0) {
906         SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
907                     fFaceRec->fFontID, fScaleX, fScaleY, err));
908         fFTSize = NULL;
909     } else {
910         // seems we need to reset this every time (not sure why, but without it
911         // I get random italics from some other fFTSize)
912         FT_Set_Transform( fFace, &fMatrix22, NULL);
913     }
914     return err;
915 }
916 
emboldenOutline(FT_Outline * outline)917 void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
918     FT_Pos strength;
919     strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
920                / SK_OUTLINE_EMBOLDEN_DIVISOR;
921     FT_Outline_Embolden(outline, strength);
922 }
923 
generateGlyphCount()924 unsigned SkScalerContext_FreeType::generateGlyphCount() {
925     return fFace->num_glyphs;
926 }
927 
generateCharToGlyph(SkUnichar uni)928 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
929     return SkToU16(FT_Get_Char_Index( fFace, uni ));
930 }
931 
generateGlyphToChar(uint16_t glyph)932 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
933     // iterate through each cmap entry, looking for matching glyph indices
934     FT_UInt glyphIndex;
935     SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
936 
937     while (glyphIndex != 0) {
938         if (glyphIndex == glyph) {
939             return charCode;
940         }
941         charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
942     }
943 
944     return 0;
945 }
946 
compute_pixel_mode(SkMask::Format format)947 static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
948     switch (format) {
949         case SkMask::kBW_Format:
950             return FT_PIXEL_MODE_MONO;
951         case SkMask::kA8_Format:
952         default:
953             return FT_PIXEL_MODE_GRAY;
954     }
955 }
956 
generateAdvance(SkGlyph * glyph)957 void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
958 #ifdef FT_ADVANCES_H
959    /* unhinted and light hinted text have linearly scaled advances
960     * which are very cheap to compute with some font formats...
961     */
962     if (fDoLinearMetrics) {
963         SkAutoMutexAcquire  ac(gFTMutex);
964 
965         if (this->setupSize()) {
966             glyph->zeroMetrics();
967             return;
968         }
969 
970         FT_Error    error;
971         FT_Fixed    advance;
972 
973         error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
974                                 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
975                                 &advance );
976         if (0 == error) {
977             glyph->fRsbDelta = 0;
978             glyph->fLsbDelta = 0;
979             glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, advance);  // advance *2/3; //DEBUG
980             glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, advance);
981             return;
982         }
983     }
984 #endif /* FT_ADVANCES_H */
985     /* otherwise, we need to load/hint the glyph, which is slower */
986     this->generateMetrics(glyph);
987     return;
988 }
989 
getBBoxForCurrentGlyph(SkGlyph * glyph,FT_BBox * bbox,bool snapToPixelBoundary)990 void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
991                                                       FT_BBox* bbox,
992                                                       bool snapToPixelBoundary) {
993 
994     FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
995 
996     if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
997         int dx = FixedToDot6(glyph->getSubXFixed());
998         int dy = FixedToDot6(glyph->getSubYFixed());
999         // negate dy since freetype-y-goes-up and skia-y-goes-down
1000         bbox->xMin += dx;
1001         bbox->yMin -= dy;
1002         bbox->xMax += dx;
1003         bbox->yMax -= dy;
1004     }
1005 
1006     // outset the box to integral boundaries
1007     if (snapToPixelBoundary) {
1008         bbox->xMin &= ~63;
1009         bbox->yMin &= ~63;
1010         bbox->xMax  = (bbox->xMax + 63) & ~63;
1011         bbox->yMax  = (bbox->yMax + 63) & ~63;
1012     }
1013 
1014     // Must come after snapToPixelBoundary so that the width and height are
1015     // consistent. Otherwise asserts will fire later on when generating the
1016     // glyph image.
1017     if (fUseVertMetrics) {
1018         FT_Vector vector;
1019         vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1020         vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1021         FT_Vector_Transform(&vector, &fMatrix22);
1022         bbox->xMin += vector.x;
1023         bbox->xMax += vector.x;
1024         bbox->yMin += vector.y;
1025         bbox->yMax += vector.y;
1026     }
1027 }
1028 
updateGlyphIfLCD(SkGlyph * glyph)1029 void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1030     if (isLCD(fRec)) {
1031         glyph->fWidth += gLCDExtra;
1032         glyph->fLeft -= gLCDExtra >> 1;
1033     }
1034 }
1035 
generateMetrics(SkGlyph * glyph)1036 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1037     SkAutoMutexAcquire  ac(gFTMutex);
1038 
1039     glyph->fRsbDelta = 0;
1040     glyph->fLsbDelta = 0;
1041 
1042     FT_Error    err;
1043 
1044     if (this->setupSize()) {
1045         goto ERROR;
1046     }
1047 
1048     err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1049     if (err != 0) {
1050         SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1051                     fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
1052     ERROR:
1053         glyph->zeroMetrics();
1054         return;
1055     }
1056 
1057     SkFixed vLeft, vTop;
1058 
1059     switch ( fFace->glyph->format ) {
1060       case FT_GLYPH_FORMAT_OUTLINE: {
1061         FT_BBox bbox;
1062 
1063         if (0 == fFace->glyph->outline.n_contours) {
1064             glyph->fWidth = 0;
1065             glyph->fHeight = 0;
1066             glyph->fTop = 0;
1067             glyph->fLeft = 0;
1068             break;
1069         }
1070 
1071         if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1072             emboldenOutline(&fFace->glyph->outline);
1073         }
1074 
1075         getBBoxForCurrentGlyph(glyph, &bbox, true);
1076 
1077         glyph->fWidth   = SkToU16((bbox.xMax - bbox.xMin) >> 6);
1078         glyph->fHeight  = SkToU16((bbox.yMax - bbox.yMin) >> 6);
1079         glyph->fTop     = -SkToS16(bbox.yMax >> 6);
1080         glyph->fLeft    = SkToS16(bbox.xMin >> 6);
1081 
1082         if ((fRec.fFlags & SkScalerContext::kVertical_Flag)) {
1083             vLeft = Dot6ToFixed(bbox.xMin);
1084             vTop = Dot6ToFixed(bbox.yMax);
1085         }
1086 
1087         updateGlyphIfLCD(glyph);
1088 
1089         break;
1090       }
1091 
1092       case FT_GLYPH_FORMAT_BITMAP:
1093         if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1094             FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1095             FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1096         }
1097 
1098         if (fUseVertMetrics) {
1099             FT_Vector vector;
1100             vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1101             vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1102             FT_Vector_Transform(&vector, &fMatrix22);
1103             fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1104             fFace->glyph->bitmap_top  += SkFDot6Floor(vector.y);
1105         }
1106 
1107         glyph->fWidth   = SkToU16(fFace->glyph->bitmap.width);
1108         glyph->fHeight  = SkToU16(fFace->glyph->bitmap.rows);
1109         glyph->fTop     = -SkToS16(fFace->glyph->bitmap_top);
1110         glyph->fLeft    = SkToS16(fFace->glyph->bitmap_left);
1111         break;
1112 
1113       default:
1114         SkDEBUGFAIL("unknown glyph format");
1115         goto ERROR;
1116     }
1117 
1118     if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
1119         glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
1120         glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
1121         if (fRec.fFlags & kDevKernText_Flag) {
1122             glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1123             glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1124         }
1125     } else {
1126         glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
1127         glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
1128     }
1129 
1130     if (fUseVertMetrics) {
1131         if (fDoLinearMetrics) {
1132             glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1133             glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1134         } else {
1135             glyph->fAdvanceX = -SkFDot6ToFixed(fFace->glyph->advance.x);
1136             glyph->fAdvanceY = SkFDot6ToFixed(fFace->glyph->advance.y);
1137         }
1138 
1139     } else if ((fRec.fFlags & SkScalerContext::kVertical_Flag)
1140                 && fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
1141 
1142         //TODO: do we need to specially handle SubpixelPositioning and Kerning?
1143 
1144         FT_Matrix identityMatrix;
1145         identityMatrix.xx = identityMatrix.yy = SK_Fixed1;
1146         identityMatrix.xy = identityMatrix.yx = 0;
1147 
1148         // if the matrix is not the identity matrix then we need to re-load the
1149         // glyph with the identity matrix to get the necessary bounding box
1150         if (memcmp(&fMatrix22, &identityMatrix, sizeof(FT_Matrix)) != 0) {
1151 
1152             FT_Set_Transform(fFace, &identityMatrix, NULL);
1153 
1154             err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
1155             if (err != 0) {
1156                 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1157                             fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
1158                 goto ERROR;
1159             }
1160 
1161             if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1162                 emboldenOutline(&fFace->glyph->outline);
1163             }
1164         }
1165 
1166         // bounding box of the unskewed and unscaled glyph
1167         FT_BBox bbox;
1168         getBBoxForCurrentGlyph(glyph, &bbox);
1169 
1170         // compute the vertical gap above and below the glyph if the glyph were
1171         // centered within the linearVertAdvance
1172         SkFixed vGap = (fFace->glyph->linearVertAdvance - Dot6ToFixed(bbox.yMax - bbox.yMin)) / 2;
1173 
1174         // the origin point of the glyph when rendered vertically
1175         FT_Vector vOrigin;
1176         vOrigin.x = fFace->glyph->linearHoriAdvance / 2;
1177         vOrigin.y = vGap + Dot6ToFixed(bbox.yMax);
1178 
1179         // transform the vertical origin based on the matrix of the actual glyph
1180         FT_Vector_Transform(&vOrigin, &fMatrix22);
1181 
1182         // compute a new offset vector for the glyph by subtracting the vertical
1183         // origin from the original horizontal offset vector
1184         glyph->fLeft = SkFixedRoundToInt(vLeft - vOrigin.x);
1185         glyph->fTop =  -SkFixedRoundToInt(vTop - vOrigin.y);
1186 
1187         updateGlyphIfLCD(glyph);
1188 
1189         // use the vertical advance values computed by freetype
1190         glyph->fAdvanceX = -SkFixedMul(fMatrix22.xy, fFace->glyph->linearVertAdvance);
1191         glyph->fAdvanceY = SkFixedMul(fMatrix22.yy, fFace->glyph->linearVertAdvance);
1192     }
1193 
1194 
1195 #ifdef ENABLE_GLYPH_SPEW
1196     SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
1197     SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
1198 #endif
1199 }
1200 
1201 ///////////////////////////////////////////////////////////////////////////////
1202 
apply_contrast(int srca,int contrast)1203 static int apply_contrast(int srca, int contrast) {
1204     return srca + (((255 - srca) * contrast * srca) / (255*255));
1205 }
1206 
build_power_table(uint8_t table[],float ee)1207 static void build_power_table(uint8_t table[], float ee) {
1208     for (int i = 0; i < 256; i++) {
1209         float x = i / 255.f;
1210         x = powf(x, ee);
1211         int xx = SkScalarRoundToInt(SkFloatToScalar(x * 255));
1212         table[i] = SkToU8(xx);
1213     }
1214 }
1215 
build_gamma_table(uint8_t table[256],int src,int dst)1216 static void build_gamma_table(uint8_t table[256], int src, int dst) {
1217     static bool gInit;
1218     static uint8_t powTable[256], invPowTable[256];
1219     if (!gInit) {
1220         const float g = SK_GAMMA_EXPONENT;
1221         build_power_table(powTable, g);
1222         build_power_table(invPowTable, 1/g);
1223         gInit = true;
1224     }
1225 
1226     const int linSrc = powTable[src];
1227     const int linDst = powTable[dst];
1228     // have our contrast value taper off to 0 as the src luminance becomes white
1229     const int contrast = SK_GAMMA_CONTRAST * (255 - linSrc) / 255;
1230 
1231     for (int i = 0; i < 256; ++i) {
1232         int srca = apply_contrast(i, contrast);
1233         SkASSERT((unsigned)srca <= 255);
1234         int dsta = 255 - srca;
1235 
1236         //Calculate the output we want.
1237         int linOut = (linSrc * srca + dsta * linDst) / 255;
1238         SkASSERT((unsigned)linOut <= 255);
1239         int out = invPowTable[linOut];
1240 
1241         //Undo what the blit blend will do.
1242         int result = ((255 * out) - (255 * dst)) / (src - dst);
1243         SkASSERT((unsigned)result <= 255);
1244 
1245         table[i] = result;
1246     }
1247 }
1248 
getGammaTable(U8CPU luminance)1249 static const uint8_t* getGammaTable(U8CPU luminance) {
1250     static uint8_t gGammaTables[4][256];
1251     static bool gInited;
1252     if (!gInited) {
1253         build_gamma_table(gGammaTables[0], 0x00, 0xFF);
1254         build_gamma_table(gGammaTables[1], 0x66, 0x99);
1255         build_gamma_table(gGammaTables[2], 0x99, 0x66);
1256         build_gamma_table(gGammaTables[3], 0xFF, 0x00);
1257 
1258         gInited = true;
1259     }
1260     SkASSERT(0 == (luminance >> 8));
1261     return gGammaTables[luminance >> 6];
1262 }
1263 
1264 #ifndef SK_USE_COLOR_LUMINANCE
getIdentityTable()1265 static const uint8_t* getIdentityTable() {
1266     static bool gOnce;
1267     static uint8_t gIdentityTable[256];
1268     if (!gOnce) {
1269         for (int i = 0; i < 256; ++i) {
1270             gIdentityTable[i] = i;
1271         }
1272         gOnce = true;
1273     }
1274     return gIdentityTable;
1275 }
1276 #endif
1277 
packTriple(unsigned r,unsigned g,unsigned b)1278 static uint16_t packTriple(unsigned r, unsigned g, unsigned b) {
1279     return SkPackRGB16(r >> 3, g >> 2, b >> 3);
1280 }
1281 
grayToRGB16(U8CPU gray)1282 static uint16_t grayToRGB16(U8CPU gray) {
1283     SkASSERT(gray <= 255);
1284     return SkPackRGB16(gray >> 3, gray >> 2, gray >> 3);
1285 }
1286 
bittst(const uint8_t data[],int bitOffset)1287 static int bittst(const uint8_t data[], int bitOffset) {
1288     SkASSERT(bitOffset >= 0);
1289     int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7);
1290     return lowBit & 1;
1291 }
1292 
copyFT2LCD16(const SkGlyph & glyph,const FT_Bitmap & bitmap,int lcdIsBGR,const uint8_t * tableR,const uint8_t * tableG,const uint8_t * tableB)1293 static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap,
1294                          int lcdIsBGR, const uint8_t* tableR,
1295                          const uint8_t* tableG, const uint8_t* tableB) {
1296     SkASSERT(glyph.fHeight == bitmap.rows);
1297     uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
1298     const size_t dstRB = glyph.rowBytes();
1299     const int width = glyph.fWidth;
1300     const uint8_t* src = bitmap.buffer;
1301 
1302     switch (bitmap.pixel_mode) {
1303         case FT_PIXEL_MODE_MONO: {
1304             for (int y = 0; y < glyph.fHeight; ++y) {
1305                 for (int x = 0; x < width; ++x) {
1306                     dst[x] = -bittst(src, x);
1307                 }
1308                 dst = (uint16_t*)((char*)dst + dstRB);
1309                 src += bitmap.pitch;
1310             }
1311         } break;
1312         case FT_PIXEL_MODE_GRAY: {
1313             for (int y = 0; y < glyph.fHeight; ++y) {
1314                 for (int x = 0; x < width; ++x) {
1315                     dst[x] = grayToRGB16(src[x]);
1316                 }
1317                 dst = (uint16_t*)((char*)dst + dstRB);
1318                 src += bitmap.pitch;
1319             }
1320         } break;
1321         default: {
1322             SkASSERT(glyph.fWidth * 3 == bitmap.width);
1323             for (int y = 0; y < glyph.fHeight; y++) {
1324                 const uint8_t* triple = src;
1325                 if (lcdIsBGR) {
1326                     for (int x = 0; x < width; x++) {
1327                         dst[x] = packTriple(tableR[triple[2]],
1328                                             tableG[triple[1]],
1329                                             tableB[triple[0]]);
1330                         triple += 3;
1331                     }
1332                 } else {
1333                     for (int x = 0; x < width; x++) {
1334                         dst[x] = packTriple(tableR[triple[0]],
1335                                             tableG[triple[1]],
1336                                             tableB[triple[2]]);
1337                         triple += 3;
1338                     }
1339                 }
1340                 src += bitmap.pitch;
1341                 dst = (uint16_t*)((char*)dst + dstRB);
1342             }
1343         } break;
1344     }
1345 }
1346 
generateImage(const SkGlyph & glyph)1347 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1348     SkAutoMutexAcquire  ac(gFTMutex);
1349 
1350     FT_Error    err;
1351 
1352     if (this->setupSize()) {
1353         goto ERROR;
1354     }
1355 
1356     err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
1357     if (err != 0) {
1358         SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1359                     glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1360     ERROR:
1361         memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1362         return;
1363     }
1364 
1365 #ifdef SK_USE_COLOR_LUMINANCE
1366     SkColor lumColor = fRec.getLuminanceColor();
1367     const uint8_t* tableR = getGammaTable(SkColorGetR(lumColor));
1368     const uint8_t* tableG = getGammaTable(SkColorGetG(lumColor));
1369     const uint8_t* tableB = getGammaTable(SkColorGetB(lumColor));
1370 #else
1371     unsigned lum = fRec.getLuminanceByte();
1372     const uint8_t* tableR;
1373     const uint8_t* tableG;
1374     const uint8_t* tableB;
1375 
1376     bool isWhite = lum >= WHITE_LUMINANCE_LIMIT;
1377     bool isBlack = lum <= BLACK_LUMINANCE_LIMIT;
1378     if ((gGammaTables[0] || gGammaTables[1]) && (isBlack || isWhite)) {
1379         tableR = tableG = tableB = gGammaTables[isBlack ? 0 : 1];
1380     } else {
1381         tableR = tableG = tableB = getIdentityTable();
1382     }
1383 #endif
1384 
1385     switch ( fFace->glyph->format ) {
1386         case FT_GLYPH_FORMAT_OUTLINE: {
1387             FT_Outline* outline = &fFace->glyph->outline;
1388             FT_BBox     bbox;
1389             FT_Bitmap   target;
1390 
1391             if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1392                 emboldenOutline(outline);
1393             }
1394 
1395             int dx = 0, dy = 0;
1396             if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
1397                 dx = glyph.getSubXFixed() >> 10;
1398                 dy = glyph.getSubYFixed() >> 10;
1399                 // negate dy since freetype-y-goes-up and skia-y-goes-down
1400                 dy = -dy;
1401             }
1402             FT_Outline_Get_CBox(outline, &bbox);
1403             /*
1404                 what we really want to do for subpixel is
1405                     offset(dx, dy)
1406                     compute_bounds
1407                     offset(bbox & !63)
1408                 but that is two calls to offset, so we do the following, which
1409                 achieves the same thing with only one offset call.
1410             */
1411             FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1412                                           dy - ((bbox.yMin + dy) & ~63));
1413 
1414             if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1415                 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
1416                 copyFT2LCD16(glyph, fFace->glyph->bitmap,
1417                              fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1418                              tableR, tableG, tableB);
1419             } else {
1420                 target.width = glyph.fWidth;
1421                 target.rows = glyph.fHeight;
1422                 target.pitch = glyph.rowBytes();
1423                 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1424                 target.pixel_mode = compute_pixel_mode(
1425                                                 (SkMask::Format)fRec.fMaskFormat);
1426                 target.num_grays = 256;
1427 
1428                 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1429                 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1430             }
1431         } break;
1432 
1433         case FT_GLYPH_FORMAT_BITMAP: {
1434             if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1435                 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1436                 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1437             }
1438             SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1439             SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1440             SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1441             SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1442 
1443             const uint8_t*  src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1444             uint8_t*        dst = (uint8_t*)glyph.fImage;
1445 
1446             if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1447                 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1448                  glyph.fMaskFormat == SkMask::kBW_Format)) {
1449                 unsigned    srcRowBytes = fFace->glyph->bitmap.pitch;
1450                 unsigned    dstRowBytes = glyph.rowBytes();
1451                 unsigned    minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1452                 unsigned    extraRowBytes = dstRowBytes - minRowBytes;
1453 
1454                 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1455                     memcpy(dst, src, minRowBytes);
1456                     memset(dst + minRowBytes, 0, extraRowBytes);
1457                     src += srcRowBytes;
1458                     dst += dstRowBytes;
1459                 }
1460             } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1461                        glyph.fMaskFormat == SkMask::kA8_Format) {
1462                 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1463                     uint8_t byte = 0;
1464                     int bits = 0;
1465                     const uint8_t* src_row = src;
1466                     uint8_t* dst_row = dst;
1467 
1468                     for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1469                         if (!bits) {
1470                             byte = *src_row++;
1471                             bits = 8;
1472                         }
1473 
1474                         *dst_row++ = byte & 0x80 ? 0xff : 0;
1475                         bits--;
1476                         byte <<= 1;
1477                     }
1478 
1479                     src += fFace->glyph->bitmap.pitch;
1480                     dst += glyph.rowBytes();
1481                 }
1482             } else if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1483                 copyFT2LCD16(glyph, fFace->glyph->bitmap,
1484                              fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag,
1485                              tableR, tableG, tableB);
1486             } else {
1487                 SkDEBUGFAIL("unknown glyph bitmap transform needed");
1488             }
1489         } break;
1490 
1491     default:
1492         SkDEBUGFAIL("unknown glyph format");
1493         goto ERROR;
1494     }
1495 
1496 // We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum,
1497 // it is optional
1498 #if defined(SK_GAMMA_APPLY_TO_A8) || !defined(SK_USE_COLOR_LUMINANCE)
1499     if (SkMask::kA8_Format == glyph.fMaskFormat) {
1500         SkASSERT(tableR == tableG && tableR == tableB);
1501         const uint8_t* table = tableR;
1502         uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1503         unsigned rowBytes = glyph.rowBytes();
1504 
1505         for (int y = glyph.fHeight - 1; y >= 0; --y) {
1506             for (int x = glyph.fWidth - 1; x >= 0; --x) {
1507                 dst[x] = table[dst[x]];
1508             }
1509             dst += rowBytes;
1510         }
1511     }
1512 #endif
1513 }
1514 
1515 ///////////////////////////////////////////////////////////////////////////////
1516 
1517 #define ft2sk(x)    SkFixedToScalar((x) << 10)
1518 
1519 #if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
1520     #define CONST_PARAM const
1521 #else   // older freetype doesn't use const here
1522     #define CONST_PARAM
1523 #endif
1524 
move_proc(CONST_PARAM FT_Vector * pt,void * ctx)1525 static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1526     SkPath* path = (SkPath*)ctx;
1527     path->close();  // to close the previous contour (if any)
1528     path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1529     return 0;
1530 }
1531 
line_proc(CONST_PARAM FT_Vector * pt,void * ctx)1532 static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1533     SkPath* path = (SkPath*)ctx;
1534     path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1535     return 0;
1536 }
1537 
quad_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,void * ctx)1538 static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1539                      void* ctx) {
1540     SkPath* path = (SkPath*)ctx;
1541     path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1542     return 0;
1543 }
1544 
cubic_proc(CONST_PARAM FT_Vector * pt0,CONST_PARAM FT_Vector * pt1,CONST_PARAM FT_Vector * pt2,void * ctx)1545 static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1546                       CONST_PARAM FT_Vector* pt2, void* ctx) {
1547     SkPath* path = (SkPath*)ctx;
1548     path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1549                   -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1550     return 0;
1551 }
1552 
generatePath(const SkGlyph & glyph,SkPath * path)1553 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1554                                             SkPath* path) {
1555     SkAutoMutexAcquire  ac(gFTMutex);
1556 
1557     SkASSERT(&glyph && path);
1558 
1559     if (this->setupSize()) {
1560         path->reset();
1561         return;
1562     }
1563 
1564     uint32_t flags = fLoadGlyphFlags;
1565     flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1566     flags &= ~FT_LOAD_RENDER;   // don't scan convert (we just want the outline)
1567 
1568     FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1569 
1570     if (err != 0) {
1571         SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1572                     glyph.getGlyphID(fBaseGlyphCount), flags, err));
1573         path->reset();
1574         return;
1575     }
1576 
1577     if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1578         emboldenOutline(&fFace->glyph->outline);
1579     }
1580 
1581     if (fUseVertMetrics) {
1582         FT_Vector vector;
1583         vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1584         vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1585         FT_Vector_Transform(&vector, &fMatrix22);
1586         FT_Outline_Translate(&fFace->glyph->outline, vector.x, vector.y);
1587     }
1588 
1589     FT_Outline_Funcs    funcs;
1590 
1591     funcs.move_to   = move_proc;
1592     funcs.line_to   = line_proc;
1593     funcs.conic_to  = quad_proc;
1594     funcs.cubic_to  = cubic_proc;
1595     funcs.shift     = 0;
1596     funcs.delta     = 0;
1597 
1598     err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1599 
1600     if (err != 0) {
1601         SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1602                     glyph.getGlyphID(fBaseGlyphCount), flags, err));
1603         path->reset();
1604         return;
1605     }
1606 
1607     path->close();
1608 }
1609 
generateFontMetrics(SkPaint::FontMetrics * mx,SkPaint::FontMetrics * my)1610 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1611                                                    SkPaint::FontMetrics* my) {
1612     if (NULL == mx && NULL == my) {
1613         return;
1614     }
1615 
1616     SkAutoMutexAcquire  ac(gFTMutex);
1617 
1618     if (this->setupSize()) {
1619         ERROR:
1620         if (mx) {
1621             sk_bzero(mx, sizeof(SkPaint::FontMetrics));
1622         }
1623         if (my) {
1624             sk_bzero(my, sizeof(SkPaint::FontMetrics));
1625         }
1626         return;
1627     }
1628 
1629     FT_Face face = fFace;
1630     int upem = face->units_per_EM;
1631     if (upem <= 0) {
1632         goto ERROR;
1633     }
1634 
1635     SkPoint pts[6];
1636     SkFixed ys[6];
1637     SkFixed scaleY = fScaleY;
1638     SkFixed mxy = fMatrix22.xy;
1639     SkFixed myy = fMatrix22.yy;
1640     SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1641     SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
1642 
1643     int leading = face->height - (face->ascender + -face->descender);
1644     if (leading < 0) {
1645         leading = 0;
1646     }
1647 
1648     // Try to get the OS/2 table from the font. This contains the specific
1649     // average font width metrics which Windows uses.
1650     TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1651 
1652     ys[0] = -face->bbox.yMax;
1653     ys[1] = -face->ascender;
1654     ys[2] = -face->descender;
1655     ys[3] = -face->bbox.yMin;
1656     ys[4] = leading;
1657     ys[5] = os2 ? os2->xAvgCharWidth : 0;
1658 
1659     SkScalar x_height;
1660     if (os2 && os2->sxHeight) {
1661         x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1662     } else {
1663         const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1664         if (x_glyph) {
1665             FT_BBox bbox;
1666             FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
1667             if ((fRec.fFlags & kEmbolden_Flag) && !(fFace->style_flags & FT_STYLE_FLAG_BOLD)) {
1668                 emboldenOutline(&fFace->glyph->outline);
1669             }
1670             FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1671             x_height = SkFixedToScalar(SkFDot6ToFixed(bbox.yMax));
1672         } else {
1673             x_height = 0;
1674         }
1675     }
1676 
1677     // convert upem-y values into scalar points
1678     for (int i = 0; i < 6; i++) {
1679         SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1680         SkFixed x = SkFixedMul(mxy, y);
1681         y = SkFixedMul(myy, y);
1682         pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1683     }
1684 
1685     if (mx) {
1686         mx->fTop = pts[0].fX;
1687         mx->fAscent = pts[1].fX;
1688         mx->fDescent = pts[2].fX;
1689         mx->fBottom = pts[3].fX;
1690         mx->fLeading = pts[4].fX;
1691         mx->fAvgCharWidth = pts[5].fX;
1692         mx->fXMin = xmin;
1693         mx->fXMax = xmax;
1694         mx->fXHeight = x_height;
1695     }
1696     if (my) {
1697         my->fTop = pts[0].fY;
1698         my->fAscent = pts[1].fY;
1699         my->fDescent = pts[2].fY;
1700         my->fBottom = pts[3].fY;
1701         my->fLeading = pts[4].fY;
1702         my->fAvgCharWidth = pts[5].fY;
1703         my->fXMin = xmin;
1704         my->fXMax = xmax;
1705         my->fXHeight = x_height;
1706     }
1707 }
1708 
1709 ////////////////////////////////////////////////////////////////////////
1710 ////////////////////////////////////////////////////////////////////////
1711 
CreateScalerContext(const SkDescriptor * desc)1712 SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
1713     SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1714     if (!c->success()) {
1715         SkDELETE(c);
1716         c = NULL;
1717     }
1718     return c;
1719 }
1720 
1721 ///////////////////////////////////////////////////////////////////////////////
1722 
1723 /*  Export this so that other parts of our FonttHost port can make use of our
1724     ability to extract the name+style from a stream, using FreeType's api.
1725 */
find_name_and_attributes(SkStream * stream,SkString * name,SkTypeface::Style * style,bool * isFixedWidth)1726 bool find_name_and_attributes(SkStream* stream, SkString* name,
1727                               SkTypeface::Style* style, bool* isFixedWidth) {
1728     FT_Library  library;
1729     if (FT_Init_FreeType(&library)) {
1730         return false;
1731     }
1732 
1733     FT_Open_Args    args;
1734     memset(&args, 0, sizeof(args));
1735 
1736     const void* memoryBase = stream->getMemoryBase();
1737     FT_StreamRec    streamRec;
1738 
1739     if (NULL != memoryBase) {
1740         args.flags = FT_OPEN_MEMORY;
1741         args.memory_base = (const FT_Byte*)memoryBase;
1742         args.memory_size = stream->getLength();
1743     } else {
1744         memset(&streamRec, 0, sizeof(streamRec));
1745         streamRec.size = stream->read(NULL, 0);
1746         streamRec.descriptor.pointer = stream;
1747         streamRec.read  = sk_stream_read;
1748         streamRec.close = sk_stream_close;
1749 
1750         args.flags = FT_OPEN_STREAM;
1751         args.stream = &streamRec;
1752     }
1753 
1754     FT_Face face;
1755     if (FT_Open_Face(library, &args, 0, &face)) {
1756         FT_Done_FreeType(library);
1757         return false;
1758     }
1759 
1760     int tempStyle = SkTypeface::kNormal;
1761     if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1762         tempStyle |= SkTypeface::kBold;
1763     }
1764     if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1765         tempStyle |= SkTypeface::kItalic;
1766     }
1767 
1768     if (name) {
1769         name->set(face->family_name);
1770     }
1771     if (style) {
1772         *style = (SkTypeface::Style) tempStyle;
1773     }
1774     if (isFixedWidth) {
1775         *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1776     }
1777 
1778     FT_Done_Face(face);
1779     FT_Done_FreeType(library);
1780     return true;
1781 }
1782