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