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