Debian Codegraph @

src/ports/SkFontHost_FreeType.cpp

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