blob: 7f35ef7b2dcd6244adca5afa187eda5cd3aa2d44 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/core/SkBitmap.h"
9#include "include/core/SkCanvas.h"
Mike Reed6d907fa2019-07-24 14:51:34 -040010#include "include/core/SkData.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "include/core/SkFontMetrics.h"
12#include "include/core/SkPath.h"
13#include "include/core/SkStream.h"
14#include "include/core/SkString.h"
15#include "include/private/SkColorData.h"
16#include "include/private/SkMalloc.h"
17#include "include/private/SkMutex.h"
Mike Klein8aa0edf2020-10-16 11:04:18 -050018#include "include/private/SkTPin.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "include/private/SkTemplates.h"
20#include "include/private/SkTo.h"
21#include "src/core/SkAdvancedTypefaceMetrics.h"
22#include "src/core/SkDescriptor.h"
23#include "src/core/SkFDot6.h"
24#include "src/core/SkFontDescriptor.h"
25#include "src/core/SkGlyph.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050026#include "src/core/SkMask.h"
27#include "src/core/SkMaskGamma.h"
28#include "src/core/SkScalerContext.h"
Ben Wagner12745c82021-07-19 11:03:45 -040029#include "src/core/SkTSearch.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050030#include "src/ports/SkFontHost_FreeType_common.h"
31#include "src/sfnt/SkOTUtils.h"
32#include "src/utils/SkCallableTraits.h"
33#include "src/utils/SkMatrix22.h"
Hal Canaryc640d0d2018-06-13 09:59:02 -040034
mtklein5f939ab2016-03-16 10:28:35 -070035#include <memory>
Ben Wagnerf25787b2020-12-01 20:22:00 -050036#include <tuple>
reed@android.com8a1c16f2008-12-17 15:59:43 +000037
38#include <ft2build.h>
Ben Wagner12745c82021-07-19 11:03:45 -040039#include <freetype/ftadvanc.h>
Dominik Röttsches2fa273e2021-08-10 12:10:45 +030040#include <freetype/ftimage.h>
Ben Wagner12745c82021-07-19 11:03:45 -040041#include <freetype/ftbitmap.h>
42#ifdef FT_COLOR_H // 2.10.0
43# include <freetype/ftcolor.h>
Bruce Wangf3ca1c62018-07-09 10:08:36 -040044#endif
Ben Wagner12745c82021-07-19 11:03:45 -040045#include <freetype/freetype.h>
46#include <freetype/ftlcdfil.h>
47#include <freetype/ftmodapi.h>
48#include <freetype/ftmm.h>
49#include <freetype/ftoutln.h>
50#include <freetype/ftsizes.h>
51#include <freetype/ftsystem.h>
52#include <freetype/tttables.h>
53#include <freetype/t1tables.h>
54#include <freetype/ftfntfmt.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000055
Ben Wagnerfc497342017-02-24 11:15:26 -050056// SK_FREETYPE_MINIMUM_RUNTIME_VERSION 0x<major><minor><patch><flags>
57// Flag SK_FREETYPE_DLOPEN: also try dlopen to get newer features.
58#define SK_FREETYPE_DLOPEN (0x1)
59#ifndef SK_FREETYPE_MINIMUM_RUNTIME_VERSION
Mike Klein6613cc52017-12-19 09:09:33 -050060# if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) || defined (SK_BUILD_FOR_GOOGLE3)
Ben Wagnerfc497342017-02-24 11:15:26 -050061# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION (((FREETYPE_MAJOR) << 24) | ((FREETYPE_MINOR) << 16) | ((FREETYPE_PATCH) << 8))
62# else
Ben Wagner12745c82021-07-19 11:03:45 -040063# define SK_FREETYPE_MINIMUM_RUNTIME_VERSION ((2 << 24) | (8 << 16) | (1 << 8) | (SK_FREETYPE_DLOPEN))
Ben Wagnerfc497342017-02-24 11:15:26 -050064# endif
65#endif
66#if SK_FREETYPE_MINIMUM_RUNTIME_VERSION & SK_FREETYPE_DLOPEN
67# include <dlfcn.h>
68#endif
69
Ben Wagnerb65f0fa2021-11-23 15:42:52 -050070#ifdef TT_SUPPORT_COLRV1
71// FT_ClipBox and FT_Get_Color_Glyph_ClipBox introduced VER-2-11-0-18-g47cf8ebf4
72// FT_COLR_COMPOSITE_PLUS and renumbering introduced VER-2-11-0-21-ge40ae7569
73// FT_SIZEOF_LONG_LONG introduced VER-2-11-0-31-gffdac8d67
74// FT_PaintRadialGradient changed size and layout at VER-2-11-0-147-gd3d3ff76d
75// FT_STATIC_CAST introduced VER-2-11-0-172-g9079c5d91
76// So undefine TT_SUPPORT_COLRV1 before 2.11.1 but not if FT_STATIC_CAST is defined.
77#if (((FREETYPE_MAJOR) < 2) || \
78 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) < 11) || \
79 ((FREETYPE_MAJOR) == 2 && (FREETYPE_MINOR) == 11 && (FREETYPE_PATCH) < 1)) && \
80 !defined(FT_STATIC_CAST)
81# undef TT_SUPPORT_COLRV1
82#endif
83#endif
84
reed@android.com8a1c16f2008-12-17 15:59:43 +000085//#define ENABLE_GLYPH_SPEW // for tracing calls
86//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080087//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000088//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000089
Mike Klein3e0141a2019-03-26 10:41:18 -050090#if 1
91 #define LOG_INFO(...)
92#else
93 #define LOG_INFO SkDEBUGF
94#endif
95
Ben Wagner3e45a2f2017-11-01 11:47:39 -040096static bool isLCD(const SkScalerContextRec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080097 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000098}
99
Ben Wagner082a7a72018-06-08 14:15:47 -0400100static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
101 return SkFixedToScalar(x);
102}
103
Ben Wagner6669b012020-07-08 11:58:18 -0400104using SkUniqueFTFace =
105 std::unique_ptr<FT_FaceRec, SkFunctionWrapper<decltype(FT_Done_Face), FT_Done_Face>>;
106
reed@android.com8a1c16f2008-12-17 15:59:43 +0000107//////////////////////////////////////////////////////////////////////////
108
Ben Wagner230a71b2018-10-01 14:54:01 -0400109using FT_Alloc_size_t = SkCallableTraits<FT_Alloc_Func>::argument<1>::type;
110static_assert(std::is_same<FT_Alloc_size_t, long >::value ||
111 std::is_same<FT_Alloc_size_t, size_t>::value,"");
112
bungeman9dc24682014-12-01 14:01:32 -0800113extern "C" {
Ben Wagner230a71b2018-10-01 14:54:01 -0400114 static void* sk_ft_alloc(FT_Memory, FT_Alloc_size_t size) {
bungeman9dc24682014-12-01 14:01:32 -0800115 return sk_malloc_throw(size);
116 }
117 static void sk_ft_free(FT_Memory, void* block) {
118 sk_free(block);
119 }
Ben Wagner230a71b2018-10-01 14:54:01 -0400120 static void* sk_ft_realloc(FT_Memory, FT_Alloc_size_t cur_size,
121 FT_Alloc_size_t new_size, void* block) {
bungeman9dc24682014-12-01 14:01:32 -0800122 return sk_realloc_throw(block, new_size);
123 }
124};
halcanary96fcdcc2015-08-27 07:41:13 -0700125FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -0800126
127class FreeTypeLibrary : SkNoncopyable {
128public:
Ben Wagner12745c82021-07-19 11:03:45 -0400129 FreeTypeLibrary() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -0800130 if (FT_New_Library(&gFTMemory, &fLibrary)) {
131 return;
132 }
133 FT_Add_Default_Modules(fLibrary);
Ben Wagner2a098d02017-03-01 13:00:53 -0500134 FT_Set_Default_Properties(fLibrary);
bungeman9dc24682014-12-01 14:01:32 -0800135
Ben Wagner12745c82021-07-19 11:03:45 -0400136 // Subpixel anti-aliasing may be unfiltered until the LCD filter is set.
137 // Newer versions may still need this, so this test with side effects must come first.
138 // The default has changed over time, so this doesn't mean the same thing to all users.
139 FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT);
bungeman9dc24682014-12-01 14:01:32 -0800140 }
141 ~FreeTypeLibrary() {
142 if (fLibrary) {
143 FT_Done_Library(fLibrary);
144 }
145 }
146
147 FT_Library library() { return fLibrary; }
Ben Wagnere346b1e2018-06-26 11:22:37 -0400148
bungeman9dc24682014-12-01 14:01:32 -0800149private:
150 FT_Library fLibrary;
bungeman9dc24682014-12-01 14:01:32 -0800151
Ben Wagner12745c82021-07-19 11:03:45 -0400152 // FT_Library_SetLcdFilterWeights 2.4.0
153 // FT_LOAD_COLOR 2.5.0
154 // FT_Pixel_Mode::FT_PIXEL_MODE_BGRA 2.5.0
155 // Thread safety in 2.6.0
156 // freetype/ftfntfmt.h (rename) 2.6.0
157 // Direct header inclusion 2.6.1
158 // FT_Get_Var_Design_Coordinates 2.7.1
159 // FT_LOAD_BITMAP_METRICS_ONLY 2.7.1
160 // FT_Set_Default_Properties 2.7.2
161 // The 'light' hinting is vertical only from 2.8.0
162 // FT_Get_Var_Axis_Flags 2.8.1
163 // FT_VAR_AXIS_FLAG_HIDDEN was introduced in FreeType 2.8.1
164 // --------------------
165 // FT_Done_MM_Var 2.9.0 (Currenty setting ft_free to a known allocator.)
166 // freetype/ftcolor.h 2.10.0 (Currently assuming if compiled with FT_COLOR_H runtime available.)
Ben Wagner2a098d02017-03-01 13:00:53 -0500167
Ben Wagner12745c82021-07-19 11:03:45 -0400168 // Ubuntu 18.04 2.8.1
169 // Debian 10 2.9.1
170 // openSUSE Leap 15.2 2.10.1
171 // Fedora 32 2.10.4
172 // RHEL 8 2.9.1
bungeman9dc24682014-12-01 14:01:32 -0800173};
174
Herb Derby9c71e7b2019-06-17 14:40:42 -0400175static SkMutex& f_t_mutex() {
176 static SkMutex& mutex = *(new SkMutex);
177 return mutex;
178}
179
bungeman9dc24682014-12-01 14:01:32 -0800180static FreeTypeLibrary* gFTLibrary;
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000181
Ben Wagnerfc497342017-02-24 11:15:26 -0500182///////////////////////////////////////////////////////////////////////////
183
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400184class SkTypeface_FreeType::FaceRec {
185public:
Ben Wagner6669b012020-07-08 11:58:18 -0400186 SkUniqueFTFace fFace;
Ben Wagnerfc497342017-02-24 11:15:26 -0500187 FT_StreamRec fFTStream;
188 std::unique_ptr<SkStreamAsset> fSkStream;
Ben Wagnerfc497342017-02-24 11:15:26 -0500189
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400190 static std::unique_ptr<FaceRec> Make(const SkTypeface_FreeType* typeface);
191 ~FaceRec();
192
193private:
194 FaceRec(std::unique_ptr<SkStreamAsset> stream);
195 void setupAxes(const SkFontData& data);
196
197 // Private to ref_ft_library and unref_ft_library
198 static int gFTCount;
199
200 // Caller must lock f_t_mutex() before calling this function.
201 static bool ref_ft_library() {
202 f_t_mutex().assertHeld();
203 SkASSERT(gFTCount >= 0);
204
205 if (0 == gFTCount) {
206 SkASSERT(nullptr == gFTLibrary);
207 gFTLibrary = new FreeTypeLibrary;
208 }
209 ++gFTCount;
210 return gFTLibrary->library();
211 }
212
213 // Caller must lock f_t_mutex() before calling this function.
214 static void unref_ft_library() {
215 f_t_mutex().assertHeld();
216 SkASSERT(gFTCount > 0);
217
218 --gFTCount;
219 if (0 == gFTCount) {
220 SkASSERT(nullptr != gFTLibrary);
221 delete gFTLibrary;
222 SkDEBUGCODE(gFTLibrary = nullptr;)
223 }
224 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500225};
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400226int SkTypeface_FreeType::FaceRec::gFTCount;
Ben Wagnerfc497342017-02-24 11:15:26 -0500227
228extern "C" {
229 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
230 unsigned long offset,
231 unsigned char* buffer,
232 unsigned long count)
233 {
234 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
235
236 if (count) {
237 if (!stream->seek(offset)) {
238 return 0;
239 }
240 count = stream->read(buffer, count);
241 }
242 return count;
243 }
244
245 static void sk_ft_stream_close(FT_Stream) {}
246}
247
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400248SkTypeface_FreeType::FaceRec::FaceRec(std::unique_ptr<SkStreamAsset> stream)
Ben Wagner12745c82021-07-19 11:03:45 -0400249 : fSkStream(std::move(stream))
Ben Wagnerfc497342017-02-24 11:15:26 -0500250{
251 sk_bzero(&fFTStream, sizeof(fFTStream));
252 fFTStream.size = fSkStream->getLength();
253 fFTStream.descriptor.pointer = fSkStream.get();
254 fFTStream.read = sk_ft_stream_io;
255 fFTStream.close = sk_ft_stream_close;
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400256
257 f_t_mutex().assertHeld();
258 ref_ft_library();
Ben Wagnerfc497342017-02-24 11:15:26 -0500259}
260
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400261SkTypeface_FreeType::FaceRec::~FaceRec() {
Ben Wagner266bf822021-06-30 16:27:14 -0400262 f_t_mutex().assertHeld();
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400263 fFace.reset(); // Must release face before the library, the library frees existing faces.
264 unref_ft_library();
265}
266
267void SkTypeface_FreeType::FaceRec::setupAxes(const SkFontData& data) {
268 if (!(fFace->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500269 return;
270 }
271
272 // If a named variation is requested, don't overwrite the named variation's position.
273 if (data.getIndex() > 0xFFFF) {
Ben Wagnerfc497342017-02-24 11:15:26 -0500274 return;
275 }
276
277 SkDEBUGCODE(
278 FT_MM_Var* variations = nullptr;
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400279 if (FT_Get_MM_Var(fFace.get(), &variations)) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500280 LOG_INFO("INFO: font %s claims variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400281 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500282 return;
283 }
284 SkAutoFree autoFreeVariations(variations);
285
286 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500287 LOG_INFO("INFO: font %s has %d variations, but %d were specified.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400288 rec->fFace->family_name, variations->num_axis, data.getAxisCount());
Ben Wagnerfc497342017-02-24 11:15:26 -0500289 return;
290 }
291 )
292
293 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
294 for (int i = 0; i < data.getAxisCount(); ++i) {
295 coords[i] = data.getAxis()[i];
296 }
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400297 if (FT_Set_Var_Design_Coordinates(fFace.get(), data.getAxisCount(), coords.get())) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500298 LOG_INFO("INFO: font %s has variations, but specified variations could not be set.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400299 rec->fFace->family_name);
Ben Wagnerfc497342017-02-24 11:15:26 -0500300 return;
301 }
Ben Wagnerfc497342017-02-24 11:15:26 -0500302}
303
304// Will return nullptr on failure
Herb Derby9c71e7b2019-06-17 14:40:42 -0400305// Caller must lock f_t_mutex() before calling this function.
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400306std::unique_ptr<SkTypeface_FreeType::FaceRec>
307SkTypeface_FreeType::FaceRec::Make(const SkTypeface_FreeType* typeface) {
Herb Derby9c71e7b2019-06-17 14:40:42 -0400308 f_t_mutex().assertHeld();
Ben Wagnerfc497342017-02-24 11:15:26 -0500309
Ben Wagnerfc497342017-02-24 11:15:26 -0500310 std::unique_ptr<SkFontData> data = typeface->makeFontData();
311 if (nullptr == data || !data->hasStream()) {
312 return nullptr;
313 }
314
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400315 std::unique_ptr<FaceRec> rec(new FaceRec(data->detachStream()));
Ben Wagnerfc497342017-02-24 11:15:26 -0500316
317 FT_Open_Args args;
318 memset(&args, 0, sizeof(args));
319 const void* memoryBase = rec->fSkStream->getMemoryBase();
320 if (memoryBase) {
321 args.flags = FT_OPEN_MEMORY;
322 args.memory_base = (const FT_Byte*)memoryBase;
323 args.memory_size = rec->fSkStream->getLength();
324 } else {
325 args.flags = FT_OPEN_STREAM;
326 args.stream = &rec->fFTStream;
327 }
328
329 {
330 FT_Face rawFace;
331 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rawFace);
332 if (err) {
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400333 SK_TRACEFTR(err, "unable to open font '%x'", typeface->uniqueID());
Ben Wagnerfc497342017-02-24 11:15:26 -0500334 return nullptr;
335 }
336 rec->fFace.reset(rawFace);
337 }
338 SkASSERT(rec->fFace);
339
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400340 rec->setupAxes(*data);
Ben Wagnerfc497342017-02-24 11:15:26 -0500341
342 // FreeType will set the charmap to the "most unicode" cmap if it exists.
343 // If there are no unicode cmaps, the charmap is set to nullptr.
344 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
345 // because they are effectively private use area only (even if they aren't).
346 // This is the last on the fallback list at
347 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
348 if (!rec->fFace->charmap) {
349 FT_Select_Charmap(rec->fFace.get(), FT_ENCODING_MS_SYMBOL);
350 }
351
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400352 return rec;
Ben Wagnerfc497342017-02-24 11:15:26 -0500353}
354
355class AutoFTAccess {
356public:
Ben Wagner9d5c55c2020-06-27 12:52:14 -0400357 AutoFTAccess(const SkTypeface_FreeType* tf) : fFaceRec(nullptr) {
Herb Derby9c71e7b2019-06-17 14:40:42 -0400358 f_t_mutex().acquire();
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400359 fFaceRec = tf->getFaceRec();
Ben Wagnerfc497342017-02-24 11:15:26 -0500360 }
361
362 ~AutoFTAccess() {
Herb Derby9c71e7b2019-06-17 14:40:42 -0400363 f_t_mutex().release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500364 }
365
366 FT_Face face() { return fFaceRec ? fFaceRec->fFace.get() : nullptr; }
Ben Wagnerfc497342017-02-24 11:15:26 -0500367
368private:
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400369 SkTypeface_FreeType::FaceRec* fFaceRec;
Ben Wagnerfc497342017-02-24 11:15:26 -0500370};
371
372///////////////////////////////////////////////////////////////////////////
373
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000374class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000375public:
Ben Wagner9d5c55c2020-06-27 12:52:14 -0400376 SkScalerContext_FreeType(sk_sp<SkTypeface_FreeType>,
bungeman7cfd46a2016-10-20 16:06:52 -0400377 const SkScalerContextEffects&,
378 const SkDescriptor* desc);
Brian Salomond3b65972017-03-22 12:05:03 -0400379 ~SkScalerContext_FreeType() override;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000380
reed@android.com62900b42009-02-11 15:07:19 +0000381 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700382 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000383 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000384
385protected:
Ben Wagnere5416452018-08-09 14:03:42 -0400386 bool generateAdvance(SkGlyph* glyph) override;
Ben Wagner66899512021-12-01 17:27:08 -0500387 void generateMetrics(SkGlyph* glyph, SkArenaAlloc*) override;
mtklein36352bf2015-03-25 18:17:31 -0700388 void generateImage(const SkGlyph& glyph) override;
Ben Wagner66899512021-12-01 17:27:08 -0500389 bool generatePath(const SkGlyph& glyph, SkPath* path) override;
Mike Reedb5784ac2018-11-12 09:35:15 -0500390 void generateFontMetrics(SkFontMetrics*) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000391
392private:
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400393 SkTypeface_FreeType::FaceRec* fFaceRec; // Borrowed face from the typeface's FaceRec.
394 FT_Face fFace; // Borrowed face from fFaceRec.
395 FT_Size fFTSize; // The size to apply to the fFace.
396 FT_Int fStrikeIndex; // The bitmap strike for the fFace (or -1 if none).
reed@android.com8a1c16f2008-12-17 15:59:43 +0000397
bungeman401ae2d2016-07-18 15:46:27 -0700398 /** The rest of the matrix after FreeType handles the size.
399 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
400 * With bitmap only fonts this matrix must be applied to scale the bitmap.
401 */
402 SkMatrix fMatrix22Scalar;
403 /** Same as fMatrix22Scalar, but in FreeType units and space. */
404 FT_Matrix fMatrix22;
405 /** The actual size requested. */
406 SkVector fScale;
407
408 uint32_t fLoadGlyphFlags;
409 bool fDoLinearMetrics;
410 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000411
reed@android.com8a1c16f2008-12-17 15:59:43 +0000412 FT_Error setupSize();
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400413 void getBBoxForCurrentGlyph(const SkGlyph* glyph, FT_BBox* bbox,
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000414 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000415 bool getCBoxForLetter(char letter, FT_BBox* bbox);
Herb Derby9c71e7b2019-06-17 14:40:42 -0400416 // Caller must lock f_t_mutex() before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000417 void updateGlyphIfLCD(SkGlyph* glyph);
Herb Derby9c71e7b2019-06-17 14:40:42 -0400418 // Caller must lock f_t_mutex() before calling this function.
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000419 // update FreeType2 glyph slot with glyph emboldened
Ben Wagnerc3aef182017-06-26 12:47:33 -0400420 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid);
bungeman401ae2d2016-07-18 15:46:27 -0700421 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000422};
423
424///////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +0000425
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000426static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000427 FT_UShort fsType = FT_Get_FSType_Flags(face);
428 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
429 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000430}
431
vandebo0f9bad02014-06-19 11:05:39 -0700432static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700433 FT_UShort fsType = FT_Get_FSType_Flags(face);
434 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700435}
436
Hal Canary5bdc4d52018-04-10 11:13:24 -0400437static SkAdvancedTypefaceMetrics::FontType get_font_type(FT_Face face) {
438 const char* fontType = FT_Get_X11_Font_Format(face);
439 static struct { const char* s; SkAdvancedTypefaceMetrics::FontType t; } values[] = {
440 { "Type 1", SkAdvancedTypefaceMetrics::kType1_Font },
441 { "CID Type 1", SkAdvancedTypefaceMetrics::kType1CID_Font },
442 { "CFF", SkAdvancedTypefaceMetrics::kCFF_Font },
443 { "TrueType", SkAdvancedTypefaceMetrics::kTrueType_Font },
444 };
445 for(const auto& v : values) { if (strcmp(fontType, v.s) == 0) { return v.t; } }
446 return SkAdvancedTypefaceMetrics::kOther_Font;
447}
448
Hal Canary209e4b12017-05-04 14:23:55 -0400449std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_FreeType::onGetAdvancedMetrics() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000450 AutoFTAccess fta(this);
451 FT_Face face = fta.face();
452 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700453 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000454 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000455
Hal Canary209e4b12017-05-04 14:23:55 -0400456 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
Hal Canary8031b322018-03-29 13:20:30 -0700457 info->fPostScriptName.set(FT_Get_Postscript_Name(face));
458 info->fFontName = info->fPostScriptName;
halcanary32875882016-08-16 09:36:23 -0700459
vandebo0f9bad02014-06-19 11:05:39 -0700460 if (FT_HAS_MULTIPLE_MASTERS(face)) {
Ben Wagner997c9072020-08-04 13:36:52 -0400461 info->fFlags |= SkAdvancedTypefaceMetrics::kVariable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700462 }
463 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700464 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700465 }
466 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700467 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700468 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000469
Hal Canary5bdc4d52018-04-10 11:13:24 -0400470 info->fType = get_font_type(face);
halcanary32875882016-08-16 09:36:23 -0700471 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700472 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000473 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700474 }
475 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000476 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700477 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000478
bungemanf1491692016-07-22 11:19:24 -0700479 PS_FontInfoRec psFontInfo;
480 TT_Postscript* postTable;
481 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
482 info->fItalicAngle = psFontInfo.italic_angle;
483 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
Ben Wagner4f6fc832017-09-15 16:00:40 -0400484 info->fItalicAngle = SkFixedFloorToInt(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000485 } else {
486 info->fItalicAngle = 0;
487 }
488
489 info->fAscent = face->ascender;
490 info->fDescent = face->descender;
491
bungemanf1491692016-07-22 11:19:24 -0700492 TT_PCLT* pcltTable;
493 TT_OS2* os2Table;
494 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
495 info->fCapHeight = pcltTable->CapHeight;
496 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
497 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000498 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700499 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000500 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700501 }
502 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000503 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700504 os2Table->version != 0xFFFF &&
505 os2Table->version >= 2)
506 {
507 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000508 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000509 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
510 face->bbox.xMax, face->bbox.yMin);
Greg Daniel97c11082018-05-09 15:35:54 +0000511 return info;
Hal Canary1c2bcd82018-04-10 11:27:48 -0400512}
513
Hal Canary46cc3da2018-05-09 11:50:34 -0400514void SkTypeface_FreeType::getGlyphToUnicodeMap(SkUnichar* dstArray) const {
Hal Canary46cc3da2018-05-09 11:50:34 -0400515 AutoFTAccess fta(this);
516 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -0400517 if (!face) {
518 return;
519 }
520
Hal Canary46cc3da2018-05-09 11:50:34 -0400521 FT_Long numGlyphs = face->num_glyphs;
Ben Wagner6669b012020-07-08 11:58:18 -0400522 if (!dstArray) { SkASSERT(numGlyphs == 0); }
Hal Canary46cc3da2018-05-09 11:50:34 -0400523 sk_bzero(dstArray, sizeof(SkUnichar) * numGlyphs);
524
525 FT_UInt glyphIndex;
526 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
527 while (glyphIndex) {
528 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
529 // Use the first character that maps to this glyphID. https://crbug.com/359065
530 if (0 == dstArray[glyphIndex]) {
531 dstArray[glyphIndex] = charCode;
532 }
533 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
534 }
535}
536
Hal Canary5bdc4d52018-04-10 11:13:24 -0400537void SkTypeface_FreeType::getPostScriptGlyphNames(SkString* dstArray) const {
Hal Canary5bdc4d52018-04-10 11:13:24 -0400538 AutoFTAccess fta(this);
539 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -0400540 if (!face) {
541 return;
542 }
543
544 FT_Long numGlyphs = face->num_glyphs;
545 if (!dstArray) { SkASSERT(numGlyphs == 0); }
546
547 if (FT_HAS_GLYPH_NAMES(face)) {
548 for (int gID = 0; gID < numGlyphs; ++gID) {
Hal Canary5bdc4d52018-04-10 11:13:24 -0400549 char glyphName[128]; // PS limit for names is 127 bytes.
550 FT_Get_Glyph_Name(face, gID, glyphName, 128);
551 dstArray[gID] = glyphName;
552 }
553 }
554}
555
Ben Wagner59637dd2020-10-05 18:25:03 -0400556bool SkTypeface_FreeType::onGetPostScriptName(SkString* skPostScriptName) const {
557 AutoFTAccess fta(this);
558 FT_Face face = fta.face();
559 if (!face) {
560 return false;
561 }
562
563 const char* ftPostScriptName = FT_Get_Postscript_Name(face);
564 if (!ftPostScriptName) {
565 return false;
566 }
567 if (skPostScriptName) {
568 *skPostScriptName = ftPostScriptName;
569 }
570 return true;
571}
572
reed@google.com618ef5e2011-01-26 22:10:41 +0000573///////////////////////////////////////////////////////////////////////////
574
reed@google.com8ed436c2011-07-21 14:12:36 +0000575static bool bothZero(SkScalar a, SkScalar b) {
576 return 0 == a && 0 == b;
577}
578
579// returns false if there is any non-90-rotation or skew
Ben Wagner3e45a2f2017-11-01 11:47:39 -0400580static bool isAxisAligned(const SkScalerContextRec& rec) {
reed@google.com8ed436c2011-07-21 14:12:36 +0000581 return 0 == rec.fPreSkewX &&
582 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
583 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
584}
585
Ben Wagnerf73a0292020-12-22 14:16:16 -0500586std::unique_ptr<SkScalerContext> SkTypeface_FreeType::onCreateScalerContext(
587 const SkScalerContextEffects& effects, const SkDescriptor* desc) const
588{
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500589 auto c = std::make_unique<SkScalerContext_FreeType>(
bungeman7cfd46a2016-10-20 16:06:52 -0400590 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
Ben Wagnerf73a0292020-12-22 14:16:16 -0500591 if (c->success()) {
592 return std::move(c);
reed@google.com0da48612013-03-19 16:06:52 +0000593 }
Ben Wagnerf73a0292020-12-22 14:16:16 -0500594 return SkScalerContext::MakeEmpty(
595 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000596}
597
Ben Wagner2478c702021-02-14 17:25:35 -0500598/** Copy the design variation coordinates into 'coordinates'.
599 *
600 * @param coordinates the buffer into which to write the design variation coordinates.
601 * @param coordinateCount the number of entries available through 'coordinates'.
602 *
603 * @return The number of axes, or -1 if there is an error.
604 * If 'coordinates != nullptr' and 'coordinateCount >= numAxes' then 'coordinates' will be
605 * filled with the variation coordinates describing the position of this typeface in design
606 * variation space. It is possible the number of axes can be retrieved but actual position
607 * cannot.
608 */
609static int GetVariationDesignPosition(AutoFTAccess& fta,
610 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount)
611{
612 FT_Face face = fta.face();
613 if (!face) {
614 return -1;
615 }
616
617 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
618 return 0;
619 }
620
621 FT_MM_Var* variations = nullptr;
622 if (FT_Get_MM_Var(face, &variations)) {
623 return -1;
624 }
625 SkAutoFree autoFreeVariations(variations);
626
627 if (!coordinates || coordinateCount < SkToInt(variations->num_axis)) {
628 return variations->num_axis;
629 }
630
631 SkAutoSTMalloc<4, FT_Fixed> coords(variations->num_axis);
Ben Wagner12745c82021-07-19 11:03:45 -0400632 if (FT_Get_Var_Design_Coordinates(face, variations->num_axis, coords.get())) {
Ben Wagner2478c702021-02-14 17:25:35 -0500633 return -1;
Ben Wagner12745c82021-07-19 11:03:45 -0400634 }
635 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
636 coordinates[i].axis = variations->axis[i].tag;
637 coordinates[i].value = SkFixedToScalar(coords[i]);
Ben Wagner2478c702021-02-14 17:25:35 -0500638 }
639
640 return variations->num_axis;
641}
642
Ben Wagner9d5c55c2020-06-27 12:52:14 -0400643std::unique_ptr<SkFontData> SkTypeface_FreeType::cloneFontData(const SkFontArguments& args) const {
Bruce Wangebf0cf52018-06-18 14:04:19 -0400644 AutoFTAccess fta(this);
645 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -0400646 if (!face) {
647 return nullptr;
648 }
Bruce Wangebf0cf52018-06-18 14:04:19 -0400649
Ben Wagner6669b012020-07-08 11:58:18 -0400650 Scanner::AxisDefinitions axisDefinitions;
Bruce Wangebf0cf52018-06-18 14:04:19 -0400651 if (!Scanner::GetAxes(face, &axisDefinitions)) {
652 return nullptr;
653 }
Ben Wagner2478c702021-02-14 17:25:35 -0500654 int axisCount = axisDefinitions.count();
655
656 SkAutoSTMalloc<4, SkFontArguments::VariationPosition::Coordinate> currentPosition(axisCount);
657 int currentAxisCount = GetVariationDesignPosition(fta, currentPosition, axisCount);
Ben Wagner6669b012020-07-08 11:58:18 -0400658
659 SkString name;
Ben Wagner2478c702021-02-14 17:25:35 -0500660 SkAutoSTMalloc<4, SkFixed> axisValues(axisCount);
661 Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(), axisValues, name,
662 currentAxisCount == axisCount ? currentPosition.get() : nullptr);
Bruce Wangebf0cf52018-06-18 14:04:19 -0400663 int ttcIndex;
Ben Wagnerff84d8a2019-02-26 15:39:41 -0500664 std::unique_ptr<SkStreamAsset> stream = this->openStream(&ttcIndex);
Ben Wagner2478c702021-02-14 17:25:35 -0500665 return std::make_unique<SkFontData>(std::move(stream), ttcIndex, axisValues.get(), axisCount);
Bruce Wangebf0cf52018-06-18 14:04:19 -0400666}
667
reed@google.com0da48612013-03-19 16:06:52 +0000668void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000669 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
670 //Cap the requested size as larger sizes give bogus values.
671 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800672 //Note that this also currently only protects against large text size requests,
673 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000674 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000675 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000676 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000677
Mike Reed04346d52018-11-05 12:45:32 -0500678 SkFontHinting h = rec->getHinting();
Ben Wagner5785e4a2019-05-07 16:50:29 -0400679 if (SkFontHinting::kFull == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000680 // collapse full->normal hinting if we're not doing LCD
Ben Wagner5785e4a2019-05-07 16:50:29 -0400681 h = SkFontHinting::kNormal;
reed@google.com618ef5e2011-01-26 22:10:41 +0000682 }
reed@google.com1ac83502012-02-28 17:06:02 +0000683
reed@google.com8ed436c2011-07-21 14:12:36 +0000684 // rotated text looks bad with hinting, so we disable it as needed
685 if (!isAxisAligned(*rec)) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400686 h = SkFontHinting::kNone;
reed@google.com8ed436c2011-07-21 14:12:36 +0000687 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000688 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000689
bungeman@google.com97efada2012-07-30 20:40:50 +0000690#ifndef SK_GAMMA_APPLY_TO_A8
691 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700692 // SRGBTODO: Is this correct? Do we want contrast boost?
693 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000694 }
reed@google.com1ac83502012-02-28 17:06:02 +0000695#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000696}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000697
Ben Wagner26a005a2018-08-31 17:41:45 -0400698int SkTypeface_FreeType::GetUnitsPerEm(FT_Face face) {
Ben Wagner6669b012020-07-08 11:58:18 -0400699 SkASSERT(face);
Ben Wagner26a005a2018-08-31 17:41:45 -0400700
701 SkScalar upem = SkIntToScalar(face->units_per_EM);
702 // At least some versions of FreeType set face->units_per_EM to 0 for bitmap only fonts.
703 if (upem == 0) {
704 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
705 if (ttHeader) {
706 upem = SkIntToScalar(ttHeader->Units_Per_EM);
707 }
708 }
709 return upem;
710}
711
reed@google.com38c37dd2013-03-21 15:36:26 +0000712int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000713 AutoFTAccess fta(this);
714 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -0400715 if (!face) {
716 return 0;
717 }
Ben Wagner26a005a2018-08-31 17:41:45 -0400718 return GetUnitsPerEm(face);
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000719}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000720
reed@google.com35fe7372013-10-30 15:07:03 +0000721bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
722 int count, int32_t adjustments[]) const {
723 AutoFTAccess fta(this);
724 FT_Face face = fta.face();
725 if (!face || !FT_HAS_KERNING(face)) {
726 return false;
727 }
728
729 for (int i = 0; i < count - 1; ++i) {
730 FT_Vector delta;
731 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
732 FT_KERNING_UNSCALED, &delta);
733 if (err) {
734 return false;
735 }
736 adjustments[i] = delta.x;
737 }
738 return true;
739}
740
bungeman401ae2d2016-07-18 15:46:27 -0700741/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800742static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700743 if (face == nullptr) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500744 LOG_INFO("chooseBitmapStrike aborted due to nullptr face.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000745 return -1;
746 }
bungeman401ae2d2016-07-18 15:46:27 -0700747
748 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000749 FT_Int chosenStrikeIndex = -1;
750 FT_Pos chosenPPEM = 0;
751 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700752 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
753 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000754 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700755 return strikeIndex;
756 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000757 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700758 if (chosenPPEM < strikePPEM) {
759 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000760 chosenStrikeIndex = strikeIndex;
761 }
762 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700763 // attempt to decrease chosenPPEM, but not below requestedPPEM
764 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
765 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000766 chosenStrikeIndex = strikeIndex;
767 }
768 }
769 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000770 return chosenStrikeIndex;
771}
772
Ben Wagner9d5c55c2020-06-27 12:52:14 -0400773SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface_FreeType> typeface,
reeda9322c22016-04-12 06:47:05 -0700774 const SkScalerContextEffects& effects,
775 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400776 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800777 , fFace(nullptr)
778 , fFTSize(nullptr)
779 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700780{
Herb Derby9c71e7b2019-06-17 14:40:42 -0400781 SkAutoMutexExclusive ac(f_t_mutex());
Ben Wagner2c7c36a2021-06-22 17:43:27 -0400782 fFaceRec = static_cast<SkTypeface_FreeType*>(this->getTypeface())->getFaceRec();
Ben Wagnerfc497342017-02-24 11:15:26 -0500783
reed@android.com8a1c16f2008-12-17 15:59:43 +0000784 // load the font file
Ben Wagnerfc497342017-02-24 11:15:26 -0500785 if (nullptr == fFaceRec) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500786 LOG_INFO("Could not create FT_Face.\n");
reed@android.com62900b42009-02-11 15:07:19 +0000787 return;
788 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000789
reed@google.coma1bfa212012-03-08 21:57:12 +0000790 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
791
reed@android.com8a1c16f2008-12-17 15:59:43 +0000792 // compute the flags we send to Load_Glyph
Ben Wagnerf460eee2019-04-18 16:37:45 -0400793 bool linearMetrics = this->isLinearMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000794 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000795 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000796
agl@chromium.org70a303f2010-05-10 14:15:50 +0000797 if (SkMask::kBW_Format == fRec.fMaskFormat) {
798 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
799 loadFlags = FT_LOAD_TARGET_MONO;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400800 if (fRec.getHinting() == SkFontHinting::kNone) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000801 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000802 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000803 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000804 } else {
805 switch (fRec.getHinting()) {
Ben Wagner5785e4a2019-05-07 16:50:29 -0400806 case SkFontHinting::kNone:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000807 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000808 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000809 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400810 case SkFontHinting::kSlight:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000811 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
Ben Wagner12745c82021-07-19 11:03:45 -0400812 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000813 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400814 case SkFontHinting::kNormal:
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400815 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000816 break;
Ben Wagner5785e4a2019-05-07 16:50:29 -0400817 case SkFontHinting::kFull:
agl@chromium.org70a303f2010-05-10 14:15:50 +0000818 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000819 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000820 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000821 loadFlags = FT_LOAD_TARGET_LCD_V;
822 } else {
823 loadFlags = FT_LOAD_TARGET_LCD;
824 }
reed@google.comea2333d2011-03-14 16:44:56 +0000825 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000826 break;
827 default:
Mike Klein3e0141a2019-03-26 10:41:18 -0500828 LOG_INFO("---------- UNKNOWN hinting %d\n", fRec.getHinting());
agl@chromium.org70a303f2010-05-10 14:15:50 +0000829 break;
830 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000831 }
832
Ben Wagnerd34b8a82018-06-07 15:02:18 -0400833 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
834 loadFlags |= FT_LOAD_FORCE_AUTOHINT;
835#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
836 } else {
837 loadFlags |= FT_LOAD_NO_AUTOHINT;
838#endif
839 }
840
reed@google.comeffc5012011-06-27 16:44:46 +0000841 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000842 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000843 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000844
reed@google.com96a9f7912011-05-06 11:49:30 +0000845 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
846 // advances, as fontconfig and cairo do.
847 // See http://code.google.com/p/skia/issues/detail?id=222.
848 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
849
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000850 // Use vertical layout if requested.
Ben Wagneraa166bd2018-08-14 14:58:18 -0400851 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000852 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
853 }
854
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000855 loadFlags |= FT_LOAD_COLOR;
856
reed@android.come4d0bc02009-07-24 19:53:20 +0000857 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000858 }
859
Ben Wagner723a8772019-08-16 11:36:58 -0400860 using DoneFTSize = SkFunctionWrapper<decltype(FT_Done_Size), FT_Done_Size>;
Mike Kleindc976a92020-04-30 06:45:25 -0500861 std::unique_ptr<std::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([this]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800862 FT_Size size;
Ben Wagnerfc497342017-02-24 11:15:26 -0500863 FT_Error err = FT_New_Size(fFaceRec->fFace.get(), &size);
bungemanaabd71c2016-03-01 15:15:09 -0800864 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500865 SK_TRACEFTR(err, "FT_New_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800866 return nullptr;
867 }
868 return size;
869 }());
870 if (nullptr == ftSize) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500871 LOG_INFO("Could not create FT_Size.\n");
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000872 return;
873 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000874
bungemanaabd71c2016-03-01 15:15:09 -0800875 FT_Error err = FT_Activate_Size(ftSize.get());
876 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500877 SK_TRACEFTR(err, "FT_Activate_Size(%s) failed.", fFaceRec->fFace->family_name);
bungemanaabd71c2016-03-01 15:15:09 -0800878 return;
879 }
880
Ben Wagner082a7a72018-06-08 14:15:47 -0400881 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
882 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
883 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
884
Ben Wagnerfc497342017-02-24 11:15:26 -0500885 if (FT_IS_SCALABLE(fFaceRec->fFace)) {
886 err = FT_Set_Char_Size(fFaceRec->fFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000887 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500888 SK_TRACEFTR(err, "FT_Set_CharSize(%s, %f, %f) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400889 fFaceRec->fFace->family_name, fScale.fX, fScale.fY);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000890 return;
891 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400892
Ben Wagner082a7a72018-06-08 14:15:47 -0400893 // Adjust the matrix to reflect the actually chosen scale.
894 // FreeType currently does not allow requesting sizes less than 1, this allow for scaling.
895 // Don't do this at all sizes as that will interfere with hinting.
896 if (fScale.fX < 1 || fScale.fY < 1) {
897 SkScalar upem = fFaceRec->fFace->units_per_EM;
898 FT_Size_Metrics& ftmetrics = fFaceRec->fFace->size->metrics;
899 SkScalar x_ppem = upem * SkFT_FixedToScalar(ftmetrics.x_scale) / 64.0f;
900 SkScalar y_ppem = upem * SkFT_FixedToScalar(ftmetrics.y_scale) / 64.0f;
901 fMatrix22Scalar.preScale(fScale.x() / x_ppem, fScale.y() / y_ppem);
902 }
Ben Wagner082a7a72018-06-08 14:15:47 -0400903
Ben Wagnerfc497342017-02-24 11:15:26 -0500904 } else if (FT_HAS_FIXED_SIZES(fFaceRec->fFace)) {
905 fStrikeIndex = chooseBitmapStrike(fFaceRec->fFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000906 if (fStrikeIndex == -1) {
Mike Klein3e0141a2019-03-26 10:41:18 -0500907 LOG_INFO("No glyphs for font \"%s\" size %f.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -0400908 fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700909 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000910 }
bungeman401ae2d2016-07-18 15:46:27 -0700911
Ben Wagnerfc497342017-02-24 11:15:26 -0500912 err = FT_Select_Size(fFaceRec->fFace.get(), fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700913 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -0500914 SK_TRACEFTR(err, "FT_Select_Size(%s, %d) failed.",
Ben Wagner082a7a72018-06-08 14:15:47 -0400915 fFaceRec->fFace->family_name, fStrikeIndex);
bungeman401ae2d2016-07-18 15:46:27 -0700916 fStrikeIndex = -1;
917 return;
918 }
919
Ben Wagner082a7a72018-06-08 14:15:47 -0400920 // Adjust the matrix to reflect the actually chosen scale.
921 // It is likely that the ppem chosen was not the one requested, this allows for scaling.
Ben Wagnerfc497342017-02-24 11:15:26 -0500922 fMatrix22Scalar.preScale(fScale.x() / fFaceRec->fFace->size->metrics.x_ppem,
923 fScale.y() / fFaceRec->fFace->size->metrics.y_ppem);
bungeman401ae2d2016-07-18 15:46:27 -0700924
925 // FreeType does not provide linear metrics for bitmap fonts.
926 linearMetrics = false;
927
928 // FreeType documentation says:
929 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
930 // Bitmap-only fonts ignore this flag.
931 //
932 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
933 // Force this flag off for bitmap only fonts.
934 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000935 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -0500936 LOG_INFO("Unknown kind of font \"%s\" size %f.\n", fFaceRec->fFace->family_name, fScale.fY);
bungeman401ae2d2016-07-18 15:46:27 -0700937 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000938 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000939
Ben Wagner082a7a72018-06-08 14:15:47 -0400940 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
941 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
942 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
943 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
944
Bruce Wangf3ca1c62018-07-09 10:08:36 -0400945#ifdef FT_COLOR_H
946 FT_Palette_Select(fFaceRec->fFace.get(), 0, nullptr);
947#endif
948
bungemanaabd71c2016-03-01 15:15:09 -0800949 fFTSize = ftSize.release();
Ben Wagnerfc497342017-02-24 11:15:26 -0500950 fFace = fFaceRec->fFace.get();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000951 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000952}
953
954SkScalerContext_FreeType::~SkScalerContext_FreeType() {
Herb Derby9c71e7b2019-06-17 14:40:42 -0400955 SkAutoMutexExclusive ac(f_t_mutex());
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000956
halcanary96fcdcc2015-08-27 07:41:13 -0700957 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000958 FT_Done_Size(fFTSize);
959 }
960
Ben Wagnerfc497342017-02-24 11:15:26 -0500961 fFaceRec = nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000962}
963
964/* We call this before each use of the fFace, since we may be sharing
965 this face with other context (at different sizes).
966*/
967FT_Error SkScalerContext_FreeType::setupSize() {
Herb Derby9c71e7b2019-06-17 14:40:42 -0400968 f_t_mutex().assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000969 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000970 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000971 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000972 }
halcanary96fcdcc2015-08-27 07:41:13 -0700973 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000974 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000975}
976
Ben Wagnere5416452018-08-09 14:03:42 -0400977bool SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000978 /* unhinted and light hinted text have linearly scaled advances
979 * which are very cheap to compute with some font formats...
980 */
Ben Wagnere5416452018-08-09 14:03:42 -0400981 if (!fDoLinearMetrics) {
982 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983 }
bungeman5ec443c2014-11-21 13:18:34 -0800984
Herb Derby9c71e7b2019-06-17 14:40:42 -0400985 SkAutoMutexExclusive ac(f_t_mutex());
Ben Wagnere5416452018-08-09 14:03:42 -0400986
987 if (this->setupSize()) {
988 glyph->zeroMetrics();
989 return true;
990 }
991
992 FT_Error error;
993 FT_Fixed advance;
994
995 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
996 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
997 &advance );
998
999 if (error != 0) {
1000 return false;
1001 }
1002
1003 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1004 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
1005 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
1006 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001007}
1008
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001009void SkScalerContext_FreeType::getBBoxForCurrentGlyph(const SkGlyph* glyph,
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001010 FT_BBox* bbox,
1011 bool snapToPixelBoundary) {
1012
1013 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1014
Ben Wagneraa166bd2018-08-14 14:58:18 -04001015 if (this->isSubpixel()) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001016 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1017 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001018 // negate dy since freetype-y-goes-up and skia-y-goes-down
1019 bbox->xMin += dx;
1020 bbox->yMin -= dy;
1021 bbox->xMax += dx;
1022 bbox->yMax -= dy;
1023 }
1024
1025 // outset the box to integral boundaries
1026 if (snapToPixelBoundary) {
1027 bbox->xMin &= ~63;
1028 bbox->yMin &= ~63;
1029 bbox->xMax = (bbox->xMax + 63) & ~63;
1030 bbox->yMax = (bbox->yMax + 63) & ~63;
1031 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001032
1033 // Must come after snapToPixelBoundary so that the width and height are
1034 // consistent. Otherwise asserts will fire later on when generating the
1035 // glyph image.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001036 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001037 FT_Vector vector;
1038 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1039 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1040 FT_Vector_Transform(&vector, &fMatrix22);
1041 bbox->xMin += vector.x;
1042 bbox->xMax += vector.x;
1043 bbox->yMin += vector.y;
1044 bbox->yMax += vector.y;
1045 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001046}
1047
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001048bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1049 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001050 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001051 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001052 }
1053 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001054 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001055 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001056 emboldenIfNeeded(fFace, fFace->glyph, SkTo<SkGlyphID>(glyph_id));
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001057 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1058 return true;
1059}
1060
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001061void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
Ben Wagnere5416452018-08-09 14:03:42 -04001062 if (glyph->fMaskFormat == SkMask::kLCD16_Format) {
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001063 if (fLCDIsVert) {
Ben Wagner12745c82021-07-19 11:03:45 -04001064 glyph->fHeight += 2;
1065 glyph->fTop -= 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001066 } else {
Ben Wagner12745c82021-07-19 11:03:45 -04001067 glyph->fWidth += 2;
1068 glyph->fLeft -= 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001069 }
1070 }
1071}
1072
bungeman401ae2d2016-07-18 15:46:27 -07001073bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1074 // If subpixel rendering of a bitmap *can* be done.
1075 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
Ben Wagneraa166bd2018-08-14 14:58:18 -04001076 this->isSubpixel() &&
bungeman401ae2d2016-07-18 15:46:27 -07001077 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001078
bungeman401ae2d2016-07-18 15:46:27 -07001079 // If subpixel rendering of a bitmap *should* be done.
1080 // 1. If the face is not scalable then always allow subpixel rendering.
1081 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1082 // 2. If the matrix is already not identity the bitmap will already be resampled,
1083 // so resampling slightly differently shouldn't make much difference.
1084 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1085
1086 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001087}
1088
Ben Wagner66899512021-12-01 17:27:08 -05001089void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph, SkArenaAlloc* alloc) {
Herb Derby9c71e7b2019-06-17 14:40:42 -04001090 SkAutoMutexExclusive ac(f_t_mutex());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001091
reed@android.com8a1c16f2008-12-17 15:59:43 +00001092 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001093 glyph->zeroMetrics();
1094 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001095 }
1096
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001097 FT_Error err;
Seigo Nonaka52ab2f52016-12-05 02:41:53 +09001098 err = FT_Load_Glyph( fFace, glyph->getGlyphID(),
1099 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001100 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001101 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001102 return;
1103 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001104 emboldenIfNeeded(fFace, fFace->glyph, glyph->getGlyphID());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001105
Ben Wagner094b3ea2018-09-06 18:09:29 -04001106 if (fFace->glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
1107 using FT_PosLimits = std::numeric_limits<FT_Pos>;
1108 FT_BBox bounds = { FT_PosLimits::max(), FT_PosLimits::max(),
1109 FT_PosLimits::min(), FT_PosLimits::min() };
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001110#ifdef FT_COLOR_H
Ben Wagner094b3ea2018-09-06 18:09:29 -04001111 FT_Bool haveLayers = false;
1112 FT_LayerIterator layerIterator = { 0, 0, nullptr };
1113 FT_UInt layerGlyphIndex;
1114 FT_UInt layerColorIndex;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001115
Dominik Röttsches691a7942021-02-11 21:08:44 +02001116#ifdef TT_SUPPORT_COLRV1
1117 FT_OpaquePaint opaqueLayerPaint;
1118 opaqueLayerPaint.p = nullptr;
1119 if (FT_Get_Color_Glyph_Paint(fFace, glyph->getGlyphID(),
1120 FT_COLOR_INCLUDE_ROOT_TRANSFORM, &opaqueLayerPaint)) {
Dominik Röttsches2fa273e2021-08-10 12:10:45 +03001121 haveLayers = true;
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001122
Dominik Röttsches2fa273e2021-08-10 12:10:45 +03001123 FT_ClipBox colrGlyphBbox;
Dominik Röttsches691a7942021-02-11 21:08:44 +02001124
Dominik Röttsches2fa273e2021-08-10 12:10:45 +03001125 // COLRv1 optionally provides a ClipBox that we can use for allocation.
1126 if (FT_Get_Color_Glyph_ClipBox(fFace, glyph->getGlyphID(), &colrGlyphBbox)) {
1127 // Find enclosing bounding box of clip box corner points, needed
1128 // when clipbox is transformed.
1129 bounds.xMin = colrGlyphBbox.bottom_left.x;
1130 bounds.xMax = colrGlyphBbox.bottom_left.x;
1131 bounds.yMin = colrGlyphBbox.bottom_left.y;
1132 bounds.yMax = colrGlyphBbox.bottom_left.y;
Dominik Röttsches691a7942021-02-11 21:08:44 +02001133
Dominik Röttsches2fa273e2021-08-10 12:10:45 +03001134 for (auto& corner : {colrGlyphBbox.top_left,
1135 colrGlyphBbox.top_right,
1136 colrGlyphBbox.bottom_right}) {
1137 if (corner.x < bounds.xMin) {
1138 bounds.xMin = corner.x;
1139 }
1140 if (corner.y < bounds.yMin) {
1141 bounds.yMin = corner.y;
1142 }
1143 if (corner.x > bounds.xMax) {
1144 bounds.xMax = corner.x;
1145 }
1146 if (corner.y > bounds.yMax) {
1147 bounds.yMax = corner.y;
1148 }
1149 }
1150 } else {
1151 // Otherwise we need to traverse the glyph graph with a focus on measuring the
1152 // required bounding box.
1153 FT_BBox computed_bounds;
1154 if (!computeColrV1GlyphBoundingBox(fFace, glyph->getGlyphID(), &computed_bounds)) {
1155 glyph->zeroMetrics();
1156 return;
1157 }
1158
1159 // Reset face so the main glyph slot contains information about the
1160 // base glyph again, for usage for computing and copying horizontal
1161 // metrics from FreeType to Skia below.
1162 if (this->setupSize()) {
1163 glyph->zeroMetrics();
1164 return;
1165 }
1166
Dominik Röttsches2fa273e2021-08-10 12:10:45 +03001167 err = FT_Load_Glyph(
1168 fFace, glyph->getGlyphID(), fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
1169 if (err != 0) {
1170 glyph->zeroMetrics();
1171 return;
1172 }
1173
1174 bounds = computed_bounds;
Dominik Röttsches691a7942021-02-11 21:08:44 +02001175 }
Dominik Röttsches691a7942021-02-11 21:08:44 +02001176 }
1177#endif // #TT_SUPPORT_COLRV1
1178
1179 if (!haveLayers) {
1180 // For COLRv0 compute the glyph bounding box from the union of layer bounding boxes.
1181 while (FT_Get_Color_Glyph_Layer(fFace, glyph->getGlyphID(), &layerGlyphIndex,
1182 &layerColorIndex, &layerIterator)) {
1183 haveLayers = true;
1184 err = FT_Load_Glyph(fFace, layerGlyphIndex,
1185 fLoadGlyphFlags | FT_LOAD_BITMAP_METRICS_ONLY);
1186 if (err != 0) {
1187 glyph->zeroMetrics();
1188 return;
1189 }
1190 emboldenIfNeeded(fFace, fFace->glyph, layerGlyphIndex);
1191
1192 if (0 < fFace->glyph->outline.n_contours) {
1193 FT_BBox bbox;
1194 getBBoxForCurrentGlyph(glyph, &bbox, true);
1195
1196 // Union
1197 bounds.xMin = std::min(bbox.xMin, bounds.xMin);
1198 bounds.yMin = std::min(bbox.yMin, bounds.yMin);
1199 bounds.xMax = std::max(bbox.xMax, bounds.xMax);
1200 bounds.yMax = std::max(bbox.yMax, bounds.yMax);
1201 }
Bruce Wangf3ca1c62018-07-09 10:08:36 -04001202 }
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001203 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001204
Ben Wagner094b3ea2018-09-06 18:09:29 -04001205 if (haveLayers) {
1206 glyph->fMaskFormat = SkMask::kARGB32_Format;
Ben Wagner66899512021-12-01 17:27:08 -05001207#ifndef SK_IGNORE_GLYPH_HAS_PATH_FIX
1208 glyph->setPath(alloc, nullptr, false);
1209#endif
Ben Wagner094b3ea2018-09-06 18:09:29 -04001210 if (!(bounds.xMin < bounds.xMax && bounds.yMin < bounds.yMax)) {
1211 bounds = { 0, 0, 0, 0 };
1212 }
1213 } else {
1214#endif
1215 if (0 < fFace->glyph->outline.n_contours) {
1216 getBBoxForCurrentGlyph(glyph, &bounds, true);
1217 } else {
1218 bounds = { 0, 0, 0, 0 };
1219 }
1220#ifdef FT_COLOR_H
1221 }
1222#endif
1223 // Round out, no longer dot6.
1224 bounds.xMin = SkFDot6Floor(bounds.xMin);
1225 bounds.yMin = SkFDot6Floor(bounds.yMin);
1226 bounds.xMax = SkFDot6Ceil (bounds.xMax);
1227 bounds.yMax = SkFDot6Ceil (bounds.yMax);
1228
1229 FT_Pos width = bounds.xMax - bounds.xMin;
1230 FT_Pos height = bounds.yMax - bounds.yMin;
1231 FT_Pos top = -bounds.yMax; // Freetype y-up, Skia y-down.
1232 FT_Pos left = bounds.xMin;
1233 if (!SkTFitsIn<decltype(glyph->fWidth )>(width ) ||
1234 !SkTFitsIn<decltype(glyph->fHeight)>(height) ||
1235 !SkTFitsIn<decltype(glyph->fTop )>(top ) ||
1236 !SkTFitsIn<decltype(glyph->fLeft )>(left ) )
1237 {
1238 width = height = top = left = 0;
1239 }
1240
1241 glyph->fWidth = SkToU16(width );
1242 glyph->fHeight = SkToU16(height);
1243 glyph->fTop = SkToS16(top );
1244 glyph->fLeft = SkToS16(left );
1245 updateGlyphIfLCD(glyph);
1246
1247 } else if (fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP) {
Ben Wagneraa166bd2018-08-14 14:58:18 -04001248 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001249 FT_Vector vector;
1250 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1251 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1252 FT_Vector_Transform(&vector, &fMatrix22);
1253 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1254 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1255 }
1256
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001257 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1258 glyph->fMaskFormat = SkMask::kARGB32_Format;
1259 }
1260
bungeman401ae2d2016-07-18 15:46:27 -07001261 {
1262 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1263 -SkIntToScalar(fFace->glyph->bitmap_top),
1264 SkIntToScalar(fFace->glyph->bitmap.width),
1265 SkIntToScalar(fFace->glyph->bitmap.rows));
1266 fMatrix22Scalar.mapRect(&rect);
1267 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1268 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1269 SkFixedToScalar(glyph->getSubYFixed()));
1270 }
1271 SkIRect irect = rect.roundOut();
1272 glyph->fWidth = SkToU16(irect.width());
1273 glyph->fHeight = SkToU16(irect.height());
1274 glyph->fTop = SkToS16(irect.top());
1275 glyph->fLeft = SkToS16(irect.left());
1276 }
Ben Wagner094b3ea2018-09-06 18:09:29 -04001277 } else {
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001278 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001279 glyph->zeroMetrics();
1280 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001281 }
1282
Ben Wagneraa166bd2018-08-14 14:58:18 -04001283 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001284 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001285 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001286 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001287 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001288 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001289 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1290 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001291 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001292 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001293 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001294 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1295 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001296 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001297 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001298 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1299 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001300 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001301 }
1302
reed@android.com8a1c16f2008-12-17 15:59:43 +00001303#ifdef ENABLE_GLYPH_SPEW
Mike Klein3e0141a2019-03-26 10:41:18 -05001304 LOG_INFO("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001305#endif
1306}
1307
bungeman@google.coma76de722012-10-26 19:35:54 +00001308void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
Herb Derby9c71e7b2019-06-17 14:40:42 -04001309 SkAutoMutexExclusive ac(f_t_mutex());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001310
reed@android.com8a1c16f2008-12-17 15:59:43 +00001311 if (this->setupSize()) {
Herb Derby793818b2019-06-25 17:10:11 -04001312 sk_bzero(glyph.fImage, glyph.imageSize());
bungeman5ec443c2014-11-21 13:18:34 -08001313 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001314 }
1315
bungeman5ec443c2014-11-21 13:18:34 -08001316 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001317 if (err != 0) {
Hal Canary2bcd8432018-01-26 10:35:07 -05001318 SK_TRACEFTR(err, "SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d "
John Stiles7bf79992021-06-25 11:05:20 -04001319 "width:%d height:%d rb:%zu flags:%d) failed.",
Herb Derby793818b2019-06-25 17:10:11 -04001320 glyph.getGlyphID(), glyph.width(), glyph.height(), glyph.rowBytes(),
Hal Canary2bcd8432018-01-26 10:35:07 -05001321 fLoadGlyphFlags);
Herb Derby793818b2019-06-25 17:10:11 -04001322 sk_bzero(glyph.fImage, glyph.imageSize());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001323 return;
1324 }
1325
Ben Wagnerc3aef182017-06-26 12:47:33 -04001326 emboldenIfNeeded(fFace, fFace->glyph, glyph.getGlyphID());
bungeman401ae2d2016-07-18 15:46:27 -07001327 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1328 SkMatrix subpixelBitmapMatrix;
1329 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1330 subpixelBitmapMatrix = fMatrix22Scalar;
1331 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1332 SkFixedToScalar(glyph.getSubYFixed()));
1333 bitmapMatrix = &subpixelBitmapMatrix;
1334 }
1335 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001336}
1337
reed@android.com8a1c16f2008-12-17 15:59:43 +00001338
Ben Wagner66899512021-12-01 17:27:08 -05001339bool SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
caryclarka10742c2014-09-18 11:00:40 -07001340 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001341
Herb Derby9c71e7b2019-06-17 14:40:42 -04001342 SkAutoMutexExclusive ac(f_t_mutex());
Ben Wagner5ddb3082018-03-29 11:18:06 -04001343
Ben Wagner66899512021-12-01 17:27:08 -05001344 SkGlyphID glyphID = glyph.getGlyphID();
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001345 // FT_IS_SCALABLE is documented to mean the face contains outline glyphs.
1346 if (!FT_IS_SCALABLE(fFace) || this->setupSize()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001347 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001348 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001349 }
1350
1351 uint32_t flags = fLoadGlyphFlags;
1352 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1353 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1354
Ben Wagner6e9ac122016-11-11 14:31:06 -05001355 FT_Error err = FT_Load_Glyph(fFace, glyphID, flags);
Ben Wagnerd6931bb2018-09-18 14:38:32 -04001356 if (err != 0 || fFace->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001357 path->reset();
Ben Wagner5ddb3082018-03-29 11:18:06 -04001358 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001359 }
Ben Wagnerc3aef182017-06-26 12:47:33 -04001360 emboldenIfNeeded(fFace, fFace->glyph, glyphID);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001361
Ben Wagner5ddb3082018-03-29 11:18:06 -04001362 if (!generateGlyphPath(fFace, path)) {
1363 path->reset();
1364 return false;
1365 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001366
1367 // The path's origin from FreeType is always the horizontal layout origin.
1368 // Offset the path so that it is relative to the vertical origin if needed.
Ben Wagneraa166bd2018-08-14 14:58:18 -04001369 if (this->isVertical()) {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001370 FT_Vector vector;
1371 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1372 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1373 FT_Vector_Transform(&vector, &fMatrix22);
1374 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1375 }
Ben Wagner5ddb3082018-03-29 11:18:06 -04001376 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377}
1378
Mike Reedb5784ac2018-11-12 09:35:15 -05001379void SkScalerContext_FreeType::generateFontMetrics(SkFontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001380 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001381 return;
1382 }
1383
Herb Derby9c71e7b2019-06-17 14:40:42 -04001384 SkAutoMutexExclusive ac(f_t_mutex());
reed@android.com8a1c16f2008-12-17 15:59:43 +00001385
1386 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001387 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001388 return;
1389 }
1390
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001391 FT_Face face = fFace;
Ben Wagner219f3622017-07-17 15:32:25 -04001392 metrics->fFlags = 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001393
Ben Wagner26a005a2018-08-31 17:41:45 -04001394 SkScalar upem = SkIntToScalar(SkTypeface_FreeType::GetUnitsPerEm(face));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001395
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001396 // use the os/2 table as a source of reasonable defaults.
1397 SkScalar x_height = 0.0f;
1398 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001399 SkScalar cap_height = 0.0f;
Kevin Lubick42846132018-01-05 10:11:11 -05001400 SkScalar strikeoutThickness = 0.0f, strikeoutPosition = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001401 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1402 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001403 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001404 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
Ben Wagner219f3622017-07-17 15:32:25 -04001405 strikeoutThickness = SkIntToScalar(os2->yStrikeoutSize) / upem;
1406 strikeoutPosition = -SkIntToScalar(os2->yStrikeoutPosition) / upem;
Mike Reedb5784ac2018-11-12 09:35:15 -05001407 metrics->fFlags |= SkFontMetrics::kStrikeoutThicknessIsValid_Flag;
1408 metrics->fFlags |= SkFontMetrics::kStrikeoutPositionIsValid_Flag;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001409 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001410 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001411 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001412 }
1413
1414 // pull from format-specific metrics as needed
1415 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001416 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001417 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001418 // FreeType will always use HHEA metrics if they're not zero.
1419 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1420 // It also ignores the VDMX tables, which are also of interest here
1421 // (and override everything else when they apply).
1422 static const int kUseTypoMetricsMask = (1 << 7);
1423 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1424 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1425 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1426 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1427 } else {
1428 ascent = -SkIntToScalar(face->ascender) / upem;
1429 descent = -SkIntToScalar(face->descender) / upem;
1430 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1431 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001432 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1433 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1434 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1435 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001436 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001437 underlinePosition = -SkIntToScalar(face->underline_position +
1438 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001439
Mike Reedb5784ac2018-11-12 09:35:15 -05001440 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1441 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
bungeman41078062014-07-07 08:16:37 -07001442
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001443 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001444 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001445 FT_BBox bbox;
1446 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001447 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1448 }
1449 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001450 if (!cap_height) {
1451 FT_BBox bbox;
1452 if (getCBoxForLetter('H', &bbox)) {
1453 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1454 }
1455 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001456 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1457 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1458 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1459 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1460 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001461 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
Ben Wagner457cad12020-09-10 13:42:30 -04001462
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001463 xmin = 0.0f;
1464 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001465 ymin = descent;
1466 ymax = ascent;
Ben Wagner457cad12020-09-10 13:42:30 -04001467 // The actual bitmaps may be any size and placed at any offset.
1468 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1469
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001470 underlineThickness = 0;
1471 underlinePosition = 0;
Mike Reedb5784ac2018-11-12 09:35:15 -05001472 metrics->fFlags &= ~SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1473 metrics->fFlags &= ~SkFontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001474
1475 TT_Postscript* post = (TT_Postscript*) FT_Get_Sfnt_Table(face, ft_sfnt_post);
1476 if (post) {
1477 underlineThickness = SkIntToScalar(post->underlineThickness) / upem;
1478 underlinePosition = -SkIntToScalar(post->underlinePosition) / upem;
Mike Reedb5784ac2018-11-12 09:35:15 -05001479 metrics->fFlags |= SkFontMetrics::kUnderlineThicknessIsValid_Flag;
1480 metrics->fFlags |= SkFontMetrics::kUnderlinePositionIsValid_Flag;
Ben Wagner5423f1f2018-02-20 09:57:58 -05001481 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001482 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001483 sk_bzero(metrics, sizeof(*metrics));
1484 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001485 }
1486
1487 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1488 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001489 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001490 }
1491 if (!avgCharWidth) {
1492 avgCharWidth = xmax - xmin;
1493 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001494 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001495 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001496 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001497
1498 // disallow negative linespacing
1499 if (leading < 0.0f) {
1500 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001501 }
1502
bungeman53790512016-07-21 13:32:09 -07001503 metrics->fTop = ymax * fScale.y();
1504 metrics->fAscent = ascent * fScale.y();
1505 metrics->fDescent = descent * fScale.y();
1506 metrics->fBottom = ymin * fScale.y();
1507 metrics->fLeading = leading * fScale.y();
1508 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1509 metrics->fXMin = xmin * fScale.y();
1510 metrics->fXMax = xmax * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001511 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
bungeman7316b102014-10-29 12:46:52 -07001512 metrics->fXHeight = x_height;
1513 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001514 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1515 metrics->fUnderlinePosition = underlinePosition * fScale.y();
Ben Wagner219f3622017-07-17 15:32:25 -04001516 metrics->fStrikeoutThickness = strikeoutThickness * fScale.y();
1517 metrics->fStrikeoutPosition = strikeoutPosition * fScale.y();
Ben Wagnerfcfd0af2020-07-09 10:51:27 -04001518
1519 if (face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
1520 // The bounds are only valid for the default variation.
1521 metrics->fFlags |= SkFontMetrics::kBoundsInvalid_Flag;
1522 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001523}
1524
djsollenfcfea992015-01-09 08:18:13 -08001525///////////////////////////////////////////////////////////////////////////////
1526
1527// hand-tuned value to reduce outline embolden strength
1528#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1529 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1530 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1531 #else
1532 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1533 #endif
1534#endif
1535
1536///////////////////////////////////////////////////////////////////////////////
1537
Ben Wagnerc3aef182017-06-26 12:47:33 -04001538void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph, SkGlyphID gid) {
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001539 // check to see if the embolden bit is set
1540 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1541 return;
1542 }
1543
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001544 switch (glyph->format) {
1545 case FT_GLYPH_FORMAT_OUTLINE:
1546 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001547 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1548 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001549 FT_Outline_Embolden(&glyph->outline, strength);
1550 break;
1551 case FT_GLYPH_FORMAT_BITMAP:
Ben Wagnerc3aef182017-06-26 12:47:33 -04001552 if (!fFace->glyph->bitmap.buffer) {
1553 FT_Load_Glyph(fFace, gid, fLoadGlyphFlags);
1554 }
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001555 FT_GlyphSlot_Own_Bitmap(glyph);
1556 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1557 break;
1558 default:
1559 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001560 }
1561}
1562
reed@google.comb4162b12013-07-02 16:32:29 +00001563///////////////////////////////////////////////////////////////////////////////
1564
Mike Kleinc0bd9f92019-04-23 12:05:21 -05001565#include "src/core/SkUtils.h"
reed@google.comb4162b12013-07-02 16:32:29 +00001566
Ben Wagner2c7c36a2021-06-22 17:43:27 -04001567SkTypeface_FreeType::SkTypeface_FreeType(const SkFontStyle& style, bool isFixedPitch)
1568 : INHERITED(style, isFixedPitch)
1569{}
1570
Ben Wagner266bf822021-06-30 16:27:14 -04001571SkTypeface_FreeType::~SkTypeface_FreeType() {
1572 if (fFaceRec) {
1573 SkAutoMutexExclusive ac(f_t_mutex());
1574 fFaceRec.reset();
1575 }
1576}
Ben Wagner2c7c36a2021-06-22 17:43:27 -04001577
Mike Reedb07e9a82019-04-19 10:02:10 -04001578// Just made up, so we don't end up storing 1000s of entries
1579constexpr int kMaxC2GCacheCount = 512;
1580
Mike Reed64670cb2019-04-16 11:37:38 -07001581void SkTypeface_FreeType::onCharsToGlyphs(const SkUnichar uni[], int count,
1582 SkGlyphID glyphs[]) const {
Mike Reedb07e9a82019-04-19 10:02:10 -04001583 // Try the cache first, *before* accessing freetype lib/face, as that
1584 // can be very slow. If we do need to compute a new glyphID, then
1585 // access those freetype objects and continue the loop.
1586
Mike Reedb07e9a82019-04-19 10:02:10 -04001587 int i;
Herb Derby12640012021-05-13 14:41:17 -04001588 {
1589 // Optimistically use a shared lock.
1590 SkAutoSharedMutexShared ama(fC2GCacheMutex);
1591 for (i = 0; i < count; ++i) {
1592 int index = fC2GCache.findGlyphIndex(uni[i]);
1593 if (index < 0) {
1594 break;
1595 }
1596 glyphs[i] = SkToU16(index);
Mike Reedb07e9a82019-04-19 10:02:10 -04001597 }
Herb Derby12640012021-05-13 14:41:17 -04001598 if (i == count) {
1599 // we're done, no need to access the freetype objects
1600 return;
1601 }
Mike Reedb07e9a82019-04-19 10:02:10 -04001602 }
1603
Herb Derby12640012021-05-13 14:41:17 -04001604 // Need to add more so grab an exclusive lock.
1605 SkAutoSharedMutexExclusive ama(fC2GCacheMutex);
reed@google.comb4162b12013-07-02 16:32:29 +00001606 AutoFTAccess fta(this);
1607 FT_Face face = fta.face();
1608 if (!face) {
Mike Reed64670cb2019-04-16 11:37:38 -07001609 sk_bzero(glyphs, count * sizeof(glyphs[0]));
1610 return;
reed@google.comb4162b12013-07-02 16:32:29 +00001611 }
1612
Mike Reedb07e9a82019-04-19 10:02:10 -04001613 for (; i < count; ++i) {
1614 SkUnichar c = uni[i];
1615 int index = fC2GCache.findGlyphIndex(c);
1616 if (index >= 0) {
1617 glyphs[i] = SkToU16(index);
1618 } else {
1619 glyphs[i] = SkToU16(FT_Get_Char_Index(face, c));
1620 fC2GCache.insertCharAndGlyph(~index, c, glyphs[i]);
1621 }
1622 }
1623
1624 if (fC2GCache.count() > kMaxC2GCacheCount) {
1625 fC2GCache.reset();
reed@google.comb4162b12013-07-02 16:32:29 +00001626 }
1627}
1628
1629int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001630 AutoFTAccess fta(this);
1631 FT_Face face = fta.face();
1632 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001633}
1634
bungeman@google.com839702b2013-08-07 17:09:22 +00001635SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
Ben Wagnerad031f52018-08-20 13:45:57 -04001636 sk_sp<SkTypeface::LocalizedStrings> nameIter =
1637 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
1638 if (!nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001639 SkString familyName;
1640 this->getFamilyName(&familyName);
1641 SkString language("und"); //undetermined
Ben Wagnerad031f52018-08-20 13:45:57 -04001642 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(familyName, language);
bungeman@google.coma9802692013-08-07 02:45:25 +00001643 }
Ben Wagnerad031f52018-08-20 13:45:57 -04001644 return nameIter.release();
bungeman@google.coma9802692013-08-07 02:45:25 +00001645}
1646
Dominik Röttsches8be63322021-11-03 11:45:25 +02001647bool SkTypeface_FreeType::onGlyphMaskNeedsCurrentColor() const {
Ben Wagner0cdcf572021-11-19 11:33:33 -05001648 fGlyphMasksMayNeedCurrentColorOnce([this]{
1649 static constexpr SkFourByteTag COLRTag = SkSetFourByteTag('C', 'O', 'L', 'R');
1650 fGlyphMasksMayNeedCurrentColor = this->getTableSize(COLRTag) > 0;
1651 });
1652 return fGlyphMasksMayNeedCurrentColor;
Dominik Röttsches8be63322021-11-03 11:45:25 +02001653}
1654
Ben Wagnerfc497342017-02-24 11:15:26 -05001655int SkTypeface_FreeType::onGetVariationDesignPosition(
Ben Wagnere346b1e2018-06-26 11:22:37 -04001656 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
Ben Wagnerfc497342017-02-24 11:15:26 -05001657{
1658 AutoFTAccess fta(this);
Ben Wagner2478c702021-02-14 17:25:35 -05001659 return GetVariationDesignPosition(fta, coordinates, coordinateCount);
Ben Wagnerfc497342017-02-24 11:15:26 -05001660}
1661
Ben Wagnere346b1e2018-06-26 11:22:37 -04001662int SkTypeface_FreeType::onGetVariationDesignParameters(
1663 SkFontParameters::Variation::Axis parameters[], int parameterCount) const
1664{
1665 AutoFTAccess fta(this);
1666 FT_Face face = fta.face();
1667 if (!face) {
1668 return -1;
1669 }
1670
1671 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
1672 return 0;
1673 }
1674
1675 FT_MM_Var* variations = nullptr;
1676 if (FT_Get_MM_Var(face, &variations)) {
1677 return -1;
1678 }
1679 SkAutoFree autoFreeVariations(variations);
1680
1681 if (!parameters || parameterCount < SkToInt(variations->num_axis)) {
1682 return variations->num_axis;
1683 }
1684
1685 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1686 parameters[i].tag = variations->axis[i].tag;
1687 parameters[i].min = SkFixedToScalar(variations->axis[i].minimum);
1688 parameters[i].def = SkFixedToScalar(variations->axis[i].def);
1689 parameters[i].max = SkFixedToScalar(variations->axis[i].maximum);
1690 FT_UInt flags = 0;
Ben Wagner12745c82021-07-19 11:03:45 -04001691 bool hidden = !FT_Get_Var_Axis_Flags(variations, i, &flags) &&
1692 (flags & FT_VAR_AXIS_FLAG_HIDDEN);
Ben Wagnere346b1e2018-06-26 11:22:37 -04001693 parameters[i].setHidden(hidden);
1694 }
1695
1696 return variations->num_axis;
1697}
1698
bungeman@google.comddc218e2013-08-01 22:29:43 +00001699int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1700 AutoFTAccess fta(this);
1701 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -04001702 if (!face) {
1703 return 0;
1704 }
bungeman@google.comddc218e2013-08-01 22:29:43 +00001705
1706 FT_ULong tableCount = 0;
1707 FT_Error error;
1708
halcanary96fcdcc2015-08-27 07:41:13 -07001709 // When 'tag' is nullptr, returns number of tables in 'length'.
1710 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001711 if (error) {
1712 return 0;
1713 }
1714
1715 if (tags) {
1716 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1717 FT_ULong tableTag;
1718 FT_ULong tablelength;
1719 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1720 if (error) {
1721 return 0;
1722 }
1723 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1724 }
1725 }
1726 return tableCount;
1727}
1728
1729size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1730 size_t length, void* data) const
1731{
1732 AutoFTAccess fta(this);
1733 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -04001734 if (!face) {
1735 return 0;
1736 }
bungeman@google.comddc218e2013-08-01 22:29:43 +00001737
1738 FT_ULong tableLength = 0;
1739 FT_Error error;
1740
1741 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001742 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001743 if (error) {
1744 return 0;
1745 }
1746
1747 if (offset > tableLength) {
1748 return 0;
1749 }
Brian Osman788b9162020-02-07 10:36:46 -05001750 FT_ULong size = std::min((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001751 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001752 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1753 if (error) {
1754 return 0;
1755 }
1756 }
1757
1758 return size;
1759}
1760
Mike Reed6d907fa2019-07-24 14:51:34 -04001761sk_sp<SkData> SkTypeface_FreeType::onCopyTableData(SkFontTableTag tag) const {
1762 AutoFTAccess fta(this);
1763 FT_Face face = fta.face();
Ben Wagner6669b012020-07-08 11:58:18 -04001764 if (!face) {
1765 return nullptr;
1766 }
Mike Reed6d907fa2019-07-24 14:51:34 -04001767
1768 FT_ULong tableLength = 0;
1769 FT_Error error;
1770
1771 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
1772 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
1773 if (error) {
1774 return nullptr;
1775 }
1776
1777 sk_sp<SkData> data = SkData::MakeUninitialized(tableLength);
1778 if (data) {
1779 error = FT_Load_Sfnt_Table(face, tag, 0,
1780 reinterpret_cast<FT_Byte*>(data->writable_data()), &tableLength);
1781 if (error) {
1782 data.reset();
1783 }
1784 }
1785 return data;
1786}
1787
Ben Wagner2c7c36a2021-06-22 17:43:27 -04001788SkTypeface_FreeType::FaceRec* SkTypeface_FreeType::getFaceRec() const {
1789 f_t_mutex().assertHeld();
1790 fFTFaceOnce([this]{ fFaceRec = SkTypeface_FreeType::FaceRec::Make(this); });
1791 return fFaceRec.get();
1792}
1793
Ben Wagner9d5c55c2020-06-27 12:52:14 -04001794std::unique_ptr<SkFontData> SkTypeface_FreeType::makeFontData() const {
1795 return this->onMakeFontData();
1796}
1797
reed@google.comb4162b12013-07-02 16:32:29 +00001798///////////////////////////////////////////////////////////////////////////////
1799///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001800
halcanary96fcdcc2015-08-27 07:41:13 -07001801SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001802 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1803 return;
bungeman14df8332014-10-28 15:07:23 -07001804 }
bungeman9dc24682014-12-01 14:01:32 -08001805 FT_Add_Default_Modules(fLibrary);
Ben Wagner12745c82021-07-19 11:03:45 -04001806 FT_Set_Default_Properties(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001807}
1808SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001809 if (fLibrary) {
1810 FT_Done_Library(fLibrary);
1811 }
bungeman14df8332014-10-28 15:07:23 -07001812}
1813
bungemanf93d7112016-09-16 06:24:20 -07001814FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001815 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001816{
Anthony Catel463d7292020-06-03 11:57:19 +02001817 if (fLibrary == nullptr || stream == nullptr) {
halcanary96fcdcc2015-08-27 07:41:13 -07001818 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001819 }
1820
bungeman14df8332014-10-28 15:07:23 -07001821 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001822 memset(&args, 0, sizeof(args));
1823
1824 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001825
bsalomon49f085d2014-09-05 13:34:00 -07001826 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001827 args.flags = FT_OPEN_MEMORY;
1828 args.memory_base = (const FT_Byte*)memoryBase;
1829 args.memory_size = stream->getLength();
1830 } else {
bungeman14df8332014-10-28 15:07:23 -07001831 memset(ftStream, 0, sizeof(*ftStream));
1832 ftStream->size = stream->getLength();
1833 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001834 ftStream->read = sk_ft_stream_io;
1835 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001836
1837 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001838 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001839 }
1840
1841 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001842 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001843 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001844 }
1845 return face;
1846}
1847
bungemanf93d7112016-09-16 06:24:20 -07001848bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
Herb Derby9b869552019-05-10 12:16:17 -04001849 SkAutoMutexExclusive libraryLock(fLibraryMutex);
bungeman14df8332014-10-28 15:07:23 -07001850
1851 FT_StreamRec streamRec;
Ben Wagner6669b012020-07-08 11:58:18 -04001852 SkUniqueFTFace face(this->openFace(stream, -1, &streamRec));
1853 if (!face) {
bungeman14df8332014-10-28 15:07:23 -07001854 return false;
1855 }
1856
1857 *numFaces = face->num_faces;
bungeman14df8332014-10-28 15:07:23 -07001858 return true;
1859}
1860
bungeman14df8332014-10-28 15:07:23 -07001861bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001862 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001863 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001864{
Herb Derby9b869552019-05-10 12:16:17 -04001865 SkAutoMutexExclusive libraryLock(fLibraryMutex);
bungeman14df8332014-10-28 15:07:23 -07001866
1867 FT_StreamRec streamRec;
Ben Wagner6669b012020-07-08 11:58:18 -04001868 SkUniqueFTFace face(this->openFace(stream, ttcIndex, &streamRec));
1869 if (!face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001870 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001871 }
1872
bungemana4c4a2d2014-10-20 13:33:19 -07001873 int weight = SkFontStyle::kNormal_Weight;
1874 int width = SkFontStyle::kNormal_Width;
1875 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001876 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001877 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001878 }
1879 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001880 slant = SkFontStyle::kItalic_Slant;
1881 }
1882
1883 PS_FontInfoRec psFontInfo;
Ben Wagner6669b012020-07-08 11:58:18 -04001884 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face.get(), ft_sfnt_os2));
bungemana4c4a2d2014-10-20 13:33:19 -07001885 if (os2 && os2->version != 0xffff) {
1886 weight = os2->usWeightClass;
1887 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001888
1889 // OS/2::fsSelection bit 9 indicates oblique.
1890 if (SkToBool(os2->fsSelection & (1u << 9))) {
1891 slant = SkFontStyle::kOblique_Slant;
1892 }
Ben Wagner6669b012020-07-08 11:58:18 -04001893 } else if (0 == FT_Get_PS_Font_Info(face.get(), &psFontInfo) && psFontInfo.weight) {
bungemana4c4a2d2014-10-20 13:33:19 -07001894 static const struct {
1895 char const * const name;
1896 int const weight;
1897 } commonWeights [] = {
1898 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001899 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001900 { "black", SkFontStyle::kBlack_Weight },
1901 { "bold", SkFontStyle::kBold_Weight },
1902 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1903 { "demi", SkFontStyle::kSemiBold_Weight },
1904 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001905 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001906 { "extrabold", SkFontStyle::kExtraBold_Weight },
1907 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001908 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001909 { "heavy", SkFontStyle::kBlack_Weight },
1910 { "light", SkFontStyle::kLight_Weight },
1911 { "medium", SkFontStyle::kMedium_Weight },
1912 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001913 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001914 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001915 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001916 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001917 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001918 { "thin", SkFontStyle::kThin_Weight },
1919 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001920 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001921 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001922 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001923 { "ultralight", SkFontStyle::kExtraLight_Weight },
1924 };
1925 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001926 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001927 if (index >= 0) {
1928 weight = commonWeights[index].weight;
1929 } else {
Mike Klein3e0141a2019-03-26 10:41:18 -05001930 LOG_INFO("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight);
bungemana4c4a2d2014-10-20 13:33:19 -07001931 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001932 }
1933
John Stiles4b4e32f2020-08-02 21:52:44 -04001934 if (name != nullptr) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001935 name->set(face->family_name);
1936 }
John Stiles4b4e32f2020-08-02 21:52:44 -04001937 if (style != nullptr) {
bungemana4c4a2d2014-10-20 13:33:19 -07001938 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001939 }
John Stiles4b4e32f2020-08-02 21:52:44 -04001940 if (isFixedPitch != nullptr) {
bungeman@google.comfe747652013-03-25 19:36:11 +00001941 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001942 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001943
John Stiles4b4e32f2020-08-02 21:52:44 -04001944 if (axes != nullptr && !GetAxes(face.get(), axes)) {
Ben Wagner6669b012020-07-08 11:58:18 -04001945 return false;
1946 }
1947 return true;
Bruce Wangebf0cf52018-06-18 14:04:19 -04001948}
1949
1950bool SkTypeface_FreeType::Scanner::GetAxes(FT_Face face, AxisDefinitions* axes) {
Ben Wagner6669b012020-07-08 11:58:18 -04001951 SkASSERT(face && axes);
1952 if (face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001953 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001954 FT_Error err = FT_Get_MM_Var(face, &variations);
1955 if (err) {
Mike Klein3e0141a2019-03-26 10:41:18 -05001956 LOG_INFO("INFO: font %s claims to have variations, but none found.\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04001957 face->family_name);
bungeman41868fe2015-05-20 09:21:04 -07001958 return false;
1959 }
1960 SkAutoFree autoFreeVariations(variations);
1961
1962 axes->reset(variations->num_axis);
1963 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1964 const FT_Var_Axis& ftAxis = variations->axis[i];
1965 (*axes)[i].fTag = ftAxis.tag;
1966 (*axes)[i].fMinimum = ftAxis.minimum;
1967 (*axes)[i].fDefault = ftAxis.def;
1968 (*axes)[i].fMaximum = ftAxis.maximum;
1969 }
1970 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001971 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001972}
bungemanf6c71072016-01-21 14:17:47 -08001973
1974/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1975 AxisDefinitions axisDefinitions,
Ben Wagnerfc497342017-02-24 11:15:26 -05001976 const SkFontArguments::VariationPosition position,
bungemanf6c71072016-01-21 14:17:47 -08001977 SkFixed* axisValues,
Ben Wagner2478c702021-02-14 17:25:35 -05001978 const SkString& name,
1979 const SkFontArguments::VariationPosition::Coordinate* current)
bungemanf6c71072016-01-21 14:17:47 -08001980{
1981 for (int i = 0; i < axisDefinitions.count(); ++i) {
1982 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001983 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1984 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
Ben Wagner2478c702021-02-14 17:25:35 -05001985
1986 // Start with the default value.
bungemanf6c71072016-01-21 14:17:47 -08001987 axisValues[i] = axisDefinition.fDefault;
Ben Wagner2478c702021-02-14 17:25:35 -05001988
1989 // Then the current value.
1990 if (current) {
1991 for (int j = 0; j < axisDefinitions.count(); ++j) {
1992 const auto& coordinate = current[j];
1993 if (axisDefinition.fTag == coordinate.axis) {
1994 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
1995 axisValues[i] = SkScalarToFixed(axisValue);
1996 break;
1997 }
1998 }
1999 }
2000
2001 // Then the requested value.
bungeman9aec8942017-03-29 13:38:53 -04002002 // The position may be over specified. If there are multiple values for a given axis,
2003 // use the last one since that's what css-fonts-4 requires.
2004 for (int j = position.coordinateCount; j --> 0;) {
Ben Wagnerfc497342017-02-24 11:15:26 -05002005 const auto& coordinate = position.coordinates[j];
2006 if (axisDefinition.fTag == coordinate.axis) {
2007 const SkScalar axisValue = SkTPin(coordinate.value, axisMin, axisMax);
2008 if (coordinate.value != axisValue) {
Mike Klein3e0141a2019-03-26 10:41:18 -05002009 LOG_INFO("Requested font axis value out of range: "
Hal Canary2b0e6cd2018-07-09 12:43:39 -04002010 "%s '%c%c%c%c' %f; pinned to %f.\n",
2011 name.c_str(),
2012 (axisDefinition.fTag >> 24) & 0xFF,
2013 (axisDefinition.fTag >> 16) & 0xFF,
2014 (axisDefinition.fTag >> 8) & 0xFF,
2015 (axisDefinition.fTag ) & 0xFF,
2016 SkScalarToDouble(coordinate.value),
2017 SkScalarToDouble(axisValue));
bungemanf6c71072016-01-21 14:17:47 -08002018 }
benjaminwagner64a3c952016-02-25 12:20:40 -08002019 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08002020 break;
2021 }
2022 }
2023 // TODO: warn on defaulted axis?
2024 }
2025
2026 SkDEBUGCODE(
2027 // Check for axis specified, but not matched in font.
Ben Wagnerfc497342017-02-24 11:15:26 -05002028 for (int i = 0; i < position.coordinateCount; ++i) {
2029 SkFourByteTag skTag = position.coordinates[i].axis;
bungemanf6c71072016-01-21 14:17:47 -08002030 bool found = false;
2031 for (int j = 0; j < axisDefinitions.count(); ++j) {
2032 if (skTag == axisDefinitions[j].fTag) {
2033 found = true;
2034 break;
2035 }
2036 }
2037 if (!found) {
Mike Klein3e0141a2019-03-26 10:41:18 -05002038 LOG_INFO("Requested font axis not found: %s '%c%c%c%c'\n",
Hal Canary2b0e6cd2018-07-09 12:43:39 -04002039 name.c_str(),
2040 (skTag >> 24) & 0xFF,
2041 (skTag >> 16) & 0xFF,
2042 (skTag >> 8) & 0xFF,
2043 (skTag) & 0xFF);
bungemanf6c71072016-01-21 14:17:47 -08002044 }
2045 }
2046 )
2047}