1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "SkAdvancedTypefaceMetrics.h"
9 #include "SkBitmap.h"
10 #include "SkCanvas.h"
11 #include "SkColorPriv.h"
12 #include "SkDescriptor.h"
13 #include "SkFDot6.h"
14 #include "SkFontDescriptor.h"
15 #include "SkFontHost_FreeType_common.h"
16 #include "SkGlyph.h"
17 #include "SkMask.h"
18 #include "SkMaskGamma.h"
19 #include "SkMatrix22.h"
20 #include "SkMutex.h"
21 #include "SkOTUtils.h"
22 #include "SkPath.h"
23 #include "SkScalerContext.h"
24 #include "SkStream.h"
25 #include "SkString.h"
26 #include "SkTemplates.h"
27 #include "SkTypes.h"
28 #include <memory>
29 
30 #if defined(SK_CAN_USE_DLOPEN)
31 #include <dlfcn.h>
32 #endif
33 #include <ft2build.h>
34 #include FT_ADVANCES_H
35 #include FT_BITMAP_H
36 #include FT_FREETYPE_H
37 #include FT_LCD_FILTER_H
38 #include FT_MODULE_H
39 #include FT_MULTIPLE_MASTERS_H
40 #include FT_OUTLINE_H
41 #include FT_SIZES_H
42 #include FT_SYSTEM_H
43 #include FT_TRUETYPE_TABLES_H
44 #include FT_TYPE1_TABLES_H
45 #include FT_XFREE86_H
46 
47 // FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
48 // were introduced in FreeType 2.5.0.
49 // The following may be removed once FreeType 2.5.0 is required to build.
50 #ifndef FT_LOAD_COLOR
51 #    define FT_LOAD_COLOR ( 1L << 20 )
52 #    define FT_PIXEL_MODE_BGRA 7
53 #endif
54 
55 //#define ENABLE_GLYPH_SPEW     // for tracing calls
56 //#define DUMP_STRIKE_CREATION
57 //#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
58 //#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
59 //#define SK_GAMMA_APPLY_TO_A8
60 
isLCD(const SkScalerContext::Rec & rec)61 static bool isLCD(const SkScalerContext::Rec& rec) {
62     return SkMask::kLCD16_Format == rec.fMaskFormat;
63 }
64 
65 //////////////////////////////////////////////////////////////////////////
66 
67 extern "C" {
sk_ft_alloc(FT_Memory,long size)68     static void* sk_ft_alloc(FT_Memory, long size) {
69         return sk_malloc_throw(size);
70     }
sk_ft_free(FT_Memory,void * block)71     static void sk_ft_free(FT_Memory, void* block) {
72         sk_free(block);
73     }
sk_ft_realloc(FT_Memory,long cur_size,long new_size,void * block)74     static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
75         return sk_realloc_throw(block, new_size);
76     }
77 };
78 FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
79 
80 class FreeTypeLibrary : SkNoncopyable {
81 public:
FreeTypeLibrary()82     FreeTypeLibrary() : fLibrary(nullptr), fIsLCDSupported(false), fLCDExtra(0) {
83         if (FT_New_Library(&gFTMemory, &fLibrary)) {
84             return;
85         }
86         FT_Add_Default_Modules(fLibrary);
87 
88         // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
89         // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
90         // SetLcdFilter must be called before SetLcdFilterWeights.
91         if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
92             fIsLCDSupported = true;
93             fLCDExtra = 2; //Using a filter adds one full pixel to each side.
94 
95 #ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
96             // Adds to 0x110 simulating ink spread, but provides better results than default.
97             static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
98 
99 #    if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
100             FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
101 #    elif SK_CAN_USE_DLOPEN == 1
102             //The FreeType library is already loaded, so symbols are available in process.
103             void* self = dlopen(nullptr, RTLD_LAZY);
104             if (self) {
105                 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
106                 //The following cast is non-standard, but safe for POSIX.
107                 *reinterpret_cast<void**>(&setLcdFilterWeights) =
108                         dlsym(self, "FT_Library_SetLcdFilterWeights");
109                 dlclose(self);
110 
111                 if (setLcdFilterWeights) {
112                     setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
113                 }
114             }
115 #    endif
116 #endif
117         }
118     }
~FreeTypeLibrary()119     ~FreeTypeLibrary() {
120         if (fLibrary) {
121             FT_Done_Library(fLibrary);
122         }
123     }
124 
library()125     FT_Library library() { return fLibrary; }
isLCDSupported()126     bool isLCDSupported() { return fIsLCDSupported; }
lcdExtra()127     int lcdExtra() { return fLCDExtra; }
128 
129 private:
130     FT_Library fLibrary;
131     bool fIsLCDSupported;
132     int fLCDExtra;
133 
134     // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
135     // The following platforms provide FreeType of at least 2.4.0.
136     // Ubuntu >= 11.04 (previous deprecated April 2013)
137     // Debian >= 6.0 (good)
138     // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
139     // Fedora >= 14 (good)
140     // Android >= Gingerbread (good)
141     typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
142 };
143 
144 struct SkFaceRec;
145 
146 SK_DECLARE_STATIC_MUTEX(gFTMutex);
147 static FreeTypeLibrary* gFTLibrary;
148 static SkFaceRec* gFaceRecHead;
149 
150 // Private to ref_ft_library and unref_ft_library
151 static int gFTCount;
152 
153 // Caller must lock gFTMutex before calling this function.
ref_ft_library()154 static bool ref_ft_library() {
155     gFTMutex.assertHeld();
156     SkASSERT(gFTCount >= 0);
157 
158     if (0 == gFTCount) {
159         SkASSERT(nullptr == gFTLibrary);
160         gFTLibrary = new FreeTypeLibrary;
161     }
162     ++gFTCount;
163     return gFTLibrary->library();
164 }
165 
166 // Caller must lock gFTMutex before calling this function.
unref_ft_library()167 static void unref_ft_library() {
168     gFTMutex.assertHeld();
169     SkASSERT(gFTCount > 0);
170 
171     --gFTCount;
172     if (0 == gFTCount) {
173         SkASSERT(nullptr == gFaceRecHead);
174         SkASSERT(nullptr != gFTLibrary);
175         delete gFTLibrary;
176         SkDEBUGCODE(gFTLibrary = nullptr;)
177     }
178 }
179 
180 class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
181 public:
182     SkScalerContext_FreeType(SkTypeface*, const SkScalerContextEffects&, const SkDescriptor* desc);
183     virtual ~SkScalerContext_FreeType();
184 
success() const185     bool success() const {
186         return fFTSize != nullptr && fFace != nullptr;
187     }
188 
189 protected:
190     unsigned generateGlyphCount() override;
191     uint16_t generateCharToGlyph(SkUnichar uni) override;
192     void generateAdvance(SkGlyph* glyph) override;
193     void generateMetrics(SkGlyph* glyph) override;
194     void generateImage(const SkGlyph& glyph) override;
195     void generatePath(const SkGlyph& glyph, SkPath* path) override;
196     void generateFontMetrics(SkPaint::FontMetrics*) override;
197     SkUnichar generateGlyphToChar(uint16_t glyph) override;
198 
199 private:
200     FT_Face   fFace;  // Shared face from gFaceRecHead.
201     FT_Size   fFTSize;  // The size on the fFace for this scaler.
202     FT_Int    fStrikeIndex;
203 
204     /** The rest of the matrix after FreeType handles the size.
205      *  With outline font rasterization this is handled by FreeType with FT_Set_Transform.
206      *  With bitmap only fonts this matrix must be applied to scale the bitmap.
207      */
208     SkMatrix  fMatrix22Scalar;
209     /** Same as fMatrix22Scalar, but in FreeType units and space. */
210     FT_Matrix fMatrix22;
211     /** The actual size requested. */
212     SkVector  fScale;
213 
214     uint32_t  fLoadGlyphFlags;
215     bool      fDoLinearMetrics;
216     bool      fLCDIsVert;
217 
218     FT_Error setupSize();
219     void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
220                                 bool snapToPixelBoundary = false);
221     bool getCBoxForLetter(char letter, FT_BBox* bbox);
222     // Caller must lock gFTMutex before calling this function.
223     void updateGlyphIfLCD(SkGlyph* glyph);
224     // Caller must lock gFTMutex before calling this function.
225     // update FreeType2 glyph slot with glyph emboldened
226     void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
227     bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
228 };
229 
230 ///////////////////////////////////////////////////////////////////////////
231 ///////////////////////////////////////////////////////////////////////////
232 
233 struct SkFaceRec {
234     SkFaceRec* fNext;
235     FT_Face fFace;
236     FT_StreamRec fFTStream;
237     std::unique_ptr<SkStreamAsset> fSkStream;
238     uint32_t fRefCnt;
239     uint32_t fFontID;
240 
241     SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
242 };
243 
244 extern "C" {
sk_ft_stream_io(FT_Stream ftStream,unsigned long offset,unsigned char * buffer,unsigned long count)245     static unsigned long sk_ft_stream_io(FT_Stream ftStream,
246                                          unsigned long offset,
247                                          unsigned char* buffer,
248                                          unsigned long count)
249     {
250         SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
251 
252         if (count) {
253             if (!stream->seek(offset)) {
254                 return 0;
255             }
256             count = stream->read(buffer, count);
257         }
258         return count;
259     }
260 
sk_ft_stream_close(FT_Stream)261     static void sk_ft_stream_close(FT_Stream) {}
262 }
263 
SkFaceRec(std::unique_ptr<SkStreamAsset> stream,uint32_t fontID)264 SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
265         : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
266 {
267     sk_bzero(&fFTStream, sizeof(fFTStream));
268     fFTStream.size = fSkStream->getLength();
269     fFTStream.descriptor.pointer = fSkStream.get();
270     fFTStream.read  = sk_ft_stream_io;
271     fFTStream.close = sk_ft_stream_close;
272 }
273 
ft_face_setup_axes(FT_Face face,const SkFontData & data)274 static void ft_face_setup_axes(FT_Face face, const SkFontData& data) {
275     if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
276         return;
277     }
278 
279     SkDEBUGCODE(
280         FT_MM_Var* variations = nullptr;
281         if (FT_Get_MM_Var(face, &variations)) {
282             SkDEBUGF(("INFO: font %s claims variations, but none found.\n", face->family_name));
283             return;
284         }
285         SkAutoFree autoFreeVariations(variations);
286 
287         if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
288             SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
289                     face->family_name, variations->num_axis, data.getAxisCount()));
290             return;
291         }
292     )
293 
294     SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
295     for (int i = 0; i < data.getAxisCount(); ++i) {
296         coords[i] = data.getAxis()[i];
297     }
298     if (FT_Set_Var_Design_Coordinates(face, data.getAxisCount(), coords.get())) {
299         SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
300                   face->family_name));
301         return;
302     }
303 }
304 
305 // Will return 0 on failure
306 // Caller must lock gFTMutex before calling this function.
ref_ft_face(const SkTypeface * typeface)307 static FT_Face ref_ft_face(const SkTypeface* typeface) {
308     gFTMutex.assertHeld();
309 
310     const SkFontID fontID = typeface->uniqueID();
311     SkFaceRec* rec = gFaceRecHead;
312     while (rec) {
313         if (rec->fFontID == fontID) {
314             SkASSERT(rec->fFace);
315             rec->fRefCnt += 1;
316             return rec->fFace;
317         }
318         rec = rec->fNext;
319     }
320 
321     std::unique_ptr<SkFontData> data = typeface->makeFontData();
322     if (nullptr == data || !data->hasStream()) {
323         return nullptr;
324     }
325 
326     rec = new SkFaceRec(data->detachStream(), fontID);
327 
328     FT_Open_Args args;
329     memset(&args, 0, sizeof(args));
330     const void* memoryBase = rec->fSkStream->getMemoryBase();
331     if (memoryBase) {
332         args.flags = FT_OPEN_MEMORY;
333         args.memory_base = (const FT_Byte*)memoryBase;
334         args.memory_size = rec->fSkStream->getLength();
335     } else {
336         args.flags = FT_OPEN_STREAM;
337         args.stream = &rec->fFTStream;
338     }
339 
340     FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rec->fFace);
341     if (err) {
342         SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
343         delete rec;
344         return nullptr;
345     }
346     SkASSERT(rec->fFace);
347 
348     ft_face_setup_axes(rec->fFace, *data);
349 
350     // FreeType will set the charmap to the "most unicode" cmap if it exists.
351     // If there are no unicode cmaps, the charmap is set to nullptr.
352     // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
353     // because they are effectively private use area only (even if they aren't).
354     // This is the last on the fallback list at
355     // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
356     if (!rec->fFace->charmap) {
357         FT_Select_Charmap(rec->fFace, FT_ENCODING_MS_SYMBOL);
358     }
359 
360     rec->fNext = gFaceRecHead;
361     gFaceRecHead = rec;
362     return rec->fFace;
363 }
364 
365 // Caller must lock gFTMutex before calling this function.
366 extern void unref_ft_face(FT_Face face);
unref_ft_face(FT_Face face)367 void unref_ft_face(FT_Face face) {
368     gFTMutex.assertHeld();
369 
370     SkFaceRec*  rec = gFaceRecHead;
371     SkFaceRec*  prev = nullptr;
372     while (rec) {
373         SkFaceRec* next = rec->fNext;
374         if (rec->fFace == face) {
375             if (--rec->fRefCnt == 0) {
376                 if (prev) {
377                     prev->fNext = next;
378                 } else {
379                     gFaceRecHead = next;
380                 }
381                 FT_Done_Face(face);
382                 delete rec;
383             }
384             return;
385         }
386         prev = rec;
387         rec = next;
388     }
389     SkDEBUGFAIL("shouldn't get here, face not in list");
390 }
391 
392 class AutoFTAccess {
393 public:
AutoFTAccess(const SkTypeface * tf)394     AutoFTAccess(const SkTypeface* tf) : fFace(nullptr) {
395         gFTMutex.acquire();
396         if (!ref_ft_library()) {
397             sk_throw();
398         }
399         fFace = ref_ft_face(tf);
400     }
401 
~AutoFTAccess()402     ~AutoFTAccess() {
403         if (fFace) {
404             unref_ft_face(fFace);
405         }
406         unref_ft_library();
407         gFTMutex.release();
408     }
409 
face()410     FT_Face face() { return fFace; }
411 
412 private:
413     FT_Face     fFace;
414 };
415 
416 ///////////////////////////////////////////////////////////////////////////
417 
canEmbed(FT_Face face)418 static bool canEmbed(FT_Face face) {
419     FT_UShort fsType = FT_Get_FSType_Flags(face);
420     return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
421                       FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
422 }
423 
canSubset(FT_Face face)424 static bool canSubset(FT_Face face) {
425     FT_UShort fsType = FT_Get_FSType_Flags(face);
426     return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
427 }
428 
GetLetterCBox(FT_Face face,char letter,FT_BBox * bbox)429 static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
430     const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
431     if (!glyph_id)
432         return false;
433     if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
434         return false;
435     FT_Outline_Get_CBox(&face->glyph->outline, bbox);
436     return true;
437 }
438 
populate_glyph_to_unicode(FT_Face & face,SkTDArray<SkUnichar> * glyphToUnicode)439 static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
440     FT_Long numGlyphs = face->num_glyphs;
441     glyphToUnicode->setCount(SkToInt(numGlyphs));
442     sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
443 
444     FT_UInt glyphIndex;
445     SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
446     while (glyphIndex) {
447         SkASSERT(glyphIndex < SkToUInt(numGlyphs));
448         // Use the first character that maps to this glyphID. https://crbug.com/359065
449         if (0 == (*glyphToUnicode)[glyphIndex]) {
450             (*glyphToUnicode)[glyphIndex] = charCode;
451         }
452         charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
453     }
454 }
455 
onGetAdvancedTypefaceMetrics(PerGlyphInfo perGlyphInfo,const uint32_t * glyphIDs,uint32_t glyphIDsCount) const456 SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
457         PerGlyphInfo perGlyphInfo,
458         const uint32_t* glyphIDs,
459         uint32_t glyphIDsCount) const {
460     AutoFTAccess fta(this);
461     FT_Face face = fta.face();
462     if (!face) {
463         return nullptr;
464     }
465 
466     SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
467     info->fFontName.set(FT_Get_Postscript_Name(face));
468 
469     if (FT_HAS_MULTIPLE_MASTERS(face)) {
470         info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
471     }
472     if (!canEmbed(face)) {
473         info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
474     }
475     if (!canSubset(face)) {
476         info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
477     }
478     info->fLastGlyphID = face->num_glyphs - 1;
479     info->fEmSize = 1000;
480 
481     const char* fontType = FT_Get_X11_Font_Format(face);
482     if (strcmp(fontType, "Type 1") == 0) {
483         info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
484     } else if (strcmp(fontType, "CID Type 1") == 0) {
485         info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
486     } else if (strcmp(fontType, "CFF") == 0) {
487         info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
488     } else if (strcmp(fontType, "TrueType") == 0) {
489         info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
490         TT_Header* ttHeader;
491         if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
492             info->fEmSize = ttHeader->Units_Per_EM;
493         }
494     } else {
495         info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
496     }
497 
498     info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
499     if (FT_IS_FIXED_WIDTH(face)) {
500         info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
501     }
502     if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
503         info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
504     }
505 
506     PS_FontInfoRec psFontInfo;
507     TT_Postscript* postTable;
508     if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
509         info->fItalicAngle = psFontInfo.italic_angle;
510     } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
511         info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
512     } else {
513         info->fItalicAngle = 0;
514     }
515 
516     info->fAscent = face->ascender;
517     info->fDescent = face->descender;
518 
519     // Figure out a good guess for StemV - Min width of i, I, !, 1.
520     // This probably isn't very good with an italic font.
521     int16_t min_width = SHRT_MAX;
522     info->fStemV = 0;
523     char stem_chars[] = {'i', 'I', '!', '1'};
524     for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
525         FT_BBox bbox;
526         if (GetLetterCBox(face, stem_chars[i], &bbox)) {
527             int16_t width = bbox.xMax - bbox.xMin;
528             if (width > 0 && width < min_width) {
529                 min_width = width;
530                 info->fStemV = min_width;
531             }
532         }
533     }
534 
535     TT_PCLT* pcltTable;
536     TT_OS2* os2Table;
537     if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
538         info->fCapHeight = pcltTable->CapHeight;
539         uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
540         if (2 <= serif_style && serif_style <= 6) {
541             info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
542         } else if (9 <= serif_style && serif_style <= 12) {
543             info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
544         }
545     } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
546                // sCapHeight is available only when version 2 or later.
547                os2Table->version != 0xFFFF &&
548                os2Table->version >= 2)
549     {
550         info->fCapHeight = os2Table->sCapHeight;
551     } else {
552         // Figure out a good guess for CapHeight: average the height of M and X.
553         FT_BBox m_bbox, x_bbox;
554         bool got_m, got_x;
555         got_m = GetLetterCBox(face, 'M', &m_bbox);
556         got_x = GetLetterCBox(face, 'X', &x_bbox);
557         if (got_m && got_x) {
558             info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
559         } else if (got_m && !got_x) {
560             info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
561         } else if (!got_m && got_x) {
562             info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
563         } else {
564             // Last resort, use the ascent.
565             info->fCapHeight = info->fAscent;
566         }
567     }
568 
569     info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
570                                     face->bbox.xMax, face->bbox.yMin);
571 
572     if (!FT_IS_SCALABLE(face)) {
573         perGlyphInfo = kNo_PerGlyphInfo;
574     }
575 
576     if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
577         info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
578     {
579         // Postscript fonts may contain more than 255 glyphs, so we end up
580         // using multiple font descriptions with a glyph ordering.  Record
581         // the name of each glyph.
582         info->fGlyphNames.reset(face->num_glyphs);
583         for (int gID = 0; gID < face->num_glyphs; gID++) {
584             char glyphName[128];  // PS limit for names is 127 bytes.
585             FT_Get_Glyph_Name(face, gID, glyphName, 128);
586             info->fGlyphNames[gID].set(glyphName);
587         }
588     }
589 
590     if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
591         info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
592         face->num_charmaps)
593     {
594         populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
595     }
596 
597     return info;
598 }
599 
600 ///////////////////////////////////////////////////////////////////////////
601 
bothZero(SkScalar a,SkScalar b)602 static bool bothZero(SkScalar a, SkScalar b) {
603     return 0 == a && 0 == b;
604 }
605 
606 // returns false if there is any non-90-rotation or skew
isAxisAligned(const SkScalerContext::Rec & rec)607 static bool isAxisAligned(const SkScalerContext::Rec& rec) {
608     return 0 == rec.fPreSkewX &&
609            (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
610             bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
611 }
612 
onCreateScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc) const613 SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
614                                                             const SkDescriptor* desc) const {
615     SkScalerContext_FreeType* c =
616             new SkScalerContext_FreeType(const_cast<SkTypeface_FreeType*>(this), effects, desc);
617     if (!c->success()) {
618         delete c;
619         c = nullptr;
620     }
621     return c;
622 }
623 
onFilterRec(SkScalerContextRec * rec) const624 void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
625     //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
626     //Cap the requested size as larger sizes give bogus values.
627     //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
628     //Note that this also currently only protects against large text size requests,
629     //the total matrix is not taken into account here.
630     if (rec->fTextSize > SkIntToScalar(1 << 14)) {
631         rec->fTextSize = SkIntToScalar(1 << 14);
632     }
633 
634     if (isLCD(*rec)) {
635         // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
636         SkAutoMutexAcquire ama(gFTMutex);
637         ref_ft_library();
638         if (!gFTLibrary->isLCDSupported()) {
639             // If the runtime Freetype library doesn't support LCD, disable it here.
640             rec->fMaskFormat = SkMask::kA8_Format;
641         }
642         unref_ft_library();
643     }
644 
645     SkPaint::Hinting h = rec->getHinting();
646     if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
647         // collapse full->normal hinting if we're not doing LCD
648         h = SkPaint::kNormal_Hinting;
649     }
650     if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
651         if (SkPaint::kNo_Hinting != h) {
652             h = SkPaint::kSlight_Hinting;
653         }
654     }
655 
656     // rotated text looks bad with hinting, so we disable it as needed
657     if (!isAxisAligned(*rec)) {
658         h = SkPaint::kNo_Hinting;
659     }
660     rec->setHinting(h);
661 
662 #ifndef SK_GAMMA_APPLY_TO_A8
663     if (!isLCD(*rec)) {
664         // SRGBTODO: Is this correct? Do we want contrast boost?
665         rec->ignorePreBlend();
666     }
667 #endif
668 }
669 
onGetUPEM() const670 int SkTypeface_FreeType::onGetUPEM() const {
671     AutoFTAccess fta(this);
672     FT_Face face = fta.face();
673     return face ? face->units_per_EM : 0;
674 }
675 
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const676 bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
677                                       int count, int32_t adjustments[]) const {
678     AutoFTAccess fta(this);
679     FT_Face face = fta.face();
680     if (!face || !FT_HAS_KERNING(face)) {
681         return false;
682     }
683 
684     for (int i = 0; i < count - 1; ++i) {
685         FT_Vector delta;
686         FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
687                                       FT_KERNING_UNSCALED, &delta);
688         if (err) {
689             return false;
690         }
691         adjustments[i] = delta.x;
692     }
693     return true;
694 }
695 
696 /** Returns the bitmap strike equal to or just larger than the requested size. */
chooseBitmapStrike(FT_Face face,FT_F26Dot6 scaleY)697 static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
698     if (face == nullptr) {
699         SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
700         return -1;
701     }
702 
703     FT_Pos requestedPPEM = scaleY;  // FT_Bitmap_Size::y_ppem is in 26.6 format.
704     FT_Int chosenStrikeIndex = -1;
705     FT_Pos chosenPPEM = 0;
706     for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
707         FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
708         if (strikePPEM == requestedPPEM) {
709             // exact match - our search stops here
710             return strikeIndex;
711         } else if (chosenPPEM < requestedPPEM) {
712             // attempt to increase chosenPPEM
713             if (chosenPPEM < strikePPEM) {
714                 chosenPPEM = strikePPEM;
715                 chosenStrikeIndex = strikeIndex;
716             }
717         } else {
718             // attempt to decrease chosenPPEM, but not below requestedPPEM
719             if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
720                 chosenPPEM = strikePPEM;
721                 chosenStrikeIndex = strikeIndex;
722             }
723         }
724     }
725     return chosenStrikeIndex;
726 }
727 
SkScalerContext_FreeType(SkTypeface * typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)728 SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
729                                                    const SkScalerContextEffects& effects,
730                                                    const SkDescriptor* desc)
731     : SkScalerContext_FreeType_Base(typeface, effects, desc)
732     , fFace(nullptr)
733     , fFTSize(nullptr)
734     , fStrikeIndex(-1)
735 {
736     SkAutoMutexAcquire  ac(gFTMutex);
737 
738     if (!ref_ft_library()) {
739         sk_throw();
740     }
741 
742     // load the font file
743     using UnrefFTFace = SkFunctionWrapper<void, skstd::remove_pointer_t<FT_Face>, unref_ft_face>;
744     std::unique_ptr<skstd::remove_pointer_t<FT_Face>, UnrefFTFace> ftFace(ref_ft_face(typeface));
745     if (nullptr == ftFace) {
746         SkDEBUGF(("Could not create FT_Face.\n"));
747         return;
748     }
749 
750     fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
751 
752     FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
753     FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
754     fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
755     fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
756     fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
757     fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
758 
759     fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
760 
761     // compute the flags we send to Load_Glyph
762     bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
763     {
764         FT_Int32 loadFlags = FT_LOAD_DEFAULT;
765 
766         if (SkMask::kBW_Format == fRec.fMaskFormat) {
767             // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
768             loadFlags = FT_LOAD_TARGET_MONO;
769             if (fRec.getHinting() == SkPaint::kNo_Hinting) {
770                 loadFlags = FT_LOAD_NO_HINTING;
771                 linearMetrics = true;
772             }
773         } else {
774             switch (fRec.getHinting()) {
775             case SkPaint::kNo_Hinting:
776                 loadFlags = FT_LOAD_NO_HINTING;
777                 linearMetrics = true;
778                 break;
779             case SkPaint::kSlight_Hinting:
780                 loadFlags = FT_LOAD_TARGET_LIGHT;  // This implies FORCE_AUTOHINT
781                 break;
782             case SkPaint::kNormal_Hinting:
783                 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
784                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
785 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
786                 } else {
787                     loadFlags = FT_LOAD_NO_AUTOHINT;
788 #endif
789                 }
790                 break;
791             case SkPaint::kFull_Hinting:
792                 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
793                     loadFlags = FT_LOAD_FORCE_AUTOHINT;
794                     break;
795                 }
796                 loadFlags = FT_LOAD_TARGET_NORMAL;
797                 if (isLCD(fRec)) {
798                     if (fLCDIsVert) {
799                         loadFlags = FT_LOAD_TARGET_LCD_V;
800                     } else {
801                         loadFlags = FT_LOAD_TARGET_LCD;
802                     }
803                 }
804                 break;
805             default:
806                 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
807                 break;
808             }
809         }
810 
811         if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
812             loadFlags |= FT_LOAD_NO_BITMAP;
813         }
814 
815         // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
816         // advances, as fontconfig and cairo do.
817         // See http://code.google.com/p/skia/issues/detail?id=222.
818         loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
819 
820         // Use vertical layout if requested.
821         if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
822             loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
823         }
824 
825         loadFlags |= FT_LOAD_COLOR;
826 
827         fLoadGlyphFlags = loadFlags;
828     }
829 
830     using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
831     std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([&ftFace]() -> FT_Size {
832         FT_Size size;
833         FT_Error err = FT_New_Size(ftFace.get(), &size);
834         if (err != 0) {
835             SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
836             return nullptr;
837         }
838         return size;
839     }());
840     if (nullptr == ftSize) {
841         SkDEBUGF(("Could not create FT_Size.\n"));
842         return;
843     }
844 
845     FT_Error err = FT_Activate_Size(ftSize.get());
846     if (err != 0) {
847         SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
848         return;
849     }
850 
851     if (FT_IS_SCALABLE(ftFace)) {
852         err = FT_Set_Char_Size(ftFace.get(), scaleX, scaleY, 72, 72);
853         if (err != 0) {
854             SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
855                       ftFace->family_name, fScale.fX, fScale.fY, err));
856             return;
857         }
858     } else if (FT_HAS_FIXED_SIZES(ftFace)) {
859         fStrikeIndex = chooseBitmapStrike(ftFace.get(), scaleY);
860         if (fStrikeIndex == -1) {
861             SkDEBUGF(("No glyphs for font \"%s\" size %f.\n", ftFace->family_name, fScale.fY));
862             return;
863         }
864 
865         err = FT_Select_Size(ftFace.get(), fStrikeIndex);
866         if (err != 0) {
867             SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
868                       ftFace->family_name, fStrikeIndex, err));
869             fStrikeIndex = -1;
870             return;
871         }
872 
873         // A non-ideal size was picked, so recompute the matrix.
874         // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
875         fMatrix22Scalar.preScale(fScale.x() / ftFace->size->metrics.x_ppem,
876                                  fScale.y() / ftFace->size->metrics.y_ppem);
877         fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
878         fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
879         fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
880         fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
881 
882         // FreeType does not provide linear metrics for bitmap fonts.
883         linearMetrics = false;
884 
885         // FreeType documentation says:
886         // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
887         // Bitmap-only fonts ignore this flag.
888         //
889         // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
890         // Force this flag off for bitmap only fonts.
891         fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
892     } else {
893         SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFace->family_name, fScale.fY));
894         return;
895     }
896 
897     fFTSize = ftSize.release();
898     fFace = ftFace.release();
899     fDoLinearMetrics = linearMetrics;
900 }
901 
~SkScalerContext_FreeType()902 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
903     SkAutoMutexAcquire  ac(gFTMutex);
904 
905     if (fFTSize != nullptr) {
906         FT_Done_Size(fFTSize);
907     }
908 
909     if (fFace != nullptr) {
910         unref_ft_face(fFace);
911     }
912 
913     unref_ft_library();
914 }
915 
916 /*  We call this before each use of the fFace, since we may be sharing
917     this face with other context (at different sizes).
918 */
setupSize()919 FT_Error SkScalerContext_FreeType::setupSize() {
920     gFTMutex.assertHeld();
921     FT_Error err = FT_Activate_Size(fFTSize);
922     if (err != 0) {
923         return err;
924     }
925     FT_Set_Transform(fFace, &fMatrix22, nullptr);
926     return 0;
927 }
928 
generateGlyphCount()929 unsigned SkScalerContext_FreeType::generateGlyphCount() {
930     return fFace->num_glyphs;
931 }
932 
generateCharToGlyph(SkUnichar uni)933 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
934     SkAutoMutexAcquire  ac(gFTMutex);
935     return SkToU16(FT_Get_Char_Index( fFace, uni ));
936 }
937 
generateGlyphToChar(uint16_t glyph)938 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
939     SkAutoMutexAcquire  ac(gFTMutex);
940     // iterate through each cmap entry, looking for matching glyph indices
941     FT_UInt glyphIndex;
942     SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
943 
944     while (glyphIndex != 0) {
945         if (glyphIndex == glyph) {
946             return charCode;
947         }
948         charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
949     }
950 
951     return 0;
952 }
953 
SkFT_FixedToScalar(FT_Fixed x)954 static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
955   return SkFixedToScalar(x);
956 }
957 
generateAdvance(SkGlyph * glyph)958 void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
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(),
974                                 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
975                                 &advance );
976         if (0 == error) {
977             glyph->fRsbDelta = 0;
978             glyph->fLsbDelta = 0;
979             const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
980             glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
981             glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
982             return;
983         }
984     }
985 
986     /* otherwise, we need to load/hint the glyph, which is slower */
987     this->generateMetrics(glyph);
988     return;
989 }
990 
getBBoxForCurrentGlyph(SkGlyph * glyph,FT_BBox * bbox,bool snapToPixelBoundary)991 void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
992                                                       FT_BBox* bbox,
993                                                       bool snapToPixelBoundary) {
994 
995     FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
996 
997     if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
998         int dx = SkFixedToFDot6(glyph->getSubXFixed());
999         int dy = SkFixedToFDot6(glyph->getSubYFixed());
1000         // negate dy since freetype-y-goes-up and skia-y-goes-down
1001         bbox->xMin += dx;
1002         bbox->yMin -= dy;
1003         bbox->xMax += dx;
1004         bbox->yMax -= dy;
1005     }
1006 
1007     // outset the box to integral boundaries
1008     if (snapToPixelBoundary) {
1009         bbox->xMin &= ~63;
1010         bbox->yMin &= ~63;
1011         bbox->xMax  = (bbox->xMax + 63) & ~63;
1012         bbox->yMax  = (bbox->yMax + 63) & ~63;
1013     }
1014 
1015     // Must come after snapToPixelBoundary so that the width and height are
1016     // consistent. Otherwise asserts will fire later on when generating the
1017     // glyph image.
1018     if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1019         FT_Vector vector;
1020         vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1021         vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1022         FT_Vector_Transform(&vector, &fMatrix22);
1023         bbox->xMin += vector.x;
1024         bbox->xMax += vector.x;
1025         bbox->yMin += vector.y;
1026         bbox->yMax += vector.y;
1027     }
1028 }
1029 
getCBoxForLetter(char letter,FT_BBox * bbox)1030 bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1031     const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
1032     if (!glyph_id) {
1033         return false;
1034     }
1035     if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
1036         return false;
1037     }
1038     emboldenIfNeeded(fFace, fFace->glyph);
1039     FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1040     return true;
1041 }
1042 
updateGlyphIfLCD(SkGlyph * glyph)1043 void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1044     if (isLCD(fRec)) {
1045         if (fLCDIsVert) {
1046             glyph->fHeight += gFTLibrary->lcdExtra();
1047             glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
1048         } else {
1049             glyph->fWidth += gFTLibrary->lcdExtra();
1050             glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
1051         }
1052     }
1053 }
1054 
shouldSubpixelBitmap(const SkGlyph & glyph,const SkMatrix & matrix)1055 bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1056     // If subpixel rendering of a bitmap *can* be done.
1057     bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1058                      fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1059                      (glyph.getSubXFixed() || glyph.getSubYFixed());
1060 
1061     // If subpixel rendering of a bitmap *should* be done.
1062     // 1. If the face is not scalable then always allow subpixel rendering.
1063     //    Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1064     // 2. If the matrix is already not identity the bitmap will already be resampled,
1065     //    so resampling slightly differently shouldn't make much difference.
1066     bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1067 
1068     return mechanism && policy;
1069 }
1070 
generateMetrics(SkGlyph * glyph)1071 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1072     SkAutoMutexAcquire  ac(gFTMutex);
1073 
1074     glyph->fRsbDelta = 0;
1075     glyph->fLsbDelta = 0;
1076 
1077     FT_Error    err;
1078 
1079     if (this->setupSize()) {
1080         glyph->zeroMetrics();
1081         return;
1082     }
1083 
1084     err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
1085     if (err != 0) {
1086         glyph->zeroMetrics();
1087         return;
1088     }
1089     emboldenIfNeeded(fFace, fFace->glyph);
1090 
1091     switch ( fFace->glyph->format ) {
1092       case FT_GLYPH_FORMAT_OUTLINE:
1093         if (0 == fFace->glyph->outline.n_contours) {
1094             glyph->fWidth = 0;
1095             glyph->fHeight = 0;
1096             glyph->fTop = 0;
1097             glyph->fLeft = 0;
1098         } else {
1099             FT_BBox bbox;
1100             getBBoxForCurrentGlyph(glyph, &bbox, true);
1101 
1102             glyph->fWidth   = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1103             glyph->fHeight  = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1104             glyph->fTop     = -SkToS16(SkFDot6Floor(bbox.yMax));
1105             glyph->fLeft    = SkToS16(SkFDot6Floor(bbox.xMin));
1106 
1107             updateGlyphIfLCD(glyph);
1108         }
1109         break;
1110 
1111       case FT_GLYPH_FORMAT_BITMAP:
1112         if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1113             FT_Vector vector;
1114             vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1115             vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1116             FT_Vector_Transform(&vector, &fMatrix22);
1117             fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1118             fFace->glyph->bitmap_top  += SkFDot6Floor(vector.y);
1119         }
1120 
1121         if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1122             glyph->fMaskFormat = SkMask::kARGB32_Format;
1123         }
1124 
1125         {
1126             SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1127                                           -SkIntToScalar(fFace->glyph->bitmap_top),
1128                                            SkIntToScalar(fFace->glyph->bitmap.width),
1129                                            SkIntToScalar(fFace->glyph->bitmap.rows));
1130             fMatrix22Scalar.mapRect(&rect);
1131             if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1132                 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1133                             SkFixedToScalar(glyph->getSubYFixed()));
1134             }
1135             SkIRect irect = rect.roundOut();
1136             glyph->fWidth   = SkToU16(irect.width());
1137             glyph->fHeight  = SkToU16(irect.height());
1138             glyph->fTop     = SkToS16(irect.top());
1139             glyph->fLeft    = SkToS16(irect.left());
1140         }
1141         break;
1142 
1143       default:
1144         SkDEBUGFAIL("unknown glyph format");
1145         glyph->zeroMetrics();
1146         return;
1147     }
1148 
1149     if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1150         if (fDoLinearMetrics) {
1151             const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
1152             glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
1153             glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
1154         } else {
1155             glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1156             glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
1157         }
1158     } else {
1159         if (fDoLinearMetrics) {
1160             const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1161             glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1162             glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1163         } else {
1164             glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1165             glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
1166 
1167             if (fRec.fFlags & kDevKernText_Flag) {
1168                 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1169                 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1170             }
1171         }
1172     }
1173 
1174 #ifdef ENABLE_GLYPH_SPEW
1175     SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
1176 #endif
1177 }
1178 
clear_glyph_image(const SkGlyph & glyph)1179 static void clear_glyph_image(const SkGlyph& glyph) {
1180     sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1181 }
1182 
generateImage(const SkGlyph & glyph)1183 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1184     SkAutoMutexAcquire  ac(gFTMutex);
1185 
1186     if (this->setupSize()) {
1187         clear_glyph_image(glyph);
1188         return;
1189     }
1190 
1191     FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
1192     if (err != 0) {
1193         SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
1194                   glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1195         clear_glyph_image(glyph);
1196         return;
1197     }
1198 
1199     emboldenIfNeeded(fFace, fFace->glyph);
1200     SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1201     SkMatrix subpixelBitmapMatrix;
1202     if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1203         subpixelBitmapMatrix = fMatrix22Scalar;
1204         subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1205                                            SkFixedToScalar(glyph.getSubYFixed()));
1206         bitmapMatrix = &subpixelBitmapMatrix;
1207     }
1208     generateGlyphImage(fFace, glyph, *bitmapMatrix);
1209 }
1210 
1211 
generatePath(const SkGlyph & glyph,SkPath * path)1212 void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
1213     SkAutoMutexAcquire  ac(gFTMutex);
1214 
1215     SkASSERT(path);
1216 
1217     if (this->setupSize()) {
1218         path->reset();
1219         return;
1220     }
1221 
1222     uint32_t flags = fLoadGlyphFlags;
1223     flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1224     flags &= ~FT_LOAD_RENDER;   // don't scan convert (we just want the outline)
1225 
1226     FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
1227 
1228     if (err != 0) {
1229         SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1230                     glyph.getGlyphID(), flags, err));
1231         path->reset();
1232         return;
1233     }
1234     emboldenIfNeeded(fFace, fFace->glyph);
1235 
1236     generateGlyphPath(fFace, path);
1237 
1238     // The path's origin from FreeType is always the horizontal layout origin.
1239     // Offset the path so that it is relative to the vertical origin if needed.
1240     if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1241         FT_Vector vector;
1242         vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1243         vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1244         FT_Vector_Transform(&vector, &fMatrix22);
1245         path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1246     }
1247 }
1248 
generateFontMetrics(SkPaint::FontMetrics * metrics)1249 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
1250     if (nullptr == metrics) {
1251         return;
1252     }
1253 
1254     SkAutoMutexAcquire ac(gFTMutex);
1255 
1256     if (this->setupSize()) {
1257         sk_bzero(metrics, sizeof(*metrics));
1258         return;
1259     }
1260 
1261     FT_Face face = fFace;
1262 
1263     // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1264     SkScalar upem = SkIntToScalar(face->units_per_EM);
1265     if (!upem) {
1266         TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1267         if (ttHeader) {
1268             upem = SkIntToScalar(ttHeader->Units_Per_EM);
1269         }
1270     }
1271 
1272     // use the os/2 table as a source of reasonable defaults.
1273     SkScalar x_height = 0.0f;
1274     SkScalar avgCharWidth = 0.0f;
1275     SkScalar cap_height = 0.0f;
1276     TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1277     if (os2) {
1278         x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
1279         avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
1280         if (os2->version != 0xFFFF && os2->version >= 2) {
1281             cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
1282         }
1283     }
1284 
1285     // pull from format-specific metrics as needed
1286     SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
1287     SkScalar underlineThickness, underlinePosition;
1288     if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
1289         // FreeType will always use HHEA metrics if they're not zero.
1290         // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1291         // It also ignores the VDMX tables, which are also of interest here
1292         // (and override everything else when they apply).
1293         static const int kUseTypoMetricsMask = (1 << 7);
1294         if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1295             ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1296             descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1297             leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1298         } else {
1299             ascent = -SkIntToScalar(face->ascender) / upem;
1300             descent = -SkIntToScalar(face->descender) / upem;
1301             leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1302         }
1303         xmin = SkIntToScalar(face->bbox.xMin) / upem;
1304         xmax = SkIntToScalar(face->bbox.xMax) / upem;
1305         ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1306         ymax = -SkIntToScalar(face->bbox.yMax) / upem;
1307         underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
1308         underlinePosition = -SkIntToScalar(face->underline_position +
1309                                            face->underline_thickness / 2) / upem;
1310 
1311         metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1312         metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1313 
1314         // we may be able to synthesize x_height and cap_height from outline
1315         if (!x_height) {
1316             FT_BBox bbox;
1317             if (getCBoxForLetter('x', &bbox)) {
1318                 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1319             }
1320         }
1321         if (!cap_height) {
1322             FT_BBox bbox;
1323             if (getCBoxForLetter('H', &bbox)) {
1324                 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1325             }
1326         }
1327     } else if (fStrikeIndex != -1) { // bitmap strike metrics
1328         SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1329         SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1330         ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1331         descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1332         leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
1333         xmin = 0.0f;
1334         xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1335         ymin = descent + leading;
1336         ymax = ascent - descent;
1337         underlineThickness = 0;
1338         underlinePosition = 0;
1339 
1340         metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1341         metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1342     } else {
1343         sk_bzero(metrics, sizeof(*metrics));
1344         return;
1345     }
1346 
1347     // synthesize elements that were not provided by the os/2 table or format-specific metrics
1348     if (!x_height) {
1349         x_height = -ascent * fScale.y();
1350     }
1351     if (!avgCharWidth) {
1352         avgCharWidth = xmax - xmin;
1353     }
1354     if (!cap_height) {
1355       cap_height = -ascent * fScale.y();
1356     }
1357 
1358     // disallow negative linespacing
1359     if (leading < 0.0f) {
1360         leading = 0.0f;
1361     }
1362 
1363     metrics->fTop = ymax * fScale.y();
1364     metrics->fAscent = ascent * fScale.y();
1365     metrics->fDescent = descent * fScale.y();
1366     metrics->fBottom = ymin * fScale.y();
1367     metrics->fLeading = leading * fScale.y();
1368     metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1369     metrics->fXMin = xmin * fScale.y();
1370     metrics->fXMax = xmax * fScale.y();
1371     metrics->fXHeight = x_height;
1372     metrics->fCapHeight = cap_height;
1373     metrics->fUnderlineThickness = underlineThickness * fScale.y();
1374     metrics->fUnderlinePosition = underlinePosition * fScale.y();
1375 }
1376 
1377 ///////////////////////////////////////////////////////////////////////////////
1378 
1379 // hand-tuned value to reduce outline embolden strength
1380 #ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1381     #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1382         #define SK_OUTLINE_EMBOLDEN_DIVISOR   34
1383     #else
1384         #define SK_OUTLINE_EMBOLDEN_DIVISOR   24
1385     #endif
1386 #endif
1387 
1388 ///////////////////////////////////////////////////////////////////////////////
1389 
emboldenIfNeeded(FT_Face face,FT_GlyphSlot glyph)1390 void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1391 {
1392     // check to see if the embolden bit is set
1393     if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1394         return;
1395     }
1396 
1397     switch (glyph->format) {
1398         case FT_GLYPH_FORMAT_OUTLINE:
1399             FT_Pos strength;
1400             strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1401                        / SK_OUTLINE_EMBOLDEN_DIVISOR;
1402             FT_Outline_Embolden(&glyph->outline, strength);
1403             break;
1404         case FT_GLYPH_FORMAT_BITMAP:
1405             FT_GlyphSlot_Own_Bitmap(glyph);
1406             FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1407             break;
1408         default:
1409             SkDEBUGFAIL("unknown glyph format");
1410     }
1411 }
1412 
1413 ///////////////////////////////////////////////////////////////////////////////
1414 
1415 #include "SkUtils.h"
1416 
next_utf8(const void ** chars)1417 static SkUnichar next_utf8(const void** chars) {
1418     return SkUTF8_NextUnichar((const char**)chars);
1419 }
1420 
next_utf16(const void ** chars)1421 static SkUnichar next_utf16(const void** chars) {
1422     return SkUTF16_NextUnichar((const uint16_t**)chars);
1423 }
1424 
next_utf32(const void ** chars)1425 static SkUnichar next_utf32(const void** chars) {
1426     const SkUnichar** uniChars = (const SkUnichar**)chars;
1427     SkUnichar uni = **uniChars;
1428     *uniChars += 1;
1429     return uni;
1430 }
1431 
1432 typedef SkUnichar (*EncodingProc)(const void**);
1433 
find_encoding_proc(SkTypeface::Encoding enc)1434 static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1435     static const EncodingProc gProcs[] = {
1436         next_utf8, next_utf16, next_utf32
1437     };
1438     SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1439     return gProcs[enc];
1440 }
1441 
onCharsToGlyphs(const void * chars,Encoding encoding,uint16_t glyphs[],int glyphCount) const1442 int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1443                                          uint16_t glyphs[], int glyphCount) const
1444 {
1445     AutoFTAccess fta(this);
1446     FT_Face face = fta.face();
1447     if (!face) {
1448         if (glyphs) {
1449             sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1450         }
1451         return 0;
1452     }
1453 
1454     EncodingProc next_uni_proc = find_encoding_proc(encoding);
1455 
1456     if (nullptr == glyphs) {
1457         for (int i = 0; i < glyphCount; ++i) {
1458             if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1459                 return i;
1460             }
1461         }
1462         return glyphCount;
1463     } else {
1464         int first = glyphCount;
1465         for (int i = 0; i < glyphCount; ++i) {
1466             unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1467             glyphs[i] = SkToU16(id);
1468             if (0 == id && i < first) {
1469                 first = i;
1470             }
1471         }
1472         return first;
1473     }
1474 }
1475 
onCountGlyphs() const1476 int SkTypeface_FreeType::onCountGlyphs() const {
1477     AutoFTAccess fta(this);
1478     FT_Face face = fta.face();
1479     return face ? face->num_glyphs : 0;
1480 }
1481 
onCreateFamilyNameIterator() const1482 SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
1483     SkTypeface::LocalizedStrings* nameIter =
1484         SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
1485     if (nullptr == nameIter) {
1486         SkString familyName;
1487         this->getFamilyName(&familyName);
1488         SkString language("und"); //undetermined
1489         nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1490     }
1491     return nameIter;
1492 }
1493 
onGetTableTags(SkFontTableTag tags[]) const1494 int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1495     AutoFTAccess fta(this);
1496     FT_Face face = fta.face();
1497 
1498     FT_ULong tableCount = 0;
1499     FT_Error error;
1500 
1501     // When 'tag' is nullptr, returns number of tables in 'length'.
1502     error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
1503     if (error) {
1504         return 0;
1505     }
1506 
1507     if (tags) {
1508         for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1509             FT_ULong tableTag;
1510             FT_ULong tablelength;
1511             error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1512             if (error) {
1513                 return 0;
1514             }
1515             tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1516         }
1517     }
1518     return tableCount;
1519 }
1520 
onGetTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const1521 size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1522                                            size_t length, void* data) const
1523 {
1524     AutoFTAccess fta(this);
1525     FT_Face face = fta.face();
1526 
1527     FT_ULong tableLength = 0;
1528     FT_Error error;
1529 
1530     // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1531     error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
1532     if (error) {
1533         return 0;
1534     }
1535 
1536     if (offset > tableLength) {
1537         return 0;
1538     }
1539     FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
1540     if (data) {
1541         error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1542         if (error) {
1543             return 0;
1544         }
1545     }
1546 
1547     return size;
1548 }
1549 
1550 ///////////////////////////////////////////////////////////////////////////////
1551 ///////////////////////////////////////////////////////////////////////////////
1552 
Scanner()1553 SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
1554     if (FT_New_Library(&gFTMemory, &fLibrary)) {
1555         return;
1556     }
1557     FT_Add_Default_Modules(fLibrary);
1558 }
~Scanner()1559 SkTypeface_FreeType::Scanner::~Scanner() {
1560     if (fLibrary) {
1561         FT_Done_Library(fLibrary);
1562     }
1563 }
1564 
openFace(SkStreamAsset * stream,int ttcIndex,FT_Stream ftStream) const1565 FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
1566                                                FT_Stream ftStream) const
1567 {
1568     if (fLibrary == nullptr) {
1569         return nullptr;
1570     }
1571 
1572     FT_Open_Args args;
1573     memset(&args, 0, sizeof(args));
1574 
1575     const void* memoryBase = stream->getMemoryBase();
1576 
1577     if (memoryBase) {
1578         args.flags = FT_OPEN_MEMORY;
1579         args.memory_base = (const FT_Byte*)memoryBase;
1580         args.memory_size = stream->getLength();
1581     } else {
1582         memset(ftStream, 0, sizeof(*ftStream));
1583         ftStream->size = stream->getLength();
1584         ftStream->descriptor.pointer = stream;
1585         ftStream->read  = sk_ft_stream_io;
1586         ftStream->close = sk_ft_stream_close;
1587 
1588         args.flags = FT_OPEN_STREAM;
1589         args.stream = ftStream;
1590     }
1591 
1592     FT_Face face;
1593     if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
1594         return nullptr;
1595     }
1596     return face;
1597 }
1598 
recognizedFont(SkStreamAsset * stream,int * numFaces) const1599 bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
1600     SkAutoMutexAcquire libraryLock(fLibraryMutex);
1601 
1602     FT_StreamRec streamRec;
1603     FT_Face face = this->openFace(stream, -1, &streamRec);
1604     if (nullptr == face) {
1605         return false;
1606     }
1607 
1608     *numFaces = face->num_faces;
1609 
1610     FT_Done_Face(face);
1611     return true;
1612 }
1613 
1614 #include "SkTSearch.h"
scanFont(SkStreamAsset * stream,int ttcIndex,SkString * name,SkFontStyle * style,bool * isFixedPitch,AxisDefinitions * axes) const1615 bool SkTypeface_FreeType::Scanner::scanFont(
1616     SkStreamAsset* stream, int ttcIndex,
1617     SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
1618 {
1619     SkAutoMutexAcquire libraryLock(fLibraryMutex);
1620 
1621     FT_StreamRec streamRec;
1622     FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
1623     if (nullptr == face) {
1624         return false;
1625     }
1626 
1627     int weight = SkFontStyle::kNormal_Weight;
1628     int width = SkFontStyle::kNormal_Width;
1629     SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
1630     if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1631         weight = SkFontStyle::kBold_Weight;
1632     }
1633     if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1634         slant = SkFontStyle::kItalic_Slant;
1635     }
1636 
1637     PS_FontInfoRec psFontInfo;
1638     TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1639     if (os2 && os2->version != 0xffff) {
1640         weight = os2->usWeightClass;
1641         width = os2->usWidthClass;
1642 
1643         // OS/2::fsSelection bit 9 indicates oblique.
1644         if (SkToBool(os2->fsSelection & (1u << 9))) {
1645             slant = SkFontStyle::kOblique_Slant;
1646         }
1647     } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1648         static const struct {
1649             char const * const name;
1650             int const weight;
1651         } commonWeights [] = {
1652             // There are probably more common names, but these are known to exist.
1653             { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
1654             { "black", SkFontStyle::kBlack_Weight },
1655             { "bold", SkFontStyle::kBold_Weight },
1656             { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1657             { "demi", SkFontStyle::kSemiBold_Weight },
1658             { "demibold", SkFontStyle::kSemiBold_Weight },
1659             { "extra", SkFontStyle::kExtraBold_Weight },
1660             { "extrabold", SkFontStyle::kExtraBold_Weight },
1661             { "extralight", SkFontStyle::kExtraLight_Weight },
1662             { "hairline", SkFontStyle::kThin_Weight },
1663             { "heavy", SkFontStyle::kBlack_Weight },
1664             { "light", SkFontStyle::kLight_Weight },
1665             { "medium", SkFontStyle::kMedium_Weight },
1666             { "normal", SkFontStyle::kNormal_Weight },
1667             { "plain", SkFontStyle::kNormal_Weight },
1668             { "regular", SkFontStyle::kNormal_Weight },
1669             { "roman", SkFontStyle::kNormal_Weight },
1670             { "semibold", SkFontStyle::kSemiBold_Weight },
1671             { "standard", SkFontStyle::kNormal_Weight },
1672             { "thin", SkFontStyle::kThin_Weight },
1673             { "ultra", SkFontStyle::kExtraBold_Weight },
1674             { "ultrablack", SkFontStyle::kExtraBlack_Weight },
1675             { "ultrabold", SkFontStyle::kExtraBold_Weight },
1676             { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
1677             { "ultralight", SkFontStyle::kExtraLight_Weight },
1678         };
1679         int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
1680                                         psFontInfo.weight, sizeof(commonWeights[0]));
1681         if (index >= 0) {
1682             weight = commonWeights[index].weight;
1683         } else {
1684             SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
1685         }
1686     }
1687 
1688     if (name) {
1689         name->set(face->family_name);
1690     }
1691     if (style) {
1692         *style = SkFontStyle(weight, width, slant);
1693     }
1694     if (isFixedPitch) {
1695         *isFixedPitch = FT_IS_FIXED_WIDTH(face);
1696     }
1697 
1698     if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
1699         FT_MM_Var* variations = nullptr;
1700         FT_Error err = FT_Get_MM_Var(face, &variations);
1701         if (err) {
1702             SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1703                       face->family_name));
1704             return false;
1705         }
1706         SkAutoFree autoFreeVariations(variations);
1707 
1708         axes->reset(variations->num_axis);
1709         for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1710             const FT_Var_Axis& ftAxis = variations->axis[i];
1711             (*axes)[i].fTag = ftAxis.tag;
1712             (*axes)[i].fMinimum = ftAxis.minimum;
1713             (*axes)[i].fDefault = ftAxis.def;
1714             (*axes)[i].fMaximum = ftAxis.maximum;
1715         }
1716     }
1717 
1718     FT_Done_Face(face);
1719     return true;
1720 }
1721 
computeAxisValues(AxisDefinitions axisDefinitions,const SkFontMgr::FontParameters::Axis * requestedAxes,int requestedAxisCount,SkFixed * axisValues,const SkString & name)1722 /*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1723     AxisDefinitions axisDefinitions,
1724     const SkFontMgr::FontParameters::Axis* requestedAxes, int requestedAxisCount,
1725     SkFixed* axisValues,
1726     const SkString& name)
1727 {
1728     for (int i = 0; i < axisDefinitions.count(); ++i) {
1729         const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
1730         const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1731         const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
1732         axisValues[i] = axisDefinition.fDefault;
1733         for (int j = 0; j < requestedAxisCount; ++j) {
1734             const SkFontMgr::FontParameters::Axis& axisSpecified = requestedAxes[j];
1735             if (axisDefinition.fTag == axisSpecified.fTag) {
1736                 const SkScalar axisValue = SkTPin(axisSpecified.fStyleValue, axisMin, axisMax);
1737                 if (axisSpecified.fStyleValue != axisValue) {
1738                     SkDEBUGF(("Requested font axis value out of range: "
1739                               "%s '%c%c%c%c' %f; pinned to %f.\n",
1740                               name.c_str(),
1741                               (axisDefinition.fTag >> 24) & 0xFF,
1742                               (axisDefinition.fTag >> 16) & 0xFF,
1743                               (axisDefinition.fTag >>  8) & 0xFF,
1744                               (axisDefinition.fTag      ) & 0xFF,
1745                               SkScalarToDouble(axisSpecified.fStyleValue),
1746                               SkScalarToDouble(axisValue)));
1747                 }
1748                 axisValues[i] = SkScalarToFixed(axisValue);
1749                 break;
1750             }
1751         }
1752         // TODO: warn on defaulted axis?
1753     }
1754 
1755     SkDEBUGCODE(
1756         // Check for axis specified, but not matched in font.
1757         for (int i = 0; i < requestedAxisCount; ++i) {
1758             SkFourByteTag skTag = requestedAxes[i].fTag;
1759             bool found = false;
1760             for (int j = 0; j < axisDefinitions.count(); ++j) {
1761                 if (skTag == axisDefinitions[j].fTag) {
1762                     found = true;
1763                     break;
1764                 }
1765             }
1766             if (!found) {
1767                 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1768                           name.c_str(),
1769                           (skTag >> 24) & 0xFF,
1770                           (skTag >> 16) & 0xFF,
1771                           (skTag >>  8) & 0xFF,
1772                           (skTag)       & 0xFF));
1773             }
1774         }
1775     )
1776 }
1777