2 * Copyright 2006 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkAdvancedTypefaceMetrics.h"
11 #include "SkColorPriv.h"
12 #include "SkDescriptor.h"
14 #include "SkFontDescriptor.h"
15 #include "SkFontHost_FreeType_common.h"
17 #include "SkMakeUnique.h"
19 #include "SkMaskGamma.h"
20 #include "SkMatrix22.h"
22 #include "SkOTUtils.h"
24 #include "SkScalerContext.h"
27 #include "SkTemplates.h"
31 #include FT_ADVANCES_H
33 #include FT_FREETYPE_H
34 #include FT_LCD_FILTER_H
36 #include FT_MULTIPLE_MASTERS_H
40 #include FT_TRUETYPE_TABLES_H
41 #include FT_TYPE1_TABLES_H
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))
51 # define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (3 << 16) | (11 << 8) | (SK_FREETYPE_DLOPEN))
54 #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
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.
62 # define FT_LOAD_COLOR ( 1L << 20 )
63 # define FT_PIXEL_MODE_BGRA 7
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 )
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
77 static bool isLCD(const SkScalerContext::Rec& rec) {
78 return SkMask::kLCD16_Format == rec.fMaskFormat;
81 //////////////////////////////////////////////////////////////////////////
84 static void* sk_ft_alloc(FT_Memory, long size) {
85 return sk_malloc_throw(size);
87 static void sk_ft_free(FT_Memory, void* block) {
90 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
91 return sk_realloc_throw(block, new_size);
94 FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
96 class FreeTypeLibrary : SkNoncopyable {
99 : fGetVarDesignCoordinates(nullptr)
101 , fIsLCDSupported(false)
104 if (FT_New_Library(&gFTMemory, &fLibrary)) {
107 FT_Add_Default_Modules(fLibrary);
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 .
115 FT_Int major, minor, patch;
116 FT_Library_Version(fLibrary, &major, &minor, &patch);
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);
125 *(void**)(&fGetVarDesignCoordinates) = dlsym(self, "FT_Get_Var_Design_Coordinates");
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);
138 FT_Set_Default_PropertiesProc setDefaultProperties;
139 *(void**)(&setDefaultProperties) = dlsym(self, "FT_Set_Default_Properties");
142 if (setDefaultProperties) {
143 setDefaultProperties(fLibrary);
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.
158 FT_Done_Library(fLibrary);
162 FT_Library library() { return fLibrary; }
163 bool isLCDSupported() { return fIsLCDSupported; }
164 int lcdExtra() { return fLCDExtra; }
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;
175 bool fIsLCDSupported;
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*);
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);
195 SK_DECLARE_STATIC_MUTEX(gFTMutex);
196 static FreeTypeLibrary* gFTLibrary;
197 static SkFaceRec* gFaceRecHead;
199 // Private to ref_ft_library and unref_ft_library
202 // Caller must lock gFTMutex before calling this function.
203 static bool ref_ft_library() {
204 gFTMutex.assertHeld();
205 SkASSERT(gFTCount >= 0);
208 SkASSERT(nullptr == gFTLibrary);
209 gFTLibrary = new FreeTypeLibrary;
212 return gFTLibrary->library();
215 // Caller must lock gFTMutex before calling this function.
216 static void unref_ft_library() {
217 gFTMutex.assertHeld();
218 SkASSERT(gFTCount > 0);
222 SkASSERT(nullptr == gFaceRecHead);
223 SkASSERT(nullptr != gFTLibrary);
225 SkDEBUGCODE(gFTLibrary = nullptr;)
229 ///////////////////////////////////////////////////////////////////////////
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;
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;
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;
249 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
253 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
254 unsigned long offset,
255 unsigned char* buffer,
258 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
261 if (!stream->seek(offset)) {
264 count = stream->read(buffer, count);
269 static void sk_ft_stream_close(FT_Stream) {}
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)
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;
283 static void ft_face_setup_axes(SkFaceRec* rec, const SkFontData& data) {
284 if (!(rec->fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
288 // If a named variation is requested, don't overwrite the named variation's position.
289 if (data.getIndex() > 0xFFFF) {
290 rec->fNamedVariationSpecified = true;
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));
301 SkAutoFree autoFreeVariations(variations);
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()));
310 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
311 for (int i = 0; i < data.getAxisCount(); ++i) {
312 coords[i] = data.getAxis()[i];
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));
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];
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();
332 const SkFontID fontID = typeface->uniqueID();
333 SkFaceRec* cachedRec = gFaceRecHead;
335 if (cachedRec->fFontID == fontID) {
336 SkASSERT(cachedRec->fFace);
337 cachedRec->fRefCnt += 1;
340 cachedRec = cachedRec->fNext;
343 std::unique_ptr<SkFontData> data = typeface->makeFontData();
344 if (nullptr == data || !data->hasStream()) {
348 std::unique_ptr<SkFaceRec> rec(new SkFaceRec(data->detachStream(), fontID));
351 memset(&args, 0, sizeof(args));
352 const void* memoryBase = rec->fSkStream->getMemoryBase();
354 args.flags = FT_OPEN_MEMORY;
355 args.memory_base = (const FT_Byte*)memoryBase;
356 args.memory_size = rec->fSkStream->getLength();
358 args.flags = FT_OPEN_STREAM;
359 args.stream = &rec->fFTStream;
364 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
366 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
369 rec->fFace.reset(rawFace);
371 SkASSERT(rec->fFace);
373 ft_face_setup_axes(rec.get(), *data);
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);
385 rec->fNext = gFaceRecHead;
386 gFaceRecHead = rec.get();
387 return rec.release();
390 // Caller must lock gFTMutex before calling this function.
391 static void unref_ft_face(SkFaceRec* faceRec) {
392 gFTMutex.assertHeld();
394 SkFaceRec* rec = gFaceRecHead;
395 SkFaceRec* prev = nullptr;
397 SkFaceRec* next = rec->fNext;
398 if (rec->fFace == faceRec->fFace) {
399 if (--rec->fRefCnt == 0) {
412 SkDEBUGFAIL("shouldn't get here, face not in list");
417 AutoFTAccess(const SkTypeface* tf) : fFaceRec(nullptr) {
419 if (!ref_ft_library()) {
422 fFaceRec = ref_ft_face(tf);
427 unref_ft_face(fFaceRec);
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;
444 ///////////////////////////////////////////////////////////////////////////
446 class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
448 SkScalerContext_FreeType(sk_sp<SkTypeface>,
449 const SkScalerContextEffects&,
450 const SkDescriptor* desc);
451 virtual ~SkScalerContext_FreeType();
453 bool success() const {
454 return fFTSize != nullptr && fFace != nullptr;
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;
468 using UnrefFTFace = SkFunctionWrapper<void, SkFaceRec, unref_ft_face>;
469 std::unique_ptr<SkFaceRec, UnrefFTFace> fFaceRec;
471 FT_Face fFace; // Borrowed face from gFaceRecHead.
472 FT_Size fFTSize; // The size on the fFace for this scaler.
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.
479 SkMatrix fMatrix22Scalar;
480 /** Same as fMatrix22Scalar, but in FreeType units and space. */
482 /** The actual size requested. */
485 uint32_t fLoadGlyphFlags;
486 bool fDoLinearMetrics;
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&);
501 ///////////////////////////////////////////////////////////////////////////
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;
509 static bool canSubset(FT_Face face) {
510 FT_UShort fsType = FT_Get_FSType_Flags(face);
511 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
514 static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
515 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
518 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
520 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
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);
530 SkUnichar charCode = FT_Get_First_Char(face, &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;
537 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
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();
551 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
552 info->fFontName.set(FT_Get_Postscript_Name(face));
554 if (FT_HAS_MULTIPLE_MASTERS(face)) {
555 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
557 if (!canEmbed(face)) {
558 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
560 if (!canSubset(face)) {
561 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
563 info->fLastGlyphID = face->num_glyphs - 1;
564 info->fEmSize = 1000;
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;
576 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
577 info->fEmSize = ttHeader->Units_Per_EM;
580 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
583 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
584 if (FT_IS_FIXED_WIDTH(face)) {
585 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
587 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
588 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
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);
598 info->fItalicAngle = 0;
601 info->fAscent = face->ascender;
602 info->fDescent = face->descender;
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;
608 char stem_chars[] = {'i', 'I', '!', '1'};
609 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
611 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
612 int16_t width = bbox.xMax - bbox.xMin;
613 if (width > 0 && width < min_width) {
615 info->fStemV = min_width;
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;
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)
635 info->fCapHeight = os2Table->sCapHeight;
637 // Figure out a good guess for CapHeight: average the height of M and X.
638 FT_BBox m_bbox, x_bbox;
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;
649 // Last resort, use the ascent.
650 info->fCapHeight = info->fAscent;
654 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
655 face->bbox.xMax, face->bbox.yMin);
657 if (!FT_IS_SCALABLE(face)) {
658 perGlyphInfo = kNo_PerGlyphInfo;
661 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
662 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
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);
675 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
676 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
679 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
685 ///////////////////////////////////////////////////////////////////////////
687 static bool bothZero(SkScalar a, SkScalar b) {
688 return 0 == a && 0 == b;
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]));
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);
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);
719 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
720 SkAutoMutexAcquire ama(gFTMutex);
722 if (!gFTLibrary->isLCDSupported()) {
723 // If the runtime Freetype library doesn't support LCD, disable it here.
724 rec->fMaskFormat = SkMask::kA8_Format;
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;
734 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
735 if (SkPaint::kNo_Hinting != h) {
736 h = SkPaint::kSlight_Hinting;
740 // rotated text looks bad with hinting, so we disable it as needed
741 if (!isAxisAligned(*rec)) {
742 h = SkPaint::kNo_Hinting;
746 #ifndef SK_GAMMA_APPLY_TO_A8
748 // SRGBTODO: Is this correct? Do we want contrast boost?
749 rec->ignorePreBlend();
754 int SkTypeface_FreeType::onGetUPEM() const {
755 AutoFTAccess fta(this);
756 FT_Face face = fta.face();
757 return face ? face->units_per_EM : 0;
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)) {
768 for (int i = 0; i < count - 1; ++i) {
770 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
771 FT_KERNING_UNSCALED, &delta);
775 adjustments[i] = delta.x;
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"));
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
795 } else if (chosenPPEM < requestedPPEM) {
796 // attempt to increase chosenPPEM
797 if (chosenPPEM < strikePPEM) {
798 chosenPPEM = strikePPEM;
799 chosenStrikeIndex = strikeIndex;
802 // attempt to decrease chosenPPEM, but not below requestedPPEM
803 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
804 chosenPPEM = strikePPEM;
805 chosenStrikeIndex = strikeIndex;
809 return chosenStrikeIndex;
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)
820 SkAutoMutexAcquire ac(gFTMutex);
822 if (!ref_ft_library()) {
826 fFaceRec.reset(ref_ft_face(this->getTypeface()));
828 // load the font file
829 if (nullptr == fFaceRec) {
830 SkDEBUGF(("Could not create FT_Face.\n"));
834 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
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());
843 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
845 // compute the flags we send to Load_Glyph
846 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
848 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
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;
858 switch (fRec.getHinting()) {
859 case SkPaint::kNo_Hinting:
860 loadFlags = FT_LOAD_NO_HINTING;
861 linearMetrics = true;
863 case SkPaint::kSlight_Hinting:
864 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
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
871 loadFlags = FT_LOAD_NO_AUTOHINT;
875 case SkPaint::kFull_Hinting:
876 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
877 loadFlags = FT_LOAD_FORCE_AUTOHINT;
880 loadFlags = FT_LOAD_TARGET_NORMAL;
883 loadFlags = FT_LOAD_TARGET_LCD_V;
885 loadFlags = FT_LOAD_TARGET_LCD;
890 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
895 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
896 loadFlags |= FT_LOAD_NO_BITMAP;
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;
904 // Use vertical layout if requested.
905 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
906 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
909 loadFlags |= FT_LOAD_COLOR;
911 fLoadGlyphFlags = loadFlags;
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 {
917 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
919 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
924 if (nullptr == ftSize) {
925 SkDEBUGF(("Could not create FT_Size.\n"));
929 FT_Error err = FT_Activate_Size(ftSize.get());
931 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", fFaceRec->fFace->family_name, err));
935 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
936 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
938 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
939 fFaceRec->fFace->family_name, fScale.fX, fScale.fY, err));
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));
950 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
952 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
953 fFaceRec->fFace->family_name, fStrikeIndex, err));
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());
967 // FreeType does not provide linear metrics for bitmap fonts.
968 linearMetrics = false;
970 // FreeType documentation says:
971 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
972 // Bitmap-only fonts ignore this flag.
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;
978 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY));
982 fFTSize = ftSize.release();
983 fFace = fFaceRec->fFace.get();
984 fDoLinearMetrics = linearMetrics;
987 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
988 SkAutoMutexAcquire ac(gFTMutex);
990 if (fFTSize != nullptr) {
991 FT_Done_Size(fFTSize);
999 /* We call this before each use of the fFace, since we may be sharing
1000 this face with other context (at different sizes).
1002 FT_Error SkScalerContext_FreeType::setupSize() {
1003 gFTMutex.assertHeld();
1004 FT_Error err = FT_Activate_Size(fFTSize);
1008 FT_Set_Transform(fFace, &fMatrix22, nullptr);
1012 unsigned SkScalerContext_FreeType::generateGlyphCount() {
1013 return fFace->num_glyphs;
1016 uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
1017 SkAutoMutexAcquire ac(gFTMutex);
1018 return SkToU16(FT_Get_Char_Index( fFace, uni ));
1021 SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
1022 SkAutoMutexAcquire ac(gFTMutex);
1023 // iterate through each cmap entry, looking for matching glyph indices
1025 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
1027 while (glyphIndex != 0) {
1028 if (glyphIndex == glyph) {
1031 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
1037 static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
1038 return SkFixedToScalar(x);
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...
1045 if (fDoLinearMetrics) {
1046 SkAutoMutexAcquire ac(gFTMutex);
1048 if (this->setupSize()) {
1049 glyph->zeroMetrics();
1056 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
1057 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
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);
1069 /* otherwise, we need to load/hint the glyph, which is slower */
1070 this->generateMetrics(glyph);
1074 void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1076 bool snapToPixelBoundary) {
1078 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
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
1090 // outset the box to integral boundaries
1091 if (snapToPixelBoundary) {
1094 bbox->xMax = (bbox->xMax + 63) & ~63;
1095 bbox->yMax = (bbox->yMax + 63) & ~63;
1098 // Must come after snapToPixelBoundary so that the width and height are
1099 // consistent. Otherwise asserts will fire later on when generating the
1101 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
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;
1113 bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1114 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
1118 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
1121 emboldenIfNeeded(fFace, fFace->glyph);
1122 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1126 void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1129 glyph->fHeight += gFTLibrary->lcdExtra();
1130 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
1132 glyph->fWidth += gFTLibrary->lcdExtra();
1133 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
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());
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();
1151 return mechanism && policy;
1154 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1155 SkAutoMutexAcquire ac(gFTMutex);
1157 glyph->fRsbDelta = 0;
1158 glyph->fLsbDelta = 0;
1162 if (this->setupSize()) {
1163 glyph->zeroMetrics();
1167 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1168 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
1170 glyph->zeroMetrics();
1173 emboldenIfNeeded(fFace, fFace->glyph);
1175 switch ( fFace->glyph->format ) {
1176 case FT_GLYPH_FORMAT_OUTLINE:
1177 if (0 == fFace->glyph->outline.n_contours) {
1184 getBBoxForCurrentGlyph(glyph, &bbox, true);
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));
1191 updateGlyphIfLCD(glyph);
1195 case FT_GLYPH_FORMAT_BITMAP:
1196 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
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);
1205 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1206 glyph->fMaskFormat = SkMask::kARGB32_Format;
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()));
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());
1228 SkDEBUGFAIL("unknown glyph format");
1229 glyph->zeroMetrics();
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);
1239 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1240 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
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);
1248 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1249 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
1251 if (fRec.fFlags & kDevKernText_Flag) {
1252 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1253 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
1258 #ifdef ENABLE_GLYPH_SPEW
1259 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
1263 static void clear_glyph_image(const SkGlyph& glyph) {
1264 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1267 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1268 SkAutoMutexAcquire ac(gFTMutex);
1270 if (this->setupSize()) {
1271 clear_glyph_image(glyph);
1275 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
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);
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;
1292 generateGlyphImage(fFace, glyph, *bitmapMatrix);
1296 void SkScalerContext_FreeType::generatePath(SkGlyphID glyphID, SkPath* path) {
1297 SkAutoMutexAcquire ac(gFTMutex);
1301 if (this->setupSize()) {
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)
1310 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
1313 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1314 glyphID, flags, err));
1318 emboldenIfNeeded(fFace, fFace->glyph);
1320 generateGlyphPath(fFace, path);
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) {
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));
1333 void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
1334 if (nullptr == metrics) {
1338 SkAutoMutexAcquire ac(gFTMutex);
1340 if (this->setupSize()) {
1341 sk_bzero(metrics, sizeof(*metrics));
1345 FT_Face face = fFace;
1347 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1348 SkScalar upem = SkIntToScalar(face->units_per_EM);
1350 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1352 upem = SkIntToScalar(ttHeader->Units_Per_EM);
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);
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();
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;
1383 ascent = -SkIntToScalar(face->ascender) / upem;
1384 descent = -SkIntToScalar(face->descender) / upem;
1385 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
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;
1395 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1396 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1398 // we may be able to synthesize x_height and cap_height from outline
1401 if (getCBoxForLetter('x', &bbox)) {
1402 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1407 if (getCBoxForLetter('H', &bbox)) {
1408 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
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;
1418 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1419 ymin = descent + leading;
1420 ymax = ascent - descent;
1421 underlineThickness = 0;
1422 underlinePosition = 0;
1424 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1425 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1427 sk_bzero(metrics, sizeof(*metrics));
1431 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1433 x_height = -ascent * fScale.y();
1435 if (!avgCharWidth) {
1436 avgCharWidth = xmax - xmin;
1439 cap_height = -ascent * fScale.y();
1442 // disallow negative linespacing
1443 if (leading < 0.0f) {
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();
1461 ///////////////////////////////////////////////////////////////////////////////
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
1468 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1472 ///////////////////////////////////////////////////////////////////////////////
1474 void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1476 // check to see if the embolden bit is set
1477 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1481 switch (glyph->format) {
1482 case FT_GLYPH_FORMAT_OUTLINE:
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);
1488 case FT_GLYPH_FORMAT_BITMAP:
1489 FT_GlyphSlot_Own_Bitmap(glyph);
1490 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1493 SkDEBUGFAIL("unknown glyph format");
1497 ///////////////////////////////////////////////////////////////////////////////
1499 #include "SkUtils.h"
1501 static SkUnichar next_utf8(const void** chars) {
1502 return SkUTF8_NextUnichar((const char**)chars);
1505 static SkUnichar next_utf16(const void** chars) {
1506 return SkUTF16_NextUnichar((const uint16_t**)chars);
1509 static SkUnichar next_utf32(const void** chars) {
1510 const SkUnichar** uniChars = (const SkUnichar**)chars;
1511 SkUnichar uni = **uniChars;
1516 typedef SkUnichar (*EncodingProc)(const void**);
1518 static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1519 static const EncodingProc gProcs[] = {
1520 next_utf8, next_utf16, next_utf32
1522 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1526 int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
1527 uint16_t glyphs[], int glyphCount) const
1529 AutoFTAccess fta(this);
1530 FT_Face face = fta.face();
1533 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1538 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1540 if (nullptr == glyphs) {
1541 for (int i = 0; i < glyphCount; ++i) {
1542 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
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) {
1560 int SkTypeface_FreeType::onCountGlyphs() const {
1561 AutoFTAccess fta(this);
1562 FT_Face face = fta.face();
1563 return face ? face->num_glyphs : 0;
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);
1578 int SkTypeface_FreeType::onGetVariationDesignPosition(
1579 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1581 AutoFTAccess fta(this);
1582 FT_Face face = fta.face();
1584 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1588 FT_MM_Var* variations = nullptr;
1589 if (FT_Get_MM_Var(face, &variations)) {
1592 SkAutoFree autoFreeVariations(variations);
1594 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
1595 return variations->num_axis;
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()))
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]);
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]);
1612 } else if (fta.isNamedVariationSpecified()) {
1613 // The font has axes, they cannot be retrieved, and some named axis was specified.
1616 // The font has axes, they cannot be retrieved, but no named instance was specified.
1620 return variations->num_axis;
1623 int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1624 AutoFTAccess fta(this);
1625 FT_Face face = fta.face();
1627 FT_ULong tableCount = 0;
1630 // When 'tag' is nullptr, returns number of tables in 'length'.
1631 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
1637 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1639 FT_ULong tablelength;
1640 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1644 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1650 size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1651 size_t length, void* data) const
1653 AutoFTAccess fta(this);
1654 FT_Face face = fta.face();
1656 FT_ULong tableLength = 0;
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);
1665 if (offset > tableLength) {
1668 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
1670 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1679 ///////////////////////////////////////////////////////////////////////////////
1680 ///////////////////////////////////////////////////////////////////////////////
1682 SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
1683 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1686 FT_Add_Default_Modules(fLibrary);
1688 SkTypeface_FreeType::Scanner::~Scanner() {
1690 FT_Done_Library(fLibrary);
1694 FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
1695 FT_Stream ftStream) const
1697 if (fLibrary == nullptr) {
1702 memset(&args, 0, sizeof(args));
1704 const void* memoryBase = stream->getMemoryBase();
1707 args.flags = FT_OPEN_MEMORY;
1708 args.memory_base = (const FT_Byte*)memoryBase;
1709 args.memory_size = stream->getLength();
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;
1717 args.flags = FT_OPEN_STREAM;
1718 args.stream = ftStream;
1722 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
1728 bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
1729 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1731 FT_StreamRec streamRec;
1732 FT_Face face = this->openFace(stream, -1, &streamRec);
1733 if (nullptr == face) {
1737 *numFaces = face->num_faces;
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
1748 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1750 FT_StreamRec streamRec;
1751 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
1752 if (nullptr == face) {
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;
1762 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1763 slant = SkFontStyle::kItalic_Slant;
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;
1772 // OS/2::fsSelection bit 9 indicates oblique.
1773 if (SkToBool(os2->fsSelection & (1u << 9))) {
1774 slant = SkFontStyle::kOblique_Slant;
1776 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1777 static const struct {
1778 char const * const name;
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 },
1808 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
1809 psFontInfo.weight, sizeof(commonWeights[0]));
1811 weight = commonWeights[index].weight;
1813 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
1818 name->set(face->family_name);
1821 *style = SkFontStyle(weight, width, slant);
1824 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
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);
1831 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1832 face->family_name));
1835 SkAutoFree autoFreeVariations(variations);
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;
1851 /*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1852 AxisDefinitions axisDefinitions,
1853 const SkFontArguments::VariationPosition position,
1854 SkFixed* axisValues,
1855 const SkString& name)
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",
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)));
1877 axisValues[i] = SkScalarToFixed(axisValue);
1881 // TODO: warn on defaulted axis?
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;
1889 for (int j = 0; j < axisDefinitions.count(); ++j) {
1890 if (skTag == axisDefinitions[j].fTag) {
1896 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1898 (skTag >> 24) & 0xFF,
1899 (skTag >> 16) & 0xFF,
1900 (skTag >> 8) & 0xFF,