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 "include/core/SkBBHFactory.h"
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkDrawable.h"
13 #include "include/core/SkFontMetrics.h"
14 #include "include/core/SkGraphics.h"
15 #include "include/core/SkPath.h"
16 #include "include/core/SkPictureRecorder.h"
17 #include "include/core/SkStream.h"
18 #include "include/core/SkString.h"
19 #include "include/private/SkColorData.h"
20 #include "include/private/base/SkTPin.h"
21 #include "include/private/base/SkTemplates.h"
22 #include "include/private/base/SkMalloc.h"
23 #include "include/private/base/SkMutex.h"
24 #include "include/private/base/SkTo.h"
25 #include "src/base/SkTSearch.h"
26 #include "src/core/SkAdvancedTypefaceMetrics.h"
27 #include "src/core/SkDescriptor.h"
28 #include "src/core/SkFDot6.h"
29 #include "src/core/SkFontDescriptor.h"
30 #include "src/core/SkGlyph.h"
31 #include "src/core/SkMask.h"
32 #include "src/core/SkMaskGamma.h"
33 #include "src/core/SkScalerContext.h"
34 #include "src/ports/SkFontHost_FreeType_common.h"
35 #include "src/sfnt/SkOTUtils.h"
36 #include "src/sfnt/SkSFNTHeader.h"
37 #include "src/sfnt/SkTTCFHeader.h"
38 #include "src/utils/SkCallableTraits.h"
39 #include "src/utils/SkMatrix22.h"
40
41 #include <memory>
42 #include <optional>
43 #include <tuple>
44
45 #include <ft2build.h>
46 #include <freetype/ftadvanc.h>
47 #include <freetype/ftimage.h>
48 #include <freetype/ftbitmap.h>
49 #ifdef FT_COLOR_H // 2.10.0
50 # include <freetype/ftcolor.h>
51 #endif
52 #include <freetype/freetype.h>
53 #include <freetype/ftlcdfil.h>
54 #include <freetype/ftmodapi.h>
55 #include <freetype/ftmm.h>
56 #include <freetype/ftoutln.h>
57 #include <freetype/ftsizes.h>
58 #include <freetype/ftsystem.h>
59 #include <freetype/tttables.h>
60 #include <freetype/t1tables.h>
61 #include <freetype/ftfntfmt.h>
62
63 using namespace skia_private;
64
65 namespace {
66 [[maybe_unused]] static inline const constexpr bool kSkShowTextBlitCoverage = false;
67
68 using SkUniqueFTFace = std::unique_ptr<FT_FaceRec, SkFunctionObject<FT_Done_Face>>;
69 using SkUniqueFTSize = std::unique_ptr<FT_SizeRec, SkFunctionObject<FT_Done_Size>>;
70 }
71
72 // SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
73 // Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
74 #define SK_FREETYPE_DLOPEN (0x1)
75 #ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
76 # if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (SK_BUILD_FOR_GOOGLE3)
77 # define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
78 # else
79 # define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (8 << 16) | (1 << 8) | (SK_FREETYPE_DLOPEN))
80 # endif
81 #endif
82 #if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
83 # include <dlfcn.h>
84 #endif
85
86 #ifdef TT_SUPPORT_COLRV1
87 // FT_ClipBox and FT_Get_Color_Glyph_ClipBox introduced VER-2-11-0-18-g47cf8ebf4
88 // FT_COLR_COMPOSITE_PLUS and renumbering introduced VER-2-11-0-21-ge40ae7569
89 // FT_SIZEOF_LONG_LONG introduced VER-2-11-0-31-gffdac8d67
90 // FT_PaintRadialGradient changed size and layout at VER-2-11-0-147-gd3d3ff76d
91 // FT_STATIC_CAST introduced VER-2-11-0-172-g9079c5d91
92 // So undefine TT_SUPPORT_COLRV1 before 2.11.1 but not if FT_STATIC_CAST is defined.
93 #if (((FREETYPE_MAJOR) < 2) || \
94 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) < 11) || \
95 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) == 11 && (FREETYPE_PATCH) < 1)) && \
96 !defined(FT_STATIC_CAST)
97 # undef TT_SUPPORT_COLRV1
98 #endif
99 #endif
100
101 //#define ENABLE_GLYPH_SPEW // for tracing calls
102 //#define DUMP_STRIKE_CREATION
103 //#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
104 //#define SK_GAMMA_APPLY_TO_A8
105
106 #if 1
107 #define LOG_INFO(...)
108 #else
109 #define LOG_INFO SkDEBUGF
110 #endif
111
isLCD(const SkScalerContextRec & rec)112 static bool isLCD(const SkScalerContextRec& rec) {
113 return SkMask::kLCD16_Format == rec.fMaskFormat;
114 }
115
SkFT_FixedToScalar(FT_Fixed x)116 static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
117 return SkFixedToScalar(x);
118 }
119
120 //////////////////////////////////////////////////////////////////////////
121
122 using FT_Alloc_size_t = SkCallableTraits<FT_Alloc_Func>::argument<1>::type;
123 static_assert(std::is_same<FT_Alloc_size_t, long >::value ||
124 std::is_same<FT_Alloc_size_t, size_t>::value,"");
125
126 extern "C" {
sk_ft_alloc(FT_Memory,FT_Alloc_size_t size)127 static void* sk_ft_alloc(FT_Memory, FT_Alloc_size_t size) {
128 return sk_malloc_canfail(size);
129 }
sk_ft_free(FT_Memory,void * block)130 static void sk_ft_free(FT_Memory, void* block) {
131 sk_free(block);
132 }
sk_ft_realloc(FT_Memory,FT_Alloc_size_t cur_size,FT_Alloc_size_t new_size,void * block)133 static void* sk_ft_realloc(FT_Memory, FT_Alloc_size_t cur_size,
134 FT_Alloc_size_t new_size, void* block) {
135 return sk_realloc_throw(block, new_size);
136 }
137 }
138 FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
139
140 class FreeTypeLibrary : SkNoncopyable {
141 public:
FreeTypeLibrary()142 FreeTypeLibrary() : fLibrary(nullptr) {
143 if (FT_New_Library(&gFTMemory, &fLibrary)) {
144 return;
145 }
146 FT_Add_Default_Modules(fLibrary);
147 FT_Set_Default_Properties(fLibrary);
148
149 // Subpixel anti-aliasing may be unfiltered until the LCD filter is set.
150 // Newer versions may still need this, so this test with side effects must come first.
151 // The default has changed over time, so this doesn't mean the same thing to all users.
152 FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT);
153 }
~FreeTypeLibrary()154 ~FreeTypeLibrary() {
155 if (fLibrary) {
156 FT_Done_Library(fLibrary);
157 }
158 }
159
library()160 FT_Library library() { return fLibrary; }
161
162 private:
163 FT_Library fLibrary;
164
165 // FT_Library_SetLcdFilterWeights 2.4.0
166 // FT_LOAD_COLOR 2.5.0
167 // FT_Pixel_Mode::FT_PIXEL_MODE_BGRA 2.5.0
168 // Thread safety in 2.6.0
169 // freetype/ftfntfmt.h (rename) 2.6.0
170 // Direct header inclusion 2.6.1
171 // FT_Get_Var_Design_Coordinates 2.7.1
172 // FT_LOAD_BITMAP_METRICS_ONLY 2.7.1
173 // FT_Set_Default_Properties 2.7.2
174 // The 'light' hinting is vertical only from 2.8.0
175 // FT_Get_Var_Axis_Flags 2.8.1
176 // FT_VAR_AXIS_FLAG_HIDDEN was introduced in FreeType 2.8.1
177 // --------------------
178 // FT_Done_MM_Var 2.9.0 (Currenty setting ft_free to a known allocator.)
179 // freetype/ftcolor.h 2.10.0 (Currently assuming if compiled with FT_COLOR_H runtime available.)
180
181 // Ubuntu 18.04 2.8.1
182 // Debian 10 2.9.1
183 // openSUSE Leap 15.2 2.10.1
184 // Fedora 32 2.10.4
185 // RHEL 8 2.9.1
186 };
187
f_t_mutex()188 static SkMutex& f_t_mutex() {
189 static SkMutex& mutex = *(new SkMutex);
190 return mutex;
191 }
192
193 static FreeTypeLibrary* gFTLibrary;
194
195 ///////////////////////////////////////////////////////////////////////////
196
197 class SkTypeface_FreeType::FaceRec {
198 public:
199 SkUniqueFTFace fFace;
200 FT_StreamRec fFTStream;
201 std::unique_ptr<SkStreamAsset> fSkStream;
202 FT_UShort fFTPaletteEntryCount = 0;
203 std::unique_ptr<SkColor[]> fSkPalette;
204
205 static std::unique_ptr<FaceRec> Make(const SkTypeface_FreeType* typeface);
206 ~FaceRec();
207
208 private:
209 FaceRec(std::unique_ptr<SkStreamAsset> stream);
210 void setupAxes(const SkFontData& data);
211 void setupPalette(const SkFontData& data);
212
213 // Private to ref_ft_library and unref_ft_library
214 static int gFTCount;
215
216 // Caller must lock f_t_mutex() before calling this function.
ref_ft_library()217 static bool ref_ft_library() {
218 f_t_mutex().assertHeld();
219 SkASSERT(gFTCount >= 0);
220
221 if (0 == gFTCount) {
222 SkASSERT(nullptr == gFTLibrary);
223 gFTLibrary = new FreeTypeLibrary;
224 }
225 ++gFTCount;
226 return gFTLibrary->library();
227 }
228
229 // Caller must lock f_t_mutex() before calling this function.
unref_ft_library()230 static void unref_ft_library() {
231 f_t_mutex().assertHeld();
232 SkASSERT(gFTCount > 0);
233
234 --gFTCount;
235 if (0 == gFTCount) {
236 SkASSERT(nullptr != gFTLibrary);
237 delete gFTLibrary;
238 SkDEBUGCODE(gFTLibrary = nullptr;)
239 }
240 }
241 };
242 int SkTypeface_FreeType::FaceRec::gFTCount;
243
244 extern "C" {
sk_ft_stream_io(FT_Stream ftStream,unsigned long offset,unsigned char * buffer,unsigned long count)245 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
246 unsigned long offset,
247 unsigned char* buffer,
248 unsigned long count)
249 {
250 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
251
252 if (count) {
253 if (!stream->seek(offset)) {
254 return 0;
255 }
256 count = stream->read(buffer, count);
257 }
258 return count;
259 }
260
sk_ft_stream_close(FT_Stream)261 static void sk_ft_stream_close(FT_Stream) {}
262 }
263
FaceRec(std::unique_ptr<SkStreamAsset> stream)264 SkTypeface_FreeType::FaceRec::FaceRec(std::unique_ptr<SkStreamAsset> stream)
265 : fSkStream(std::move(stream))
266 {
267 sk_bzero(&fFTStream, sizeof(fFTStream));
268 fFTStream.size = fSkStream->getLength();
269 fFTStream.descriptor.pointer = fSkStream.get();
270 fFTStream.read = sk_ft_stream_io;
271 fFTStream.close = sk_ft_stream_close;
272
273 f_t_mutex().assertHeld();
274 ref_ft_library();
275 }
276
~FaceRec()277 SkTypeface_FreeType::FaceRec::~FaceRec() {
278 f_t_mutex().assertHeld();
279 fFace.reset(); // Must release face before the library, the library frees existing faces.
280 unref_ft_library();
281 }
282
setupAxes(const SkFontData & data)283 void SkTypeface_FreeType::FaceRec::setupAxes(const SkFontData& data) {
284 if (!(fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
285 return;
286 }
287
288 // If a named variation is requested, don't overwrite the named variation's position.
289 if (data.getIndex() > 0xFFFF) {
290 return;
291 }
292
293 SkDEBUGCODE(
294 FT_MM_Var* variations = nullptr;
295 if (FT_Get_MM_Var(fFace.get(), &variations)) {
296 LOG_INFO("INFO: font %s claims variations, but none found.\n",
297 rec->fFace->family_name);
298 return;
299 }
300 UniqueVoidPtr autoFreeVariations(variations);
301
302 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
303 LOG_INFO("INFO: font %s has %d variations, but %d were specified.\n",
304 rec->fFace->family_name, variations->num_axis, data.getAxisCount());
305 return;
306 }
307 )
308
309 AutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
310 for (int i = 0; i < data.getAxisCount(); ++i) {
311 coords[i] = data.getAxis()[i];
312 }
313 if (FT_Set_Var_Design_Coordinates(fFace.get(), data.getAxisCount(), coords.get())) {
314 LOG_INFO("INFO: font %s has variations, but specified variations could not be set.\n",
315 rec->fFace->family_name);
316 return;
317 }
318 }
319
setupPalette(const SkFontData & data)320 void SkTypeface_FreeType::FaceRec::setupPalette(const SkFontData& data) {
321 #ifdef FT_COLOR_H
322 FT_Palette_Data paletteData;
323 if (FT_Palette_Data_Get(fFace.get(), &paletteData)) {
324 return;
325 }
326
327 // Treat out of range values as 0. Still apply overrides.
328 // https://www.w3.org/TR/css-fonts-4/#base-palette-desc
329 FT_UShort basePaletteIndex = 0;
330 if (SkTFitsIn<FT_UShort>(data.getPaletteIndex()) &&
331 SkTo<FT_UShort>(data.getPaletteIndex()) < paletteData.num_palettes)
332 {
333 basePaletteIndex = data.getPaletteIndex();
334 }
335
336 FT_Color* ftPalette = nullptr;
337 if (FT_Palette_Select(fFace.get(), basePaletteIndex, &ftPalette)) {
338 return;
339 }
340 fFTPaletteEntryCount = paletteData.num_palette_entries;
341
342 for (int i = 0; i < data.getPaletteOverrideCount(); ++i) {
343 const SkFontArguments::Palette::Override& paletteOverride = data.getPaletteOverrides()[i];
344 if (0 <= paletteOverride.index && paletteOverride.index < fFTPaletteEntryCount) {
345 const SkColor& skColor = paletteOverride.color;
346 FT_Color& ftColor = ftPalette[paletteOverride.index];
347 ftColor.blue = SkColorGetB(skColor);
348 ftColor.green = SkColorGetG(skColor);
349 ftColor.red = SkColorGetR(skColor);
350 ftColor.alpha = SkColorGetA(skColor);
351 }
352 }
353
354 fSkPalette.reset(new SkColor[fFTPaletteEntryCount]);
355 for (int i = 0; i < fFTPaletteEntryCount; ++i) {
356 fSkPalette[i] = SkColorSetARGB(ftPalette[i].alpha,
357 ftPalette[i].red,
358 ftPalette[i].green,
359 ftPalette[i].blue);
360 }
361 #endif
362 }
363
364 // Will return nullptr on failure
365 // Caller must lock f_t_mutex() before calling this function.
366 std::unique_ptr<SkTypeface_FreeType::FaceRec>
Make(const SkTypeface_FreeType * typeface)367 SkTypeface_FreeType::FaceRec::Make(const SkTypeface_FreeType* typeface) {
368 f_t_mutex().assertHeld();
369
370 std::unique_ptr<SkFontData> data = typeface->makeFontData();
371 if (nullptr == data || !data->hasStream()) {
372 return nullptr;
373 }
374
375 std::unique_ptr<FaceRec> rec(new FaceRec(data->detachStream()));
376
377 FT_Open_Args args;
378 memset(&args, 0, sizeof(args));
379 const void* memoryBase = rec->fSkStream->getMemoryBase();
380 if (memoryBase) {
381 args.flags = FT_OPEN_MEMORY;
382 args.memory_base = (const FT_Byte*)memoryBase;
383 args.memory_size = rec->fSkStream->getLength();
384 } else {
385 args.flags = FT_OPEN_STREAM;
386 args.stream = &rec->fFTStream;
387 }
388
389 {
390 FT_Face rawFace;
391 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
392 if (err) {
393 SK_TRACEFTR(err, "unable to open font '%x'", typeface->uniqueID());
394 return nullptr;
395 }
396 rec->fFace.reset(rawFace);
397 }
398 SkASSERT(rec->fFace);
399
400 rec->setupAxes(*data);
401 rec->setupPalette(*data);
402
403 // FreeType will set the charmap to the "most unicode" cmap if it exists.
404 // If there are no unicode cmaps, the charmap is set to nullptr.
405 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
406 // because they are effectively private use area only (even if they aren't).
407 // This is the last on the fallback list at
408 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
409 if (!rec->fFace->charmap) {
410 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
411 }
412
413 return rec;
414 }
415
416 class AutoFTAccess {
417 public:
AutoFTAccess(const SkTypeface_FreeType * tf)418 AutoFTAccess(const SkTypeface_FreeType* tf) : fFaceRec(nullptr) {
419 f_t_mutex().acquire();
420 fFaceRec = tf->getFaceRec();
421 }
422
~AutoFTAccess()423 ~AutoFTAccess() {
424 f_t_mutex().release();
425 }
426
face()427 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
428
429 private:
430 SkTypeface_FreeType::FaceRec* fFaceRec;
431 };
432
433 ///////////////////////////////////////////////////////////////////////////
434
435 class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
436 public:
437 SkScalerContext_FreeType(sk_sp<SkTypeface_FreeType>,
438 const SkScalerContextEffects&,
439 const SkDescriptor* desc);
440 ~SkScalerContext_FreeType() override;
441
success() const442 bool success() const {
443 return fFTSize != nullptr && fFace != nullptr;
444 }
445
446 protected:
447 bool generateAdvance(SkGlyph* glyph) override;
448 void generateMetrics(SkGlyph* glyph, SkArenaAlloc*) override;
449 void generateImage(const SkGlyph& glyph) override;
450 bool generatePath(const SkGlyph& glyph, SkPath* path) override;
451 sk_sp<SkDrawable> generateDrawable(const SkGlyph&) override;
452 void generateFontMetrics(SkFontMetrics*) override;
453
454 private:
455 SkTypeface_FreeType::FaceRec* fFaceRec; // Borrowed face from the typeface's FaceRec.
456 FT_Face fFace; // Borrowed face from fFaceRec.
457 FT_Size fFTSize; // The size to apply to the fFace.
458 FT_Int fStrikeIndex; // The bitmap strike for the fFace (or -1 if none).
459
460 /** The rest of the matrix after FreeType handles the size.
461 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
462 * With bitmap only fonts this matrix must be applied to scale the bitmap.
463 */
464 SkMatrix fMatrix22Scalar;
465 /** Same as fMatrix22Scalar, but in FreeType units and space. */
466 FT_Matrix fMatrix22;
467 /** The actual size requested. */
468 SkVector fScale;
469
470 uint32_t fLoadGlyphFlags;
471 bool fDoLinearMetrics;
472 bool fLCDIsVert;
473
474 FT_Error setupSize();
475 static bool getBoundsOfCurrentOutlineGlyph(FT_GlyphSlot glyph, SkRect* bounds);
476 static void setGlyphBounds(SkGlyph* glyph, SkRect* bounds, bool subpixel);
477 bool getCBoxForLetter(char letter, FT_BBox* bbox);
478 // Caller must lock f_t_mutex() before calling this function.
479 void updateGlyphBoundsIfLCD(SkGlyph* glyph);
480 // Caller must lock f_t_mutex() before calling this function.
481 // update FreeType2 glyph slot with glyph emboldened
482 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
483 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
484 };
485
486 ///////////////////////////////////////////////////////////////////////////
487
canEmbed(FT_Face face)488 static bool canEmbed(FT_Face face) {
489 FT_UShort fsType = FT_Get_FSType_Flags(face);
490 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
491 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
492 }
493
canSubset(FT_Face face)494 static bool canSubset(FT_Face face) {
495 FT_UShort fsType = FT_Get_FSType_Flags(face);
496 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
497 }
498
get_font_type(FT_Face face)499 static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
500 const char* fontType = FT_Get_X11_Font_Format(face);
501 static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
502 { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
503 { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
504 { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
505 { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
506 };
507 for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
508 return SkAdvancedTypefaceMetrics::kOther_Font;
509 }
510
is_opentype_font_data_standard_format(const SkTypeface & typeface)511 static bool is_opentype_font_data_standard_format(const SkTypeface& typeface) {
512 // FreeType reports TrueType for any data that can be decoded to TrueType or OpenType.
513 // However, there are alternate data formats for OpenType, like wOFF and wOF2.
514 std::unique_ptr<SkStreamAsset> stream = typeface.openStream(nullptr);
515 if (!stream) {
516 return false;
517 }
518 char buffer[4];
519 if (stream->read(buffer, 4) < 4) {
520 return false;
521 }
522
523 SkFourByteTag tag = SkSetFourByteTag(buffer[0], buffer[1], buffer[2], buffer[3]);
524 SK_OT_ULONG otTag = SkEndian_SwapBE32(tag);
525 return otTag == SkSFNTHeader::fontType_WindowsTrueType::TAG ||
526 otTag == SkSFNTHeader::fontType_MacTrueType::TAG ||
527 otTag == SkSFNTHeader::fontType_PostScript::TAG ||
528 otTag == SkSFNTHeader::fontType_OpenTypeCFF::TAG ||
529 otTag == SkTTCFHeader::TAG;
530 }
531
onGetAdvancedMetrics() const532 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
533 AutoFTAccess fta(this);
534 FT_Face face = fta.face();
535 if (!face) {
536 return nullptr;
537 }
538
539 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
540 info->fPostScriptName.set(FT_Get_Postscript_Name(face));
541 info->fFontName = info->fPostScriptName;
542
543 if (FT_HAS_MULTIPLE_MASTERS(face)) {
544 info->fFlags |= SkAdvancedTypefaceMetrics::kVariable_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 info->fType = get_font_type(face);
554 if (info->fType == SkAdvancedTypefaceMetrics::kTrueType_Font &&
555 !is_opentype_font_data_standard_format(*this))
556 {
557 info->fFlags |= SkAdvancedTypefaceMetrics::kAltDataFormat_FontFlag;
558 }
559
560 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
561 if (FT_IS_FIXED_WIDTH(face)) {
562 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
563 }
564 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
565 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
566 }
567
568 PS_FontInfoRec psFontInfo;
569 TT_Postscript* postTable;
570 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
571 info->fItalicAngle = psFontInfo.italic_angle;
572 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
573 info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
574 } else {
575 info->fItalicAngle = 0;
576 }
577
578 info->fAscent = face->ascender;
579 info->fDescent = face->descender;
580
581 TT_PCLT* pcltTable;
582 TT_OS2* os2Table;
583 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
584 info->fCapHeight = pcltTable->CapHeight;
585 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
586 if (2 <= serif_style && serif_style <= 6) {
587 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
588 } else if (9 <= serif_style && serif_style <= 12) {
589 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
590 }
591 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
592 // sCapHeight is available only when version 2 or later.
593 os2Table->version != 0xFFFF &&
594 os2Table->version >= 2)
595 {
596 info->fCapHeight = os2Table->sCapHeight;
597 }
598 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
599 face->bbox.xMax, face->bbox.yMin);
600 return info;
601 }
602
getGlyphToUnicodeMap(SkUnichar * dstArray) const603 void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
604 AutoFTAccess fta(this);
605 FT_Face face = fta.face();
606 if (!face) {
607 return;
608 }
609
610 FT_Long numGlyphs = face->num_glyphs;
611 if (!dstArray) { SkASSERT(numGlyphs == 0); }
612 sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
613
614 FT_UInt glyphIndex;
615 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
616 while (glyphIndex) {
617 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
618 // Use the first character that maps to this glyphID. https://crbug.com/359065
619 if (0 == dstArray[glyphIndex]) {
620 dstArray[glyphIndex] = charCode;
621 }
622 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
623 }
624 }
625
getPostScriptGlyphNames(SkString * dstArray) const626 void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
627 AutoFTAccess fta(this);
628 FT_Face face = fta.face();
629 if (!face) {
630 return;
631 }
632
633 FT_Long numGlyphs = face->num_glyphs;
634 if (!dstArray) { SkASSERT(numGlyphs == 0); }
635
636 if (FT_HAS_GLYPH_NAMES(face)) {
637 for (int gID = 0; gID < numGlyphs; ++gID) {
638 char glyphName[128]; // PS limit for names is 127 bytes.
639 FT_Get_Glyph_Name(face, gID, glyphName, 128);
640 dstArray[gID] = glyphName;
641 }
642 }
643 }
644
onGetPostScriptName(SkString * skPostScriptName) const645 bool SkTypeface_FreeType::onGetPostScriptName(SkString* skPostScriptName) const {
646 AutoFTAccess fta(this);
647 FT_Face face = fta.face();
648 if (!face) {
649 return false;
650 }
651
652 const char* ftPostScriptName = FT_Get_Postscript_Name(face);
653 if (!ftPostScriptName) {
654 return false;
655 }
656 if (skPostScriptName) {
657 *skPostScriptName = ftPostScriptName;
658 }
659 return true;
660 }
661
662 ///////////////////////////////////////////////////////////////////////////
663
bothZero(SkScalar a,SkScalar b)664 static bool bothZero(SkScalar a, SkScalar b) {
665 return 0 == a && 0 == b;
666 }
667
668 // returns false if there is any non-90-rotation or skew
isAxisAligned(const SkScalerContextRec & rec)669 static bool isAxisAligned(const SkScalerContextRec& rec) {
670 return 0 == rec.fPreSkewX &&
671 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
672 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
673 }
674
onCreateScalerContext(const SkScalerContextEffects & effects,const SkDescriptor * desc) const675 std::unique_ptr<SkScalerContext> SkTypeface_FreeType::onCreateScalerContext(
676 const SkScalerContextEffects& effects, const SkDescriptor* desc) const
677 {
678 auto c = std::make_unique<SkScalerContext_FreeType>(
679 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
680 if (c->success()) {
681 return std::move(c);
682 }
683 return SkScalerContext::MakeEmpty(
684 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
685 }
686
687 /** Copy the design variation coordinates into 'coordinates'.
688 *
689 * @param coordinates the buffer into which to write the design variation coordinates.
690 * @param coordinateCount the number of entries available through 'coordinates'.
691 *
692 * @return The number of axes, or -1 if there is an error.
693 * If 'coordinates != nullptr' and 'coordinateCount >= numAxes' then 'coordinates' will be
694 * filled with the variation coordinates describing the position of this typeface in design
695 * variation space. It is possible the number of axes can be retrieved but actual position
696 * cannot.
697 */
GetVariationDesignPosition(AutoFTAccess & fta,SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount)698 static int GetVariationDesignPosition(AutoFTAccess& fta,
699 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount)
700 {
701 FT_Face face = fta.face();
702 if (!face) {
703 return -1;
704 }
705
706 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
707 return 0;
708 }
709
710 FT_MM_Var* variations = nullptr;
711 if (FT_Get_MM_Var(face, &variations)) {
712 return -1;
713 }
714 UniqueVoidPtr autoFreeVariations(variations);
715
716 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
717 return variations->num_axis;
718 }
719
720 AutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
721 if (FT_Get_Var_Design_Coordinates(face, variations->num_axis, coords.get())) {
722 return -1;
723 }
724 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
725 coordinates[i].axis = variations->axis[i].tag;
726 coordinates[i].value = SkFixedToScalar(coords[i]);
727 }
728
729 return variations->num_axis;
730 }
731
cloneFontData(const SkFontArguments & args) const732 std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(const SkFontArguments& args) const {
733 AutoFTAccess fta(this);
734 FT_Face face = fta.face();
735 if (!face) {
736 return nullptr;
737 }
738
739 Scanner::AxisDefinitions axisDefinitions;
740 if (!Scanner::GetAxes(face, &axisDefinitions)) {
741 return nullptr;
742 }
743 int axisCount = axisDefinitions.size();
744
745 AutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> currentPosition(axisCount);
746 int currentAxisCount = GetVariationDesignPosition(fta, currentPosition, axisCount);
747
748 SkString name;
749 AutoSTMalloc<4, SkFixed> axisValues(axisCount);
750 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(), axisValues, name,
751 currentAxisCount == axisCount ? currentPosition.get() : nullptr);
752
753 int ttcIndex;
754 std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
755
756 return std::make_unique<SkFontData>(std::move(stream),
757 ttcIndex,
758 args.getPalette().index,
759 axisValues.get(),
760 axisCount,
761 args.getPalette().overrides,
762 args.getPalette().overrideCount);
763 }
764
onFilterRec(SkScalerContextRec * rec) const765 void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
766 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
767 //Cap the requested size as larger sizes give bogus values.
768 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
769 //Note that this also currently only protects against large text size requests,
770 //the total matrix is not taken into account here.
771 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
772 rec->fTextSize = SkIntToScalar(1 << 14);
773 }
774
775 SkFontHinting h = rec->getHinting();
776 if (SkFontHinting::kFull == h && !isLCD(*rec)) {
777 // collapse full->normal hinting if we're not doing LCD
778 h = SkFontHinting::kNormal;
779 }
780
781 // rotated text looks bad with hinting, so we disable it as needed
782 if (!isAxisAligned(*rec)) {
783 h = SkFontHinting::kNone;
784 }
785 rec->setHinting(h);
786
787 #ifndef SK_GAMMA_APPLY_TO_A8
788 if (!isLCD(*rec)) {
789 // SRGBTODO: Is this correct? Do we want contrast boost?
790 rec->ignorePreBlend();
791 }
792 #endif
793 }
794
GetUnitsPerEm(FT_Face face)795 int SkTypeface_FreeType::GetUnitsPerEm(FT_Face face) {
796 SkASSERT(face);
797
798 SkScalar upem = SkIntToScalar(face->units_per_EM);
799 // At least some versions of FreeType set face->units_per_EM to 0 for bitmap only fonts.
800 if (upem == 0) {
801 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
802 if (ttHeader) {
803 upem = SkIntToScalar(ttHeader->Units_Per_EM);
804 }
805 }
806 return upem;
807 }
808
onGetUPEM() const809 int SkTypeface_FreeType::onGetUPEM() const {
810 AutoFTAccess fta(this);
811 FT_Face face = fta.face();
812 if (!face) {
813 return 0;
814 }
815 return GetUnitsPerEm(face);
816 }
817
onGetKerningPairAdjustments(const uint16_t glyphs[],int count,int32_t adjustments[]) const818 bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
819 int count, int32_t adjustments[]) const {
820 AutoFTAccess fta(this);
821 FT_Face face = fta.face();
822 if (!face || !FT_HAS_KERNING(face)) {
823 return false;
824 }
825
826 for (int i = 0; i < count - 1; ++i) {
827 FT_Vector delta;
828 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
829 FT_KERNING_UNSCALED, &delta);
830 if (err) {
831 return false;
832 }
833 adjustments[i] = delta.x;
834 }
835 return true;
836 }
837
838 /** Returns the bitmap strike equal to or just larger than the requested size. */
chooseBitmapStrike(FT_Face face,FT_F26Dot6 scaleY)839 static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
840 if (face == nullptr) {
841 LOG_INFO("chooseBitmapStrike aborted due to nullptr face.\n");
842 return -1;
843 }
844
845 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
846 FT_Int chosenStrikeIndex = -1;
847 FT_Pos chosenPPEM = 0;
848 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
849 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
850 if (strikePPEM == requestedPPEM) {
851 // exact match - our search stops here
852 return strikeIndex;
853 } else if (chosenPPEM < requestedPPEM) {
854 // attempt to increase chosenPPEM
855 if (chosenPPEM < strikePPEM) {
856 chosenPPEM = strikePPEM;
857 chosenStrikeIndex = strikeIndex;
858 }
859 } else {
860 // attempt to decrease chosenPPEM, but not below requestedPPEM
861 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
862 chosenPPEM = strikePPEM;
863 chosenStrikeIndex = strikeIndex;
864 }
865 }
866 }
867 return chosenStrikeIndex;
868 }
869
SkScalerContext_FreeType(sk_sp<SkTypeface_FreeType> typeface,const SkScalerContextEffects & effects,const SkDescriptor * desc)870 SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface_FreeType> typeface,
871 const SkScalerContextEffects& effects,
872 const SkDescriptor* desc)
873 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
874 , fFace(nullptr)
875 , fFTSize(nullptr)
876 , fStrikeIndex(-1)
877 {
878 SkAutoMutexExclusive ac(f_t_mutex());
879 fFaceRec = static_cast<SkTypeface_FreeType*>(this->getTypeface())->getFaceRec();
880
881 // load the font file
882 if (nullptr == fFaceRec) {
883 LOG_INFO("Could not create FT_Face.\n");
884 return;
885 }
886
887 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
888
889 // compute the flags we send to Load_Glyph
890 bool linearMetrics = this->isLinearMetrics();
891 {
892 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
893
894 if (SkMask::kBW_Format == fRec.fMaskFormat) {
895 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
896 loadFlags = FT_LOAD_TARGET_MONO;
897 if (fRec.getHinting() == SkFontHinting::kNone) {
898 loadFlags |= FT_LOAD_NO_HINTING;
899 linearMetrics = true;
900 }
901 } else {
902 switch (fRec.getHinting()) {
903 case SkFontHinting::kNone:
904 loadFlags = FT_LOAD_NO_HINTING;
905 linearMetrics = true;
906 break;
907 case SkFontHinting::kSlight:
908 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
909 linearMetrics = true;
910 break;
911 case SkFontHinting::kNormal:
912 loadFlags = FT_LOAD_TARGET_NORMAL;
913 break;
914 case SkFontHinting::kFull:
915 loadFlags = FT_LOAD_TARGET_NORMAL;
916 if (isLCD(fRec)) {
917 if (fLCDIsVert) {
918 loadFlags = FT_LOAD_TARGET_LCD_V;
919 } else {
920 loadFlags = FT_LOAD_TARGET_LCD;
921 }
922 }
923 break;
924 default:
925 LOG_INFO("---------- UNKNOWN hinting %d\n", fRec.getHinting());
926 break;
927 }
928 }
929
930 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
931 loadFlags |= FT_LOAD_FORCE_AUTOHINT;
932 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
933 } else {
934 loadFlags |= FT_LOAD_NO_AUTOHINT;
935 #endif
936 }
937
938 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
939 loadFlags |= FT_LOAD_NO_BITMAP;
940 }
941
942 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
943 // advances, as fontconfig and cairo do.
944 // See http://code.google.com/p/skia/issues/detail?id=222.
945 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
946
947 // Use vertical layout if requested.
948 if (this->isVertical()) {
949 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
950 }
951
952 fLoadGlyphFlags = loadFlags;
953 }
954
955 SkUniqueFTSize ftSize([this]() -> FT_Size {
956 FT_Size size;
957 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
958 if (err != 0) {
959 SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
960 return nullptr;
961 }
962 return size;
963 }());
964 if (nullptr == ftSize) {
965 LOG_INFO("Could not create FT_Size.\n");
966 return;
967 }
968
969 FT_Error err = FT_Activate_Size(ftSize.get());
970 if (err != 0) {
971 SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
972 return;
973 }
974
975 fRec.computeMatrices(SkScalerContextRec::PreMatrixScale::kFull, &fScale, &fMatrix22Scalar);
976 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
977 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
978
979 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
980 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
981 if (err != 0) {
982 SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
983 fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
984 return;
985 }
986
987 // Adjust the matrix to reflect the actually chosen scale.
988 // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
989 // Don't do this at all sizes as that will interfere with hinting.
990 if (fScale.fX < 1 || fScale.fY < 1) {
991 SkScalar upem = fFaceRec->fFace->units_per_EM;
992 FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
993 SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
994 SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
995 fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
996 }
997
998 // FT_LOAD_COLOR with scalable fonts means allow SVG.
999 // It also implies attempt to render COLR if available, but this is not used.
1000 #if defined(FT_CONFIG_OPTION_SVG)
1001 if (SkGraphics::GetOpenTypeSVGDecoderFactory()) {
1002 fLoadGlyphFlags |= FT_LOAD_COLOR;
1003 }
1004 #endif
1005 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
1006 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
1007 if (fStrikeIndex == -1) {
1008 LOG_INFO("No glyphs for font \"%s\" size %f.\n",
1009 fFaceRec->fFace->family_name, fScale.fY);
1010 return;
1011 }
1012
1013 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
1014 if (err != 0) {
1015 SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
1016 fFaceRec->fFace->family_name, fStrikeIndex);
1017 fStrikeIndex = -1;
1018 return;
1019 }
1020
1021 // Adjust the matrix to reflect the actually chosen scale.
1022 // It is likely that the ppem chosen was not the one requested, this allows for scaling.
1023 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
1024 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
1025
1026 // FreeType does not provide linear metrics for bitmap fonts.
1027 linearMetrics = false;
1028
1029 // FreeType documentation says:
1030 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
1031 // Bitmap-only fonts ignore this flag.
1032 //
1033 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
1034 // Force this flag off for bitmap only fonts.
1035 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
1036
1037 // Color bitmaps are supported.
1038 fLoadGlyphFlags |= FT_LOAD_COLOR;
1039 } else {
1040 LOG_INFO("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
1041 return;
1042 }
1043
1044 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
1045 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
1046 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
1047 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
1048
1049 fFTSize = ftSize.release();
1050 fFace = fFaceRec->fFace.get();
1051 fDoLinearMetrics = linearMetrics;
1052 }
1053
~SkScalerContext_FreeType()1054 SkScalerContext_FreeType::~SkScalerContext_FreeType() {
1055 SkAutoMutexExclusive ac(f_t_mutex());
1056
1057 if (fFTSize != nullptr) {
1058 FT_Done_Size(fFTSize);
1059 }
1060
1061 fFaceRec = nullptr;
1062 }
1063
1064 /* We call this before each use of the fFace, since we may be sharing
1065 this face with other context (at different sizes).
1066 */
setupSize()1067 FT_Error SkScalerContext_FreeType::setupSize() {
1068 f_t_mutex().assertHeld();
1069 FT_Error err = FT_Activate_Size(fFTSize);
1070 if (err != 0) {
1071 return err;
1072 }
1073 FT_Set_Transform(fFace, &fMatrix22, nullptr);
1074 return 0;
1075 }
1076
generateAdvance(SkGlyph * glyph)1077 bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
1078 /* unhinted and light hinted text have linearly scaled advances
1079 * which are very cheap to compute with some font formats...
1080 */
1081 if (!fDoLinearMetrics) {
1082 return false;
1083 }
1084
1085 SkAutoMutexExclusive ac(f_t_mutex());
1086
1087 if (this->setupSize()) {
1088 glyph->zeroMetrics();
1089 return true;
1090 }
1091
1092 FT_Error error;
1093 FT_Fixed advance;
1094
1095 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
1096 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1097 &advance );
1098
1099 if (error != 0) {
1100 return false;
1101 }
1102
1103 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1104 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1105 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1106 return true;
1107 }
1108
getBoundsOfCurrentOutlineGlyph(FT_GlyphSlot glyph,SkRect * bounds)1109 bool SkScalerContext_FreeType::getBoundsOfCurrentOutlineGlyph(FT_GlyphSlot glyph, SkRect* bounds) {
1110 if (glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
1111 SkASSERT(false);
1112 return false;
1113 }
1114 if (0 == glyph->outline.n_contours) {
1115 return false;
1116 }
1117
1118 FT_BBox bbox;
1119 FT_Outline_Get_CBox(&glyph->outline, &bbox);
1120 *bounds = SkRect::MakeLTRB(SkFDot6ToScalar(bbox.xMin), -SkFDot6ToScalar(bbox.yMax),
1121 SkFDot6ToScalar(bbox.xMax), -SkFDot6ToScalar(bbox.yMin));
1122 return true;
1123 }
1124
getCBoxForLetter(char letter,FT_BBox * bbox)1125 bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1126 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
1127 if (!glyph_id) {
1128 return false;
1129 }
1130 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags)) {
1131 return false;
1132 }
1133 if (fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
1134 return false;
1135 }
1136 emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
1137 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1138 return true;
1139 }
1140
setGlyphBounds(SkGlyph * glyph,SkRect * bounds,bool subpixel)1141 void SkScalerContext_FreeType::setGlyphBounds(SkGlyph* glyph, SkRect* bounds, bool subpixel) {
1142 SkIRect irect;
1143 if (bounds->isEmpty()) {
1144 irect = SkIRect::MakeEmpty();
1145 } else {
1146 if (subpixel) {
1147 bounds->offset(SkFixedToScalar(glyph->getSubXFixed()),
1148 SkFixedToScalar(glyph->getSubYFixed()));
1149 }
1150
1151 irect = bounds->roundOut();
1152 if (!SkTFitsIn<decltype(glyph->fWidth )>(irect.width ()) ||
1153 !SkTFitsIn<decltype(glyph->fHeight)>(irect.height()) ||
1154 !SkTFitsIn<decltype(glyph->fTop )>(irect.top ()) ||
1155 !SkTFitsIn<decltype(glyph->fLeft )>(irect.left ()) )
1156 {
1157 irect = SkIRect::MakeEmpty();
1158 }
1159 }
1160 glyph->fWidth = SkToU16(irect.width ());
1161 glyph->fHeight = SkToU16(irect.height());
1162 glyph->fTop = SkToS16(irect.top ());
1163 glyph->fLeft = SkToS16(irect.left ());
1164 }
1165
updateGlyphBoundsIfLCD(SkGlyph * glyph)1166 void SkScalerContext_FreeType::updateGlyphBoundsIfLCD(SkGlyph* glyph) {
1167 if (glyph->fMaskFormat == SkMask::kLCD16_Format &&
1168 glyph->fWidth > 0 && glyph->fHeight > 0)
1169 {
1170 if (fLCDIsVert) {
1171 glyph->fHeight += 2;
1172 glyph->fTop -= 1;
1173 } else {
1174 glyph->fWidth += 2;
1175 glyph->fLeft -= 1;
1176 }
1177 }
1178 }
1179
shouldSubpixelBitmap(const SkGlyph & glyph,const SkMatrix & matrix)1180 bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1181 // If subpixel rendering of a bitmap *can* be done.
1182 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1183 this->isSubpixel() &&
1184 (glyph.getSubXFixed() || glyph.getSubYFixed());
1185
1186 // If subpixel rendering of a bitmap *should* be done.
1187 // 1. If the face is not scalable then always allow subpixel rendering.
1188 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1189 // 2. If the matrix is already not identity the bitmap will already be resampled,
1190 // so resampling slightly differently shouldn't make much difference.
1191 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1192
1193 return mechanism && policy;
1194 }
1195
generateMetrics(SkGlyph * glyph,SkArenaAlloc * alloc)1196 void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph, SkArenaAlloc* alloc) {
1197 SkAutoMutexExclusive ac(f_t_mutex());
1198
1199 if (this->setupSize()) {
1200 glyph->zeroMetrics();
1201 return;
1202 }
1203
1204 FT_Bool haveLayers = false;
1205 #ifdef FT_COLOR_H
1206 // See https://skbug.com/12945, if the face isn't marked scalable then paths cannot be loaded.
1207 if (FT_IS_SCALABLE(fFace)) {
1208 SkRect bounds = SkRect::MakeEmpty();
1209 #ifdef TT_SUPPORT_COLRV1
1210 FT_OpaquePaint opaqueLayerPaint{nullptr, 1};
1211 if (FT_Get_Color_Glyph_Paint(fFace, glyph->getGlyphID(),
1212 FT_COLOR_INCLUDE_ROOT_TRANSFORM, &opaqueLayerPaint)) {
1213 haveLayers = true;
1214 glyph->fScalerContextBits = ScalerContextBits::COLRv1;
1215
1216 // COLRv1 optionally provides a ClipBox.
1217 FT_ClipBox clipBox;
1218 if (FT_Get_Color_Glyph_ClipBox(fFace, glyph->getGlyphID(), &clipBox)) {
1219 // Find bounding box of clip box corner points, needed when clipbox is transformed.
1220 FT_BBox bbox;
1221 bbox.xMin = clipBox.bottom_left.x;
1222 bbox.xMax = clipBox.bottom_left.x;
1223 bbox.yMin = clipBox.bottom_left.y;
1224 bbox.yMax = clipBox.bottom_left.y;
1225 for (auto& corner : {clipBox.top_left, clipBox.top_right, clipBox.bottom_right}) {
1226 bbox.xMin = std::min(bbox.xMin, corner.x);
1227 bbox.yMin = std::min(bbox.yMin, corner.y);
1228 bbox.xMax = std::max(bbox.xMax, corner.x);
1229 bbox.yMax = std::max(bbox.yMax, corner.y);
1230 }
1231 bounds = SkRect::MakeLTRB(SkFDot6ToScalar(bbox.xMin), -SkFDot6ToScalar(bbox.yMax),
1232 SkFDot6ToScalar(bbox.xMax), -SkFDot6ToScalar(bbox.yMin));
1233 } else {
1234 // Traverse the glyph graph with a focus on measuring the required bounding box.
1235 // The call to computeColrV1GlyphBoundingBox may modify the face.
1236 // Reset the face to load the base glyph for metrics.
1237 if (!computeColrV1GlyphBoundingBox(fFace, glyph->getGlyphID(), &bounds) ||
1238 this->setupSize())
1239 {
1240 glyph->zeroMetrics();
1241 return;
1242 }
1243 }
1244 }
1245 #endif // #TT_SUPPORT_COLRV1
1246
1247 if (!haveLayers) {
1248 FT_LayerIterator layerIterator = { 0, 0, nullptr };
1249 FT_UInt layerGlyphIndex;
1250 FT_UInt layerColorIndex;
1251 FT_Int32 flags = fLoadGlyphFlags;
1252 flags |= FT_LOAD_BITMAP_METRICS_ONLY; // Don't decode any bitmaps.
1253 flags |= FT_LOAD_NO_BITMAP; // Ignore embedded bitmaps.
1254 flags &= ~FT_LOAD_RENDER; // Don't scan convert.
1255 flags &= ~FT_LOAD_COLOR; // Ignore SVG.
1256 // For COLRv0 compute the glyph bounding box from the union of layer bounding boxes.
1257 while (FT_Get_Color_Glyph_Layer(fFace, glyph->getGlyphID(), &layerGlyphIndex,
1258 &layerColorIndex, &layerIterator)) {
1259 haveLayers = true;
1260 if (FT_Load_Glyph(fFace, layerGlyphIndex, flags)) {
1261 glyph->zeroMetrics();
1262 return;
1263 }
1264
1265 SkRect currentBounds;
1266 if (getBoundsOfCurrentOutlineGlyph(fFace->glyph, ¤tBounds)) {
1267 bounds.join(currentBounds);
1268 }
1269 }
1270 if (haveLayers) {
1271 glyph->fScalerContextBits = ScalerContextBits::COLRv0;
1272 }
1273 }
1274
1275 if (haveLayers) {
1276 glyph->fMaskFormat = SkMask::kARGB32_Format;
1277 glyph->setPath(alloc, nullptr, false);
1278 setGlyphBounds(glyph, &bounds, this->isSubpixel());
1279 }
1280 }
1281 #endif //FT_COLOR_H
1282
1283 // Even if haveLayers, the base glyph must be loaded to get the metrics.
1284 if (FT_Load_Glyph(fFace, glyph->getGlyphID(), fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY)) {
1285 glyph->zeroMetrics();
1286 return;
1287 }
1288
1289 if (!haveLayers) {
1290 emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
1291
1292 if (fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
1293 SkRect bounds;
1294 if (!getBoundsOfCurrentOutlineGlyph(fFace->glyph, &bounds)) {
1295 bounds = SkRect::MakeEmpty();
1296 }
1297 setGlyphBounds(glyph, &bounds, this->isSubpixel());
1298 updateGlyphBoundsIfLCD(glyph);
1299
1300 } else if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
1301 glyph->setPath(alloc, nullptr, false);
1302
1303 if (this->isVertical()) {
1304 FT_Vector vector;
1305 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1306 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1307 FT_Vector_Transform(&vector, &fMatrix22);
1308 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1309 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1310 }
1311
1312 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1313 glyph->fMaskFormat = SkMask::kARGB32_Format;
1314 }
1315
1316 SkRect bounds = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left ),
1317 -SkIntToScalar(fFace->glyph->bitmap_top ),
1318 SkIntToScalar(fFace->glyph->bitmap.width),
1319 SkIntToScalar(fFace->glyph->bitmap.rows ));
1320 fMatrix22Scalar.mapRect(&bounds);
1321 setGlyphBounds(glyph, &bounds, this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar));
1322
1323 #if defined(FT_CONFIG_OPTION_SVG)
1324 } else if (fFace->glyph->format == FT_GLYPH_FORMAT_SVG) {
1325 glyph->fScalerContextBits = ScalerContextBits::SVG;
1326 glyph->fMaskFormat = SkMask::kARGB32_Format;
1327 glyph->setPath(alloc, nullptr, false);
1328
1329 SkPictureRecorder recorder;
1330 SkRect infiniteRect = SkRect::MakeLTRB(-SK_ScalarInfinity, -SK_ScalarInfinity,
1331 SK_ScalarInfinity, SK_ScalarInfinity);
1332 sk_sp<SkBBoxHierarchy> bboxh = SkRTreeFactory()();
1333 SkSpan<SkColor> palette(fFaceRec->fSkPalette.get(), fFaceRec->fFTPaletteEntryCount);
1334 SkCanvas* recordingCanvas = recorder.beginRecording(infiniteRect, bboxh);
1335 if (!this->drawSVGGlyph(fFace, *glyph, fLoadGlyphFlags, palette, recordingCanvas)) {
1336 glyph->zeroMetrics();
1337 return;
1338 }
1339 sk_sp<SkPicture> pic = recorder.finishRecordingAsPicture();
1340 SkRect bounds = pic->cullRect();
1341 SkASSERT(bounds.isFinite());
1342
1343 // drawSVGGlyph already applied the subpixel positioning.
1344 setGlyphBounds(glyph, &bounds, false);
1345 #endif // FT_CONFIG_OPTION_SVG
1346
1347 } else {
1348 SkDEBUGFAIL("unknown glyph format");
1349 glyph->zeroMetrics();
1350 return;
1351 }
1352 }
1353
1354 if (this->isVertical()) {
1355 if (fDoLinearMetrics) {
1356 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
1357 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
1358 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
1359 } else {
1360 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1361 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
1362 }
1363 } else {
1364 if (fDoLinearMetrics) {
1365 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1366 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1367 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1368 } else {
1369 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1370 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
1371 }
1372 }
1373
1374 #ifdef ENABLE_GLYPH_SPEW
1375 LOG_INFO("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
1376 #endif
1377 }
1378
generateImage(const SkGlyph & glyph)1379 void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
1380 SkAutoMutexExclusive ac(f_t_mutex());
1381
1382 if (this->setupSize()) {
1383 sk_bzero(glyph.fImage, glyph.imageSize());
1384 return;
1385 }
1386
1387 if (glyph.fScalerContextBits == ScalerContextBits::COLRv0 ||
1388 glyph.fScalerContextBits == ScalerContextBits::COLRv1 ||
1389 glyph.fScalerContextBits == ScalerContextBits::SVG )
1390 {
1391 SkASSERT(glyph.maskFormat() == SkMask::kARGB32_Format);
1392 SkBitmap dstBitmap;
1393 // TODO: mark this as sRGB when the blits will be sRGB.
1394 dstBitmap.setInfo(SkImageInfo::Make(glyph.fWidth, glyph.fHeight,
1395 kN32_SkColorType,
1396 kPremul_SkAlphaType),
1397 glyph.rowBytes());
1398 dstBitmap.setPixels(glyph.fImage);
1399
1400 SkCanvas canvas(dstBitmap);
1401 if constexpr (kSkShowTextBlitCoverage) {
1402 canvas.clear(0x33FF0000);
1403 } else {
1404 canvas.clear(SK_ColorTRANSPARENT);
1405 }
1406 canvas.translate(-glyph.fLeft, -glyph.fTop);
1407
1408 SkSpan<SkColor> palette(fFaceRec->fSkPalette.get(), fFaceRec->fFTPaletteEntryCount);
1409 if (glyph.fScalerContextBits == ScalerContextBits::COLRv0) {
1410 #ifdef FT_COLOR_H
1411 this->drawCOLRv0Glyph(fFace, glyph, fLoadGlyphFlags, palette, &canvas);
1412 #endif
1413 } else if (glyph.fScalerContextBits == ScalerContextBits::COLRv1) {
1414 #ifdef TT_SUPPORT_COLRV1
1415 this->drawCOLRv1Glyph(fFace, glyph, fLoadGlyphFlags, palette, &canvas);
1416 #endif
1417 } else if (glyph.fScalerContextBits == ScalerContextBits::SVG) {
1418 #if defined(FT_CONFIG_OPTION_SVG)
1419 if (FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags)) {
1420 return;
1421 }
1422 this->drawSVGGlyph(fFace, glyph, fLoadGlyphFlags, palette, &canvas);
1423 #endif
1424 }
1425 return;
1426 }
1427
1428 if (FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags)) {
1429 sk_bzero(glyph.fImage, glyph.imageSize());
1430 return;
1431 }
1432 emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
1433
1434 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1435 SkMatrix subpixelBitmapMatrix;
1436 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1437 subpixelBitmapMatrix = fMatrix22Scalar;
1438 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1439 SkFixedToScalar(glyph.getSubYFixed()));
1440 bitmapMatrix = &subpixelBitmapMatrix;
1441 }
1442
1443 generateGlyphImage(fFace, glyph, *bitmapMatrix);
1444 }
1445
generateDrawable(const SkGlyph & glyph)1446 sk_sp<SkDrawable> SkScalerContext_FreeType::generateDrawable(const SkGlyph& glyph) {
1447 // Because FreeType's FT_Face is stateful (not thread safe) and the current design of this
1448 // SkTypeface and SkScalerContext does not work around this, it is necessary lock at least the
1449 // FT_Face when using it (this implementation currently locks the whole FT_Library).
1450 // It should be possible to draw the drawable straight out of the FT_Face. However, this would
1451 // mean locking each time any such drawable is drawn. To avoid locking, this implementation
1452 // creates drawables backed as pictures so that they can be played back later without locking.
1453 SkAutoMutexExclusive ac(f_t_mutex());
1454
1455 if (this->setupSize()) {
1456 return nullptr;
1457 }
1458
1459 #if defined(FT_COLOR_H) || defined(TT_SUPPORT_COLRV1) || defined(FT_CONFIG_OPTION_SVG)
1460 if (glyph.fScalerContextBits == ScalerContextBits::COLRv0 ||
1461 glyph.fScalerContextBits == ScalerContextBits::COLRv1 ||
1462 glyph.fScalerContextBits == ScalerContextBits::SVG )
1463 {
1464 SkSpan<SkColor> palette(fFaceRec->fSkPalette.get(), fFaceRec->fFTPaletteEntryCount);
1465 SkPictureRecorder recorder;
1466 SkCanvas* recordingCanvas = recorder.beginRecording(SkRect::Make(glyph.mask().fBounds));
1467 if (glyph.fScalerContextBits == ScalerContextBits::COLRv0) {
1468 #ifdef FT_COLOR_H
1469 if (!this->drawCOLRv0Glyph(fFace, glyph, fLoadGlyphFlags, palette, recordingCanvas)) {
1470 return nullptr;
1471 }
1472 #else
1473 return nullptr;
1474 #endif
1475 } else if (glyph.fScalerContextBits == ScalerContextBits::COLRv1) {
1476 #ifdef TT_SUPPORT_COLRV1
1477 if (!this->drawCOLRv1Glyph(fFace, glyph, fLoadGlyphFlags, palette, recordingCanvas)) {
1478 return nullptr;
1479 }
1480 #else
1481 return nullptr;
1482 #endif
1483 } else if (glyph.fScalerContextBits == ScalerContextBits::SVG) {
1484 #if defined(FT_CONFIG_OPTION_SVG)
1485 if (FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags)) {
1486 return nullptr;
1487 }
1488 if (!this->drawSVGGlyph(fFace, glyph, fLoadGlyphFlags, palette, recordingCanvas)) {
1489 return nullptr;
1490 }
1491 #else
1492 return nullptr;
1493 #endif
1494 }
1495 return recorder.finishRecordingAsDrawable();
1496 }
1497 #endif
1498 return nullptr;
1499 }
1500
generatePath(const SkGlyph & glyph,SkPath * path)1501 bool SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
1502 SkASSERT(path);
1503
1504 SkAutoMutexExclusive ac(f_t_mutex());
1505
1506 SkGlyphID glyphID = glyph.getGlyphID();
1507 // FT_IS_SCALABLE is documented to mean the face contains outline glyphs.
1508 if (!FT_IS_SCALABLE(fFace) || this->setupSize()) {
1509 path->reset();
1510 return false;
1511 }
1512
1513 uint32_t flags = fLoadGlyphFlags;
1514 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1515 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1516
1517 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
1518 if (err != 0 || fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
1519 path->reset();
1520 return false;
1521 }
1522 emboldenIfNeeded(fFace, fFace->glyph, glyphID);
1523
1524 if (!generateGlyphPath(fFace, path)) {
1525 path->reset();
1526 return false;
1527 }
1528
1529 // The path's origin from FreeType is always the horizontal layout origin.
1530 // Offset the path so that it is relative to the vertical origin if needed.
1531 if (this->isVertical()) {
1532 FT_Vector vector;
1533 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1534 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1535 FT_Vector_Transform(&vector, &fMatrix22);
1536 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1537 }
1538 return true;
1539 }
1540
generateFontMetrics(SkFontMetrics * metrics)1541 void SkScalerContext_FreeType::generateFontMetrics(SkFontMetrics* metrics) {
1542 if (nullptr == metrics) {
1543 return;
1544 }
1545
1546 SkAutoMutexExclusive ac(f_t_mutex());
1547
1548 if (this->setupSize()) {
1549 sk_bzero(metrics, sizeof(*metrics));
1550 return;
1551 }
1552
1553 FT_Face face = fFace;
1554 metrics->fFlags = 0;
1555
1556 SkScalar upem = SkIntToScalar(SkTypeface_FreeType::GetUnitsPerEm(face));
1557
1558 // use the os/2 table as a source of reasonable defaults.
1559 SkScalar x_height = 0.0f;
1560 SkScalar avgCharWidth = 0.0f;
1561 SkScalar cap_height = 0.0f;
1562 SkScalar strikeoutThickness = 0.0f, strikeoutPosition = 0.0f;
1563 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1564 if (os2) {
1565 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
1566 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
1567 strikeoutThickness = SkIntToScalar(os2->yStrikeoutSize) / upem;
1568 strikeoutPosition = -SkIntToScalar(os2->yStrikeoutPosition) / upem;
1569 metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
1570 metrics->fFlags |= SkFontMetrics::kStrikeoutPositionIsValid_Flag;
1571 if (os2->version != 0xFFFF && os2->version >= 2) {
1572 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
1573 }
1574 }
1575
1576 // pull from format-specific metrics as needed
1577 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
1578 SkScalar underlineThickness, underlinePosition;
1579 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
1580 // FreeType will always use HHEA metrics if they're not zero.
1581 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1582 // It also ignores the VDMX tables, which are also of interest here
1583 // (and override everything else when they apply).
1584 static const int kUseTypoMetricsMask = (1 << 7);
1585 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1586 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1587 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1588 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1589 } else {
1590 ascent = -SkIntToScalar(face->ascender) / upem;
1591 descent = -SkIntToScalar(face->descender) / upem;
1592 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1593 }
1594 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1595 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1596 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1597 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
1598 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
1599 underlinePosition = -SkIntToScalar(face->underline_position +
1600 face->underline_thickness / 2) / upem;
1601
1602 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1603 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
1604
1605 // we may be able to synthesize x_height and cap_height from outline
1606 if (!x_height) {
1607 FT_BBox bbox;
1608 if (getCBoxForLetter('x', &bbox)) {
1609 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1610 }
1611 }
1612 if (!cap_height) {
1613 FT_BBox bbox;
1614 if (getCBoxForLetter('H', &bbox)) {
1615 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1616 }
1617 }
1618 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1619 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1620 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1621 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1622 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
1623 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
1624
1625 xmin = 0.0f;
1626 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1627 ymin = descent;
1628 ymax = ascent;
1629 // The actual bitmaps may be any size and placed at any offset.
1630 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1631
1632 underlineThickness = 0;
1633 underlinePosition = 0;
1634 metrics->fFlags &= ~SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1635 metrics->fFlags &= ~SkFontMetrics::kUnderlinePositionIsValid_Flag;
1636
1637 TT_Postscript* post = (TT_Postscript*) FT_Get_Sfnt_Table(face, ft_sfnt_post);
1638 if (post) {
1639 underlineThickness = SkIntToScalar(post->underlineThickness) / upem;
1640 underlinePosition = -SkIntToScalar(post->underlinePosition) / upem;
1641 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1642 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
1643 }
1644 } else {
1645 sk_bzero(metrics, sizeof(*metrics));
1646 return;
1647 }
1648
1649 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1650 if (!x_height) {
1651 x_height = -ascent * fScale.y();
1652 }
1653 if (!avgCharWidth) {
1654 avgCharWidth = xmax - xmin;
1655 }
1656 if (!cap_height) {
1657 cap_height = -ascent * fScale.y();
1658 }
1659
1660 // disallow negative linespacing
1661 if (leading < 0.0f) {
1662 leading = 0.0f;
1663 }
1664
1665 metrics->fTop = ymax * fScale.y();
1666 metrics->fAscent = ascent * fScale.y();
1667 metrics->fDescent = descent * fScale.y();
1668 metrics->fBottom = ymin * fScale.y();
1669 metrics->fLeading = leading * fScale.y();
1670 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1671 metrics->fXMin = xmin * fScale.y();
1672 metrics->fXMax = xmax * fScale.y();
1673 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
1674 metrics->fXHeight = x_height;
1675 metrics->fCapHeight = cap_height;
1676 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1677 metrics->fUnderlinePosition = underlinePosition * fScale.y();
1678 metrics->fStrikeoutThickness = strikeoutThickness * fScale.y();
1679 metrics->fStrikeoutPosition = strikeoutPosition * fScale.y();
1680
1681 if (face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS
1682 #if defined(FT_CONFIG_OPTION_SVG)
1683 || face->face_flags & FT_FACE_FLAG_SVG
1684 #endif // FT_CONFIG_OPTION_SVG
1685 ) {
1686 // The bounds are only valid for the default variation of variable glyphs.
1687 // https://docs.microsoft.com/en-us/typography/opentype/spec/head
1688 // For SVG glyphs this number is often incorrect for its non-`glyf` points.
1689 // https://github.com/fonttools/fonttools/issues/2566
1690 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1691 }
1692 }
1693
1694 ///////////////////////////////////////////////////////////////////////////////
1695
1696 // hand-tuned value to reduce outline embolden strength
1697 #ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1698 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1699 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1700 #else
1701 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1702 #endif
1703 #endif
1704
1705 ///////////////////////////////////////////////////////////////////////////////
1706
emboldenIfNeeded(FT_Face face,FT_GlyphSlot glyph,SkGlyphID gid)1707 void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid) {
1708 // check to see if the embolden bit is set
1709 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1710 return;
1711 }
1712
1713 switch (glyph->format) {
1714 case FT_GLYPH_FORMAT_OUTLINE:
1715 FT_Pos strength;
1716 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1717 / SK_OUTLINE_EMBOLDEN_DIVISOR;
1718 FT_Outline_Embolden(&glyph->outline, strength);
1719 break;
1720 case FT_GLYPH_FORMAT_BITMAP:
1721 if (!fFace->glyph->bitmap.buffer) {
1722 FT_Load_Glyph(fFace, gid, fLoadGlyphFlags);
1723 }
1724 FT_GlyphSlot_Own_Bitmap(glyph);
1725 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1726 break;
1727 default:
1728 SkDEBUGFAIL("unknown glyph format");
1729 }
1730 }
1731
1732 ///////////////////////////////////////////////////////////////////////////////
1733
1734 #include "src/base/SkUtils.h"
1735
SkTypeface_FreeType(const SkFontStyle & style,bool isFixedPitch)1736 SkTypeface_FreeType::SkTypeface_FreeType(const SkFontStyle& style, bool isFixedPitch)
1737 : INHERITED(style, isFixedPitch)
1738 {}
1739
~SkTypeface_FreeType()1740 SkTypeface_FreeType::~SkTypeface_FreeType() {
1741 if (fFaceRec) {
1742 SkAutoMutexExclusive ac(f_t_mutex());
1743 fFaceRec.reset();
1744 }
1745 }
1746
1747 // Just made up, so we don't end up storing 1000s of entries
1748 constexpr int kMaxC2GCacheCount = 512;
1749
onCharsToGlyphs(const SkUnichar uni[],int count,SkGlyphID glyphs[]) const1750 void SkTypeface_FreeType::onCharsToGlyphs(const SkUnichar uni[], int count,
1751 SkGlyphID glyphs[]) const {
1752 // Try the cache first, *before* accessing freetype lib/face, as that
1753 // can be very slow. If we do need to compute a new glyphID, then
1754 // access those freetype objects and continue the loop.
1755
1756 int i;
1757 {
1758 // Optimistically use a shared lock.
1759 SkAutoSharedMutexShared ama(fC2GCacheMutex);
1760 for (i = 0; i < count; ++i) {
1761 int index = fC2GCache.findGlyphIndex(uni[i]);
1762 if (index < 0) {
1763 break;
1764 }
1765 glyphs[i] = SkToU16(index);
1766 }
1767 if (i == count) {
1768 // we're done, no need to access the freetype objects
1769 return;
1770 }
1771 }
1772
1773 // Need to add more so grab an exclusive lock.
1774 SkAutoSharedMutexExclusive ama(fC2GCacheMutex);
1775 AutoFTAccess fta(this);
1776 FT_Face face = fta.face();
1777 if (!face) {
1778 sk_bzero(glyphs, count * sizeof(glyphs[0]));
1779 return;
1780 }
1781
1782 for (; i < count; ++i) {
1783 SkUnichar c = uni[i];
1784 int index = fC2GCache.findGlyphIndex(c);
1785 if (index >= 0) {
1786 glyphs[i] = SkToU16(index);
1787 } else {
1788 glyphs[i] = SkToU16(FT_Get_Char_Index(face, c));
1789 fC2GCache.insertCharAndGlyph(~index, c, glyphs[i]);
1790 }
1791 }
1792
1793 if (fC2GCache.count() > kMaxC2GCacheCount) {
1794 fC2GCache.reset();
1795 }
1796 }
1797
onCountGlyphs() const1798 int SkTypeface_FreeType::onCountGlyphs() const {
1799 AutoFTAccess fta(this);
1800 FT_Face face = fta.face();
1801 return face ? face->num_glyphs : 0;
1802 }
1803
onCreateFamilyNameIterator() const1804 SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
1805 sk_sp<SkTypeface::LocalizedStrings> nameIter =
1806 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
1807 if (!nameIter) {
1808 SkString familyName;
1809 this->getFamilyName(&familyName);
1810 SkString language("und"); //undetermined
1811 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
1812 }
1813 return nameIter.release();
1814 }
1815
onGlyphMaskNeedsCurrentColor() const1816 bool SkTypeface_FreeType::onGlyphMaskNeedsCurrentColor() const {
1817 fGlyphMasksMayNeedCurrentColorOnce([this]{
1818 static constexpr SkFourByteTag COLRTag = SkSetFourByteTag('C', 'O', 'L', 'R');
1819 fGlyphMasksMayNeedCurrentColor = this->getTableSize(COLRTag) > 0;
1820 #if defined(FT_CONFIG_OPTION_SVG)
1821 static constexpr SkFourByteTag SVGTag = SkSetFourByteTag('S', 'V', 'G', ' ');
1822 fGlyphMasksMayNeedCurrentColor |= this->getTableSize(SVGTag) > 0 ;
1823 #endif // FT_CONFIG_OPTION_SVG
1824 });
1825 return fGlyphMasksMayNeedCurrentColor;
1826 }
1827
onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],int coordinateCount) const1828 int SkTypeface_FreeType::onGetVariationDesignPosition(
1829 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1830 {
1831 AutoFTAccess fta(this);
1832 return GetVariationDesignPosition(fta, coordinates, coordinateCount);
1833 }
1834
onGetVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],int parameterCount) const1835 int SkTypeface_FreeType::onGetVariationDesignParameters(
1836 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
1837 {
1838 AutoFTAccess fta(this);
1839 FT_Face face = fta.face();
1840 if (!face) {
1841 return -1;
1842 }
1843
1844 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1845 return 0;
1846 }
1847
1848 FT_MM_Var* variations = nullptr;
1849 if (FT_Get_MM_Var(face, &variations)) {
1850 return -1;
1851 }
1852 UniqueVoidPtr autoFreeVariations(variations);
1853
1854 if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
1855 return variations->num_axis;
1856 }
1857
1858 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1859 parameters[i].tag = variations->axis[i].tag;
1860 parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
1861 parameters[i].def = SkFixedToScalar(variations->axis[i].def);
1862 parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
1863 FT_UInt flags = 0;
1864 bool hidden = !FT_Get_Var_Axis_Flags(variations, i, &flags) &&
1865 (flags & FT_VAR_AXIS_FLAG_HIDDEN);
1866 parameters[i].setHidden(hidden);
1867 }
1868
1869 return variations->num_axis;
1870 }
1871
onGetTableTags(SkFontTableTag tags[]) const1872 int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1873 AutoFTAccess fta(this);
1874 FT_Face face = fta.face();
1875 if (!face) {
1876 return 0;
1877 }
1878
1879 FT_ULong tableCount = 0;
1880 FT_Error error;
1881
1882 // When 'tag' is nullptr, returns number of tables in 'length'.
1883 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
1884 if (error) {
1885 return 0;
1886 }
1887
1888 if (tags) {
1889 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1890 FT_ULong tableTag;
1891 FT_ULong tablelength;
1892 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1893 if (error) {
1894 return 0;
1895 }
1896 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1897 }
1898 }
1899 return tableCount;
1900 }
1901
onGetTableData(SkFontTableTag tag,size_t offset,size_t length,void * data) const1902 size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1903 size_t length, void* data) const
1904 {
1905 AutoFTAccess fta(this);
1906 FT_Face face = fta.face();
1907 if (!face) {
1908 return 0;
1909 }
1910
1911 FT_ULong tableLength = 0;
1912 FT_Error error;
1913
1914 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1915 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
1916 if (error) {
1917 return 0;
1918 }
1919
1920 if (offset > tableLength) {
1921 return 0;
1922 }
1923 FT_ULong size = std::min((FT_ULong)length, tableLength - (FT_ULong)offset);
1924 if (data) {
1925 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1926 if (error) {
1927 return 0;
1928 }
1929 }
1930
1931 return size;
1932 }
1933
onCopyTableData(SkFontTableTag tag) const1934 sk_sp<SkData> SkTypeface_FreeType::onCopyTableData(SkFontTableTag tag) const {
1935 AutoFTAccess fta(this);
1936 FT_Face face = fta.face();
1937 if (!face) {
1938 return nullptr;
1939 }
1940
1941 FT_ULong tableLength = 0;
1942 FT_Error error;
1943
1944 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1945 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
1946 if (error) {
1947 return nullptr;
1948 }
1949
1950 sk_sp<SkData> data = SkData::MakeUninitialized(tableLength);
1951 if (data) {
1952 error = FT_Load_Sfnt_Table(face, tag, 0,
1953 reinterpret_cast<FT_Byte*>(data->writable_data()), &tableLength);
1954 if (error) {
1955 data.reset();
1956 }
1957 }
1958 return data;
1959 }
1960
getFaceRec() const1961 SkTypeface_FreeType::FaceRec* SkTypeface_FreeType::getFaceRec() const {
1962 f_t_mutex().assertHeld();
1963 fFTFaceOnce([this]{ fFaceRec = SkTypeface_FreeType::FaceRec::Make(this); });
1964 return fFaceRec.get();
1965 }
1966
makeFontData() const1967 std::unique_ptr<SkFontData> SkTypeface_FreeType::makeFontData() const {
1968 return this->onMakeFontData();
1969 }
1970
FontDataPaletteToDescriptorPalette(const SkFontData & fontData,SkFontDescriptor * desc)1971 void SkTypeface_FreeType::FontDataPaletteToDescriptorPalette(const SkFontData& fontData,
1972 SkFontDescriptor* desc) {
1973 desc->setPaletteIndex(fontData.getPaletteIndex());
1974 int paletteOverrideCount = fontData.getPaletteOverrideCount();
1975 auto overrides = desc->setPaletteEntryOverrides(paletteOverrideCount);
1976 for (int i = 0; i < paletteOverrideCount; ++i) {
1977 overrides[i] = fontData.getPaletteOverrides()[i];
1978 }
1979 }
1980
1981 ///////////////////////////////////////////////////////////////////////////////
1982 ///////////////////////////////////////////////////////////////////////////////
1983
Scanner()1984 SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
1985 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1986 return;
1987 }
1988 FT_Add_Default_Modules(fLibrary);
1989 FT_Set_Default_Properties(fLibrary);
1990 }
~Scanner()1991 SkTypeface_FreeType::Scanner::~Scanner() {
1992 if (fLibrary) {
1993 FT_Done_Library(fLibrary);
1994 }
1995 }
1996
openFace(SkStreamAsset * stream,int ttcIndex,FT_Stream ftStream) const1997 FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
1998 FT_Stream ftStream) const
1999 {
2000 if (fLibrary == nullptr || stream == nullptr) {
2001 return nullptr;
2002 }
2003
2004 FT_Open_Args args;
2005 memset(&args, 0, sizeof(args));
2006
2007 const void* memoryBase = stream->getMemoryBase();
2008
2009 if (memoryBase) {
2010 args.flags = FT_OPEN_MEMORY;
2011 args.memory_base = (const FT_Byte*)memoryBase;
2012 args.memory_size = stream->getLength();
2013 } else {
2014 memset(ftStream, 0, sizeof(*ftStream));
2015 ftStream->size = stream->getLength();
2016 ftStream->descriptor.pointer = stream;
2017 ftStream->read = sk_ft_stream_io;
2018 ftStream->close = sk_ft_stream_close;
2019
2020 args.flags = FT_OPEN_STREAM;
2021 args.stream = ftStream;
2022 }
2023
2024 FT_Face face;
2025 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
2026 return nullptr;
2027 }
2028 return face;
2029 }
2030
recognizedFont(SkStreamAsset * stream,int * numFaces) const2031 bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
2032 SkAutoMutexExclusive libraryLock(fLibraryMutex);
2033
2034 FT_StreamRec streamRec;
2035 SkUniqueFTFace face(this->openFace(stream, -1, &streamRec));
2036 if (!face) {
2037 return false;
2038 }
2039
2040 *numFaces = face->num_faces;
2041 return true;
2042 }
2043
scanFont(SkStreamAsset * stream,int ttcIndex,SkString * name,SkFontStyle * style,bool * isFixedPitch,AxisDefinitions * axes) const2044 bool SkTypeface_FreeType::Scanner::scanFont(
2045 SkStreamAsset* stream, int ttcIndex,
2046 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
2047 {
2048 SkAutoMutexExclusive libraryLock(fLibraryMutex);
2049
2050 FT_StreamRec streamRec;
2051 SkUniqueFTFace face(this->openFace(stream, ttcIndex, &streamRec));
2052 if (!face) {
2053 return false;
2054 }
2055
2056 int weight = SkFontStyle::kNormal_Weight;
2057 int width = SkFontStyle::kNormal_Width;
2058 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
2059 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
2060 weight = SkFontStyle::kBold_Weight;
2061 }
2062 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
2063 slant = SkFontStyle::kItalic_Slant;
2064 }
2065
2066 bool hasAxes = face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS;
2067 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face.get(), ft_sfnt_os2));
2068 bool hasOs2 = os2 && os2->version != 0xffff;
2069
2070 PS_FontInfoRec psFontInfo;
2071
2072 if (hasOs2) {
2073 weight = os2->usWeightClass;
2074 width = os2->usWidthClass;
2075
2076 // OS/2::fsSelection bit 9 indicates oblique.
2077 if (SkToBool(os2->fsSelection & (1u << 9))) {
2078 slant = SkFontStyle::kOblique_Slant;
2079 }
2080 }
2081
2082 // Let variable axes override properties from the OS/2 table.
2083 if (hasAxes) {
2084 AxisDefinitions axisDefinitions;
2085 if (GetAxes(face.get(), &axisDefinitions)) {
2086 size_t numAxes = axisDefinitions.size();
2087 static constexpr SkFourByteTag wghtTag = SkSetFourByteTag('w', 'g', 'h', 't');
2088 static constexpr SkFourByteTag wdthTag = SkSetFourByteTag('w', 'd', 't', 'h');
2089 static constexpr SkFourByteTag slntTag = SkSetFourByteTag('s', 'l', 'n', 't');
2090 std::optional<size_t> wghtIndex;
2091 std::optional<size_t> wdthIndex;
2092 std::optional<size_t> slntIndex;
2093 for(size_t i = 0; i < numAxes; ++i) {
2094 if (axisDefinitions[i].fTag == wghtTag) {
2095 // Rough validity check, is there sufficient spread and are ranges
2096 // within 0-1000.
2097 int wghtRange = SkFixedToScalar(axisDefinitions[i].fMaximum) -
2098 SkFixedToScalar(axisDefinitions[i].fMinimum);
2099 if (wghtRange > 5 && wghtRange <= 1000 &&
2100 SkFixedToScalar(axisDefinitions[i].fMaximum) <= 1000) {
2101 wghtIndex = i;
2102 }
2103 }
2104 if (axisDefinitions[i].fTag == wdthTag) {
2105 // Rough validity check, is there a spread and are ranges within
2106 // 0-500.
2107 int widthRange = SkFixedToScalar(axisDefinitions[i].fMaximum) -
2108 SkFixedToScalar(axisDefinitions[i].fMinimum);
2109 if (widthRange > 0 && widthRange <= 500 &&
2110 SkFixedToScalar(axisDefinitions[i].fMaximum) <= 500)
2111 wdthIndex = i;
2112 }
2113 if (axisDefinitions[i].fTag == slntTag)
2114 slntIndex = i;
2115 }
2116 AutoSTMalloc<4, FT_Fixed> coords(numAxes);
2117 if ((wghtIndex || wdthIndex || slntIndex) &&
2118 !FT_Get_Var_Design_Coordinates(face.get(), numAxes, coords.get())) {
2119 if (wghtIndex) {
2120 SkASSERT(*wghtIndex < numAxes);
2121 weight = SkScalarRoundToInt(SkFixedToScalar(coords[*wghtIndex]));
2122 }
2123 if (wdthIndex) {
2124 SkASSERT(*wdthIndex < numAxes);
2125 SkScalar wdthValue = SkFixedToScalar(coords[*wdthIndex]);
2126 width = SkFontDescriptor::SkFontStyleWidthForWidthAxisValue(wdthValue);
2127 }
2128 if (slntIndex) {
2129 SkASSERT(*slntIndex < numAxes);
2130 // https://docs.microsoft.com/en-us/typography/opentype/spec/dvaraxistag_slnt
2131 // "Scale interpretation: Values can be interpreted as the angle,
2132 // in counter-clockwise degrees, of oblique slant from whatever
2133 // the designer considers to be upright for that font design."
2134 if (SkFixedToScalar(coords[*slntIndex]) < 0) {
2135 slant = SkFontStyle::kOblique_Slant;
2136 }
2137 }
2138 }
2139 }
2140 }
2141
2142 if (!hasOs2 && !hasAxes && 0 == FT_Get_PS_Font_Info(face.get(), &psFontInfo) && psFontInfo.weight) {
2143 static const struct {
2144 char const * const name;
2145 int const weight;
2146 } commonWeights [] = {
2147 // There are probably more common names, but these are known to exist.
2148 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
2149 { "black", SkFontStyle::kBlack_Weight },
2150 { "bold", SkFontStyle::kBold_Weight },
2151 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
2152 { "demi", SkFontStyle::kSemiBold_Weight },
2153 { "demibold", SkFontStyle::kSemiBold_Weight },
2154 { "extra", SkFontStyle::kExtraBold_Weight },
2155 { "extrabold", SkFontStyle::kExtraBold_Weight },
2156 { "extralight", SkFontStyle::kExtraLight_Weight },
2157 { "hairline", SkFontStyle::kThin_Weight },
2158 { "heavy", SkFontStyle::kBlack_Weight },
2159 { "light", SkFontStyle::kLight_Weight },
2160 { "medium", SkFontStyle::kMedium_Weight },
2161 { "normal", SkFontStyle::kNormal_Weight },
2162 { "plain", SkFontStyle::kNormal_Weight },
2163 { "regular", SkFontStyle::kNormal_Weight },
2164 { "roman", SkFontStyle::kNormal_Weight },
2165 { "semibold", SkFontStyle::kSemiBold_Weight },
2166 { "standard", SkFontStyle::kNormal_Weight },
2167 { "thin", SkFontStyle::kThin_Weight },
2168 { "ultra", SkFontStyle::kExtraBold_Weight },
2169 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
2170 { "ultrabold", SkFontStyle::kExtraBold_Weight },
2171 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
2172 { "ultralight", SkFontStyle::kExtraLight_Weight },
2173 };
2174 int const index = SkStrLCSearch(&commonWeights[0].name, std::size(commonWeights),
2175 psFontInfo.weight, sizeof(commonWeights[0]));
2176 if (index >= 0) {
2177 weight = commonWeights[index].weight;
2178 } else {
2179 LOG_INFO("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
2180 }
2181 }
2182
2183 if (name != nullptr) {
2184 name->set(face->family_name);
2185 }
2186 if (style != nullptr) {
2187 *style = SkFontStyle(weight, width, slant);
2188 }
2189 if (isFixedPitch != nullptr) {
2190 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
2191 }
2192
2193 if (axes != nullptr && !GetAxes(face.get(), axes)) {
2194 return false;
2195 }
2196 return true;
2197 }
2198
GetAxes(FT_Face face,AxisDefinitions * axes)2199 bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
2200 SkASSERT(face && axes);
2201 if (face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
2202 FT_MM_Var* variations = nullptr;
2203 FT_Error err = FT_Get_MM_Var(face, &variations);
2204 if (err) {
2205 LOG_INFO("INFO: font %s claims to have variations, but none found.\n",
2206 face->family_name);
2207 return false;
2208 }
2209 UniqueVoidPtr autoFreeVariations(variations);
2210
2211 axes->reset(variations->num_axis);
2212 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
2213 const FT_Var_Axis& ftAxis = variations->axis[i];
2214 (*axes)[i].fTag = ftAxis.tag;
2215 (*axes)[i].fMinimum = ftAxis.minimum;
2216 (*axes)[i].fDefault = ftAxis.def;
2217 (*axes)[i].fMaximum = ftAxis.maximum;
2218 }
2219 }
2220 return true;
2221 }
2222
computeAxisValues(AxisDefinitions axisDefinitions,const SkFontArguments::VariationPosition position,SkFixed * axisValues,const SkString & name,const SkFontArguments::VariationPosition::Coordinate * current)2223 /*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
2224 AxisDefinitions axisDefinitions,
2225 const SkFontArguments::VariationPosition position,
2226 SkFixed* axisValues,
2227 const SkString& name,
2228 const SkFontArguments::VariationPosition::Coordinate* current)
2229 {
2230 for (int i = 0; i < axisDefinitions.size(); ++i) {
2231 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
2232 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
2233 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
2234
2235 // Start with the default value.
2236 axisValues[i] = axisDefinition.fDefault;
2237
2238 // Then the current value.
2239 if (current) {
2240 for (int j = 0; j < axisDefinitions.size(); ++j) {
2241 const auto& coordinate = current[j];
2242 if (axisDefinition.fTag == coordinate.axis) {
2243 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
2244 axisValues[i] = SkScalarToFixed(axisValue);
2245 break;
2246 }
2247 }
2248 }
2249
2250 // Then the requested value.
2251 // The position may be over specified. If there are multiple values for a given axis,
2252 // use the last one since that's what css-fonts-4 requires.
2253 for (int j = position.coordinateCount; j --> 0;) {
2254 const auto& coordinate = position.coordinates[j];
2255 if (axisDefinition.fTag == coordinate.axis) {
2256 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
2257 if (coordinate.value != axisValue) {
2258 LOG_INFO("Requested font axis value out of range: "
2259 "%s '%c%c%c%c' %f; pinned to %f.\n",
2260 name.c_str(),
2261 (axisDefinition.fTag >> 24) & 0xFF,
2262 (axisDefinition.fTag >> 16) & 0xFF,
2263 (axisDefinition.fTag >> 8) & 0xFF,
2264 (axisDefinition.fTag ) & 0xFF,
2265 SkScalarToDouble(coordinate.value),
2266 SkScalarToDouble(axisValue));
2267 }
2268 axisValues[i] = SkScalarToFixed(axisValue);
2269 break;
2270 }
2271 }
2272 // TODO: warn on defaulted axis?
2273 }
2274
2275 SkDEBUGCODE(
2276 // Check for axis specified, but not matched in font.
2277 for (int i = 0; i < position.coordinateCount; ++i) {
2278 SkFourByteTag skTag = position.coordinates[i].axis;
2279 bool found = false;
2280 for (int j = 0; j < axisDefinitions.size(); ++j) {
2281 if (skTag == axisDefinitions[j].fTag) {
2282 found = true;
2283 break;
2284 }
2285 }
2286 if (!found) {
2287 LOG_INFO("Requested font axis not found: %s '%c%c%c%c'\n",
2288 name.c_str(),
2289 (skTag >> 24) & 0xFF,
2290 (skTag >> 16) & 0xFF,
2291 (skTag >> 8) & 0xFF,
2292 (skTag) & 0xFF);
2293 }
2294 }
2295 )
2296 }
2297
2298
SkTypeface_FreeTypeStream(std::unique_ptr<SkFontData> fontData,const SkString familyName,const SkFontStyle & style,bool isFixedPitch)2299 SkTypeface_FreeTypeStream::SkTypeface_FreeTypeStream(std::unique_ptr<SkFontData> fontData,
2300 const SkString familyName,
2301 const SkFontStyle& style, bool isFixedPitch)
2302 : SkTypeface_FreeType(style, isFixedPitch)
2303 , fFamilyName(std::move(familyName))
2304 , fData(std::move(fontData))
2305 { }
2306
~SkTypeface_FreeTypeStream()2307 SkTypeface_FreeTypeStream::~SkTypeface_FreeTypeStream() {}
2308
onGetFamilyName(SkString * familyName) const2309 void SkTypeface_FreeTypeStream::onGetFamilyName(SkString* familyName) const {
2310 *familyName = fFamilyName;
2311 }
2312
onOpenStream(int * ttcIndex) const2313 std::unique_ptr<SkStreamAsset> SkTypeface_FreeTypeStream::onOpenStream(int* ttcIndex) const {
2314 *ttcIndex = fData->getIndex();
2315 return fData->getStream()->duplicate();
2316 }
2317
onMakeFontData() const2318 std::unique_ptr<SkFontData> SkTypeface_FreeTypeStream::onMakeFontData() const {
2319 return std::make_unique<SkFontData>(*fData);
2320 }
2321
onMakeClone(const SkFontArguments & args) const2322 sk_sp<SkTypeface> SkTypeface_FreeTypeStream::onMakeClone(const SkFontArguments& args) const {
2323 std::unique_ptr<SkFontData> data = this->cloneFontData(args);
2324 if (!data) {
2325 return nullptr;
2326 }
2327
2328 SkString familyName;
2329 this->getFamilyName(&familyName);
2330
2331 return sk_make_sp<SkTypeface_FreeTypeStream>(
2332 std::move(data), familyName, this->fontStyle(), this->isFixedPitch());
2333 }
2334
onGetFontDescriptor(SkFontDescriptor * desc,bool * serialize) const2335 void SkTypeface_FreeTypeStream::onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const {
2336 desc->setFamilyName(fFamilyName.c_str());
2337 desc->setStyle(this->fontStyle());
2338 desc->setFactoryId(SkTypeface_FreeType::FactoryId);
2339 SkTypeface_FreeType::FontDataPaletteToDescriptorPalette(*fData, desc);
2340 *serialize = true;
2341 }
2342
MakeFromStream(std::unique_ptr<SkStreamAsset> stream,const SkFontArguments & args)2343 sk_sp<SkTypeface> SkTypeface_FreeType::MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
2344 const SkFontArguments& args) {
2345 using Scanner = SkTypeface_FreeType::Scanner;
2346 static Scanner scanner;
2347 bool isFixedPitch;
2348 SkFontStyle style;
2349 SkString name;
2350 Scanner::AxisDefinitions axisDefinitions;
2351 if (!scanner.scanFont(stream.get(), args.getCollectionIndex(),
2352 &name, &style, &isFixedPitch, &axisDefinitions)) {
2353 return nullptr;
2354 }
2355
2356 const SkFontArguments::VariationPosition position = args.getVariationDesignPosition();
2357 AutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.size());
2358 Scanner::computeAxisValues(axisDefinitions, position, axisValues, name);
2359
2360 auto data = std::make_unique<SkFontData>(
2361 std::move(stream), args.getCollectionIndex(), args.getPalette().index,
2362 axisValues.get(), axisDefinitions.size(),
2363 args.getPalette().overrides, args.getPalette().overrideCount);
2364 return sk_make_sp<SkTypeface_FreeTypeStream>(std::move(data), name, style, isFixedPitch);
2365 }
2366