blob: 2eaf2bf06e86c1dae3139f7a3a125a7e53da617d [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
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +00008#include "SkAdvancedTypefaceMetrics.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +00009#include "SkBitmap.h"
10#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000011#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000012#include "SkDescriptor.h"
13#include "SkFDot6.h"
bungeman41868fe2015-05-20 09:21:04 -070014#include "SkFontDescriptor.h"
george@mozilla.comc59b5da2012-08-23 00:39:08 +000015#include "SkFontHost_FreeType_common.h"
bungeman@google.combbe50132012-07-24 20:33:21 +000016#include "SkGlyph.h"
bungeman7cfd46a2016-10-20 16:06:52 -040017#include "SkMakeUnique.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000018#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000019#include "SkMaskGamma.h"
bungeman@google.comd3fbd342014-04-15 15:52:07 +000020#include "SkMatrix22.h"
mtklein1b249332015-07-07 12:21:21 -070021#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000022#include "SkOTUtils.h"
bungemand3ebb482015-08-05 13:57:49 -070023#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000024#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000025#include "SkStream.h"
26#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027#include "SkTemplates.h"
bungeman9dc24682014-12-01 14:01:32 -080028#include "SkTypes.h"
mtklein5f939ab2016-03-16 10:28:35 -070029#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000030
bungeman@google.comfd668cf2012-08-24 17:46:11 +000031#if defined(SK_CAN_USE_DLOPEN)
32#include <dlfcn.h>
33#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000034#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080035#include FT_ADVANCES_H
36#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000037#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080038#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080039#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070040#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000041#include FT_OUTLINE_H
42#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080043#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000044#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000045#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000046#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000047
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000048// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
49// were introduced in FreeType 2.5.0.
50// The following may be removed once FreeType 2.5.0 is required to build.
51#ifndef FT_LOAD_COLOR
52# define FT_LOAD_COLOR ( 1L << 20 )
53# define FT_PIXEL_MODE_BGRA 7
54#endif
55
reed@android.com8a1c16f2008-12-17 15:59:43 +000056//#define ENABLE_GLYPH_SPEW // for tracing calls
57//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080058//#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
59//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000060//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000061
reed@google.comeffc5012011-06-27 16:44:46 +000062static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080063 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000064}
65
reed@android.com8a1c16f2008-12-17 15:59:43 +000066//////////////////////////////////////////////////////////////////////////
67
bungeman9dc24682014-12-01 14:01:32 -080068extern "C" {
69 static void* sk_ft_alloc(FT_Memory, long size) {
70 return sk_malloc_throw(size);
71 }
72 static void sk_ft_free(FT_Memory, void* block) {
73 sk_free(block);
74 }
75 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
76 return sk_realloc_throw(block, new_size);
77 }
78};
halcanary96fcdcc2015-08-27 07:41:13 -070079FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -080080
81class FreeTypeLibrary : SkNoncopyable {
82public:
halcanary96fcdcc2015-08-27 07:41:13 -070083 FreeTypeLibrary() : fLibrary(nullptr), fIsLCDSupported(false), fLCDExtra(0) {
bungeman9dc24682014-12-01 14:01:32 -080084 if (FT_New_Library(&gFTMemory, &fLibrary)) {
85 return;
86 }
87 FT_Add_Default_Modules(fLibrary);
88
89 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
90 // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
91 // SetLcdFilter must be called before SetLcdFilterWeights.
92 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
93 fIsLCDSupported = true;
94 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
95
96#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
97 // Adds to 0x110 simulating ink spread, but provides better results than default.
98 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
99
100# if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
101 FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
102# elif SK_CAN_USE_DLOPEN == 1
103 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700104 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800105 if (self) {
106 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
107 //The following cast is non-standard, but safe for POSIX.
108 *reinterpret_cast<void**>(&setLcdFilterWeights) =
109 dlsym(self, "FT_Library_SetLcdFilterWeights");
110 dlclose(self);
111
112 if (setLcdFilterWeights) {
113 setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
114 }
115 }
116# endif
117#endif
118 }
119 }
120 ~FreeTypeLibrary() {
121 if (fLibrary) {
122 FT_Done_Library(fLibrary);
123 }
124 }
125
126 FT_Library library() { return fLibrary; }
127 bool isLCDSupported() { return fIsLCDSupported; }
128 int lcdExtra() { return fLCDExtra; }
129
130private:
131 FT_Library fLibrary;
132 bool fIsLCDSupported;
133 int fLCDExtra;
134
135 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
136 // The following platforms provide FreeType of at least 2.4.0.
137 // Ubuntu >= 11.04 (previous deprecated April 2013)
138 // Debian >= 6.0 (good)
139 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
140 // Fedora >= 14 (good)
141 // Android >= Gingerbread (good)
142 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
143};
144
reed@android.com8a1c16f2008-12-17 15:59:43 +0000145struct SkFaceRec;
146
reed086eea92016-05-04 17:12:46 -0700147SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800148static FreeTypeLibrary* gFTLibrary;
149static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000150
bungemanaabd71c2016-03-01 15:15:09 -0800151// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800152static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000153
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000154// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800155static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800156 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800157 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800158
bungeman9dc24682014-12-01 14:01:32 -0800159 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700160 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700161 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000162 }
bungeman9dc24682014-12-01 14:01:32 -0800163 ++gFTCount;
164 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000165}
166
bungeman9dc24682014-12-01 14:01:32 -0800167// Caller must lock gFTMutex before calling this function.
168static void unref_ft_library() {
169 gFTMutex.assertHeld();
170 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000171
bungeman9dc24682014-12-01 14:01:32 -0800172 --gFTCount;
173 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800174 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700175 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700176 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700177 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800178 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000179}
180
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000181class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182public:
bungeman7cfd46a2016-10-20 16:06:52 -0400183 SkScalerContext_FreeType(sk_sp<SkTypeface>,
184 const SkScalerContextEffects&,
185 const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000186 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000187
reed@android.com62900b42009-02-11 15:07:19 +0000188 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700189 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000190 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000191
192protected:
mtklein36352bf2015-03-25 18:17:31 -0700193 unsigned generateGlyphCount() override;
194 uint16_t generateCharToGlyph(SkUnichar uni) override;
195 void generateAdvance(SkGlyph* glyph) override;
196 void generateMetrics(SkGlyph* glyph) override;
197 void generateImage(const SkGlyph& glyph) override;
198 void generatePath(const SkGlyph& glyph, SkPath* path) override;
199 void generateFontMetrics(SkPaint::FontMetrics*) override;
200 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000201
202private:
bungeman401ae2d2016-07-18 15:46:27 -0700203 FT_Face fFace; // Shared face from gFaceRecHead.
204 FT_Size fFTSize; // The size on the fFace for this scaler.
205 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000206
bungeman401ae2d2016-07-18 15:46:27 -0700207 /** The rest of the matrix after FreeType handles the size.
208 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
209 * With bitmap only fonts this matrix must be applied to scale the bitmap.
210 */
211 SkMatrix fMatrix22Scalar;
212 /** Same as fMatrix22Scalar, but in FreeType units and space. */
213 FT_Matrix fMatrix22;
214 /** The actual size requested. */
215 SkVector fScale;
216
217 uint32_t fLoadGlyphFlags;
218 bool fDoLinearMetrics;
219 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000220
reed@android.com8a1c16f2008-12-17 15:59:43 +0000221 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000222 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
223 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000224 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000225 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000226 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000227 // Caller must lock gFTMutex before calling this function.
228 // update FreeType2 glyph slot with glyph emboldened
229 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
bungeman401ae2d2016-07-18 15:46:27 -0700230 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000231};
232
233///////////////////////////////////////////////////////////////////////////
234///////////////////////////////////////////////////////////////////////////
235
reed@android.com8a1c16f2008-12-17 15:59:43 +0000236struct SkFaceRec {
bungeman52b64b42015-01-27 10:41:17 -0800237 SkFaceRec* fNext;
238 FT_Face fFace;
239 FT_StreamRec fFTStream;
bungemanf93d7112016-09-16 06:24:20 -0700240 std::unique_ptr<SkStreamAsset> fSkStream;
bungeman52b64b42015-01-27 10:41:17 -0800241 uint32_t fRefCnt;
242 uint32_t fFontID;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000243
bungemanf93d7112016-09-16 06:24:20 -0700244 SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000245};
246
247extern "C" {
bungeman52b64b42015-01-27 10:41:17 -0800248 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
bungeman9dc24682014-12-01 14:01:32 -0800249 unsigned long offset,
250 unsigned char* buffer,
251 unsigned long count)
252 {
bungeman52b64b42015-01-27 10:41:17 -0800253 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000254
255 if (count) {
bungeman52b64b42015-01-27 10:41:17 -0800256 if (!stream->seek(offset)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000257 return 0;
bungeman9dc24682014-12-01 14:01:32 -0800258 }
bungeman52b64b42015-01-27 10:41:17 -0800259 count = stream->read(buffer, count);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000260 }
261 return count;
262 }
263
bungeman9dc24682014-12-01 14:01:32 -0800264 static void sk_ft_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000265}
266
bungemanf93d7112016-09-16 06:24:20 -0700267SkFaceRec::SkFaceRec(std::unique_ptr<SkStreamAsset> stream, uint32_t fontID)
268 : fNext(nullptr), fSkStream(std::move(stream)), fRefCnt(1), fFontID(fontID)
bungeman52b64b42015-01-27 10:41:17 -0800269{
reed@android.com4516f472009-06-29 16:25:36 +0000270 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000271 fFTStream.size = fSkStream->getLength();
bungemanf93d7112016-09-16 06:24:20 -0700272 fFTStream.descriptor.pointer = fSkStream.get();
bungeman9dc24682014-12-01 14:01:32 -0800273 fFTStream.read = sk_ft_stream_io;
274 fFTStream.close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000275}
276
bungeman41868fe2015-05-20 09:21:04 -0700277static void ft_face_setup_axes(FT_Face face, const SkFontData& data) {
278 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
279 return;
280 }
281
282 SkDEBUGCODE(
halcanary96fcdcc2015-08-27 07:41:13 -0700283 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -0700284 if (FT_Get_MM_Var(face, &variations)) {
285 SkDEBUGF(("INFO: font %s claims variations, but none found.\n", face->family_name));
286 return;
287 }
288 SkAutoFree autoFreeVariations(variations);
289
290 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
291 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
292 face->family_name, variations->num_axis, data.getAxisCount()));
293 return;
294 }
295 )
296
297 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
298 for (int i = 0; i < data.getAxisCount(); ++i) {
299 coords[i] = data.getAxis()[i];
300 }
301 if (FT_Set_Var_Design_Coordinates(face, data.getAxisCount(), coords.get())) {
302 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
303 face->family_name));
304 return;
305 }
306}
bungeman41868fe2015-05-20 09:21:04 -0700307
reed@android.com62900b42009-02-11 15:07:19 +0000308// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000309// Caller must lock gFTMutex before calling this function.
bungeman13a007d2015-06-19 05:09:39 -0700310static FT_Face ref_ft_face(const SkTypeface* typeface) {
bungeman5ec443c2014-11-21 13:18:34 -0800311 gFTMutex.assertHeld();
312
reed@google.com2cdc6712013-03-21 18:22:00 +0000313 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000314 SkFaceRec* rec = gFaceRecHead;
315 while (rec) {
316 if (rec->fFontID == fontID) {
317 SkASSERT(rec->fFace);
318 rec->fRefCnt += 1;
bungeman13a007d2015-06-19 05:09:39 -0700319 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000320 }
321 rec = rec->fNext;
322 }
323
bungemanf93d7112016-09-16 06:24:20 -0700324 std::unique_ptr<SkFontData> data = typeface->makeFontData();
halcanary96fcdcc2015-08-27 07:41:13 -0700325 if (nullptr == data || !data->hasStream()) {
326 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000327 }
328
halcanary385fe4d2015-08-26 13:07:48 -0700329 rec = new SkFaceRec(data->detachStream(), fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000330
bungeman9dc24682014-12-01 14:01:32 -0800331 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000332 memset(&args, 0, sizeof(args));
bungeman41868fe2015-05-20 09:21:04 -0700333 const void* memoryBase = rec->fSkStream->getMemoryBase();
bsalomon49f085d2014-09-05 13:34:00 -0700334 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000335 args.flags = FT_OPEN_MEMORY;
336 args.memory_base = (const FT_Byte*)memoryBase;
bungeman41868fe2015-05-20 09:21:04 -0700337 args.memory_size = rec->fSkStream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338 } else {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000339 args.flags = FT_OPEN_STREAM;
340 args.stream = &rec->fFTStream;
341 }
342
bungeman41868fe2015-05-20 09:21:04 -0700343 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rec->fFace);
344 if (err) {
bungeman5ec443c2014-11-21 13:18:34 -0800345 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
halcanary385fe4d2015-08-26 13:07:48 -0700346 delete rec;
halcanary96fcdcc2015-08-27 07:41:13 -0700347 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000348 }
bungeman9dc24682014-12-01 14:01:32 -0800349 SkASSERT(rec->fFace);
bungeman41868fe2015-05-20 09:21:04 -0700350
bungeman41868fe2015-05-20 09:21:04 -0700351 ft_face_setup_axes(rec->fFace, *data);
bungeman41868fe2015-05-20 09:21:04 -0700352
bungeman726cf902015-06-05 13:38:12 -0700353 // FreeType will set the charmap to the "most unicode" cmap if it exists.
halcanary96fcdcc2015-08-27 07:41:13 -0700354 // If there are no unicode cmaps, the charmap is set to nullptr.
bungeman726cf902015-06-05 13:38:12 -0700355 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
356 // because they are effectively private use area only (even if they aren't).
357 // This is the last on the fallback list at
358 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
359 if (!rec->fFace->charmap) {
360 FT_Select_Charmap(rec->fFace, FT_ENCODING_MS_SYMBOL);
361 }
362
bungeman9dc24682014-12-01 14:01:32 -0800363 rec->fNext = gFaceRecHead;
364 gFaceRecHead = rec;
bungeman13a007d2015-06-19 05:09:39 -0700365 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000366}
367
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000368// Caller must lock gFTMutex before calling this function.
caryclarkfe7ada72016-03-21 06:55:52 -0700369extern void unref_ft_face(FT_Face face);
370void unref_ft_face(FT_Face face) {
bungeman5ec443c2014-11-21 13:18:34 -0800371 gFTMutex.assertHeld();
372
reed@android.com8a1c16f2008-12-17 15:59:43 +0000373 SkFaceRec* rec = gFaceRecHead;
halcanary96fcdcc2015-08-27 07:41:13 -0700374 SkFaceRec* prev = nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000375 while (rec) {
376 SkFaceRec* next = rec->fNext;
377 if (rec->fFace == face) {
378 if (--rec->fRefCnt == 0) {
379 if (prev) {
380 prev->fNext = next;
381 } else {
382 gFaceRecHead = next;
383 }
384 FT_Done_Face(face);
halcanary385fe4d2015-08-26 13:07:48 -0700385 delete rec;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000386 }
387 return;
388 }
389 prev = rec;
390 rec = next;
391 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000392 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000393}
394
reed@google.comb4162b12013-07-02 16:32:29 +0000395class AutoFTAccess {
396public:
halcanary96fcdcc2015-08-27 07:41:13 -0700397 AutoFTAccess(const SkTypeface* tf) : fFace(nullptr) {
reed@google.comb4162b12013-07-02 16:32:29 +0000398 gFTMutex.acquire();
bungeman9dc24682014-12-01 14:01:32 -0800399 if (!ref_ft_library()) {
400 sk_throw();
reed@google.comb4162b12013-07-02 16:32:29 +0000401 }
bungeman13a007d2015-06-19 05:09:39 -0700402 fFace = ref_ft_face(tf);
reed@google.comb4162b12013-07-02 16:32:29 +0000403 }
404
405 ~AutoFTAccess() {
406 if (fFace) {
407 unref_ft_face(fFace);
408 }
bungeman9dc24682014-12-01 14:01:32 -0800409 unref_ft_library();
reed@google.comb4162b12013-07-02 16:32:29 +0000410 gFTMutex.release();
411 }
412
reed@google.comb4162b12013-07-02 16:32:29 +0000413 FT_Face face() { return fFace; }
414
415private:
reed@google.comb4162b12013-07-02 16:32:29 +0000416 FT_Face fFace;
417};
418
reed@android.com8a1c16f2008-12-17 15:59:43 +0000419///////////////////////////////////////////////////////////////////////////
420
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000421static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000422 FT_UShort fsType = FT_Get_FSType_Flags(face);
423 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
424 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000425}
426
vandebo0f9bad02014-06-19 11:05:39 -0700427static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700428 FT_UShort fsType = FT_Get_FSType_Flags(face);
429 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700430}
431
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000432static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
433 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
434 if (!glyph_id)
435 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000436 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
437 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000438 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
439 return true;
440}
441
bungeman5ec443c2014-11-21 13:18:34 -0800442static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
halcanaryf8c74a12016-04-20 08:37:43 -0700443 FT_Long numGlyphs = face->num_glyphs;
444 glyphToUnicode->setCount(SkToInt(numGlyphs));
445 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000446
bungeman726cf902015-06-05 13:38:12 -0700447 FT_UInt glyphIndex;
448 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
449 while (glyphIndex) {
halcanaryf8c74a12016-04-20 08:37:43 -0700450 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
halcanary5f1d0f62016-09-13 08:08:38 -0700451 // Use the first character that maps to this glyphID. https://crbug.com/359065
452 if (0 == (*glyphToUnicode)[glyphIndex]) {
453 (*glyphToUnicode)[glyphIndex] = charCode;
454 }
bungeman726cf902015-06-05 13:38:12 -0700455 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000456 }
457}
458
reed@google.com2689f612013-03-20 20:01:47 +0000459SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700460 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000461 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000462 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000463 AutoFTAccess fta(this);
464 FT_Face face = fta.face();
465 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700466 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000467 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000468
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000469 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
470 info->fFontName.set(FT_Get_Postscript_Name(face));
halcanary32875882016-08-16 09:36:23 -0700471
vandebo0f9bad02014-06-19 11:05:39 -0700472 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700473 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700474 }
475 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700476 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700477 }
478 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700479 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700480 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000481 info->fLastGlyphID = face->num_glyphs - 1;
482 info->fEmSize = 1000;
483
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000484 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000485 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000486 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000487 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000488 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000489 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000490 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000491 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000492 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000493 TT_Header* ttHeader;
bungemanf1491692016-07-22 11:19:24 -0700494 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000495 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000496 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000497 } else {
498 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000499 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000500
halcanary32875882016-08-16 09:36:23 -0700501 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700502 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000503 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700504 }
505 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000506 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700507 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000508
bungemanf1491692016-07-22 11:19:24 -0700509 PS_FontInfoRec psFontInfo;
510 TT_Postscript* postTable;
511 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
512 info->fItalicAngle = psFontInfo.italic_angle;
513 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
514 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000515 } else {
516 info->fItalicAngle = 0;
517 }
518
519 info->fAscent = face->ascender;
520 info->fDescent = face->descender;
521
522 // Figure out a good guess for StemV - Min width of i, I, !, 1.
523 // This probably isn't very good with an italic font.
524 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000525 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000526 char stem_chars[] = {'i', 'I', '!', '1'};
527 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
528 FT_BBox bbox;
529 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
530 int16_t width = bbox.xMax - bbox.xMin;
531 if (width > 0 && width < min_width) {
532 min_width = width;
533 info->fStemV = min_width;
534 }
535 }
536 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000537
bungemanf1491692016-07-22 11:19:24 -0700538 TT_PCLT* pcltTable;
539 TT_OS2* os2Table;
540 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
541 info->fCapHeight = pcltTable->CapHeight;
542 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
543 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000544 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700545 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000546 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700547 }
548 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000549 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700550 os2Table->version != 0xFFFF &&
551 os2Table->version >= 2)
552 {
553 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000554 } else {
555 // Figure out a good guess for CapHeight: average the height of M and X.
556 FT_BBox m_bbox, x_bbox;
557 bool got_m, got_x;
558 got_m = GetLetterCBox(face, 'M', &m_bbox);
559 got_x = GetLetterCBox(face, 'X', &x_bbox);
560 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700561 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000562 } else if (got_m && !got_x) {
563 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
564 } else if (!got_m && got_x) {
565 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000566 } else {
567 // Last resort, use the ascent.
568 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000569 }
570 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000571
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000572 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
573 face->bbox.xMax, face->bbox.yMin);
574
vandebo0f9bad02014-06-19 11:05:39 -0700575 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700576 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000577 }
578
reed39a9a502015-05-12 09:50:04 -0700579 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700580 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
581 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000582 // Postscript fonts may contain more than 255 glyphs, so we end up
583 // using multiple font descriptions with a glyph ordering. Record
584 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700585 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000586 for (int gID = 0; gID < face->num_glyphs; gID++) {
587 char glyphName[128]; // PS limit for names is 127 bytes.
588 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700589 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000590 }
591 }
592
reed39a9a502015-05-12 09:50:04 -0700593 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700594 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
595 face->num_charmaps)
596 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000597 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
598 }
599
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000600 return info;
601}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000602
reed@google.com618ef5e2011-01-26 22:10:41 +0000603///////////////////////////////////////////////////////////////////////////
604
reed@google.com8ed436c2011-07-21 14:12:36 +0000605static bool bothZero(SkScalar a, SkScalar b) {
606 return 0 == a && 0 == b;
607}
608
609// returns false if there is any non-90-rotation or skew
610static bool isAxisAligned(const SkScalerContext::Rec& rec) {
611 return 0 == rec.fPreSkewX &&
612 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
613 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
614}
615
reeda9322c22016-04-12 06:47:05 -0700616SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
617 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -0400618 auto c = skstd::make_unique<SkScalerContext_FreeType>(
619 sk_ref_sp(const_cast<SkTypeface_FreeType*>(this)), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000620 if (!c->success()) {
Ben Wagnerc05b2bf2016-11-03 16:51:26 -0400621 return nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000622 }
bungeman7cfd46a2016-10-20 16:06:52 -0400623 return c.release();
reed@google.com0da48612013-03-19 16:06:52 +0000624}
625
626void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000627 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
628 //Cap the requested size as larger sizes give bogus values.
629 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800630 //Note that this also currently only protects against large text size requests,
631 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000632 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000633 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000634 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000635
bungemanec7e12f2015-01-21 11:55:16 -0800636 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800637 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
638 SkAutoMutexAcquire ama(gFTMutex);
639 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800640 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800641 // If the runtime Freetype library doesn't support LCD, disable it here.
642 rec->fMaskFormat = SkMask::kA8_Format;
643 }
644 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000645 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000646
reed@google.com618ef5e2011-01-26 22:10:41 +0000647 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000648 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000649 // collapse full->normal hinting if we're not doing LCD
650 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000651 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000652 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000653 if (SkPaint::kNo_Hinting != h) {
654 h = SkPaint::kSlight_Hinting;
655 }
656 }
657
reed@google.com8ed436c2011-07-21 14:12:36 +0000658 // rotated text looks bad with hinting, so we disable it as needed
659 if (!isAxisAligned(*rec)) {
660 h = SkPaint::kNo_Hinting;
661 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000662 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000663
bungeman@google.com97efada2012-07-30 20:40:50 +0000664#ifndef SK_GAMMA_APPLY_TO_A8
665 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700666 // SRGBTODO: Is this correct? Do we want contrast boost?
667 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000668 }
reed@google.com1ac83502012-02-28 17:06:02 +0000669#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000670}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000671
reed@google.com38c37dd2013-03-21 15:36:26 +0000672int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000673 AutoFTAccess fta(this);
674 FT_Face face = fta.face();
675 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000676}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000677
reed@google.com35fe7372013-10-30 15:07:03 +0000678bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
679 int count, int32_t adjustments[]) const {
680 AutoFTAccess fta(this);
681 FT_Face face = fta.face();
682 if (!face || !FT_HAS_KERNING(face)) {
683 return false;
684 }
685
686 for (int i = 0; i < count - 1; ++i) {
687 FT_Vector delta;
688 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
689 FT_KERNING_UNSCALED, &delta);
690 if (err) {
691 return false;
692 }
693 adjustments[i] = delta.x;
694 }
695 return true;
696}
697
bungeman401ae2d2016-07-18 15:46:27 -0700698/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800699static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700700 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700701 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000702 return -1;
703 }
bungeman401ae2d2016-07-18 15:46:27 -0700704
705 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000706 FT_Int chosenStrikeIndex = -1;
707 FT_Pos chosenPPEM = 0;
708 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700709 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
710 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000711 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700712 return strikeIndex;
713 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000714 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700715 if (chosenPPEM < strikePPEM) {
716 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000717 chosenStrikeIndex = strikeIndex;
718 }
719 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700720 // attempt to decrease chosenPPEM, but not below requestedPPEM
721 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
722 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000723 chosenStrikeIndex = strikeIndex;
724 }
725 }
726 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000727 return chosenStrikeIndex;
728}
729
bungeman7cfd46a2016-10-20 16:06:52 -0400730SkScalerContext_FreeType::SkScalerContext_FreeType(sk_sp<SkTypeface> typeface,
reeda9322c22016-04-12 06:47:05 -0700731 const SkScalerContextEffects& effects,
732 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400733 : SkScalerContext_FreeType_Base(std::move(typeface), effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800734 , fFace(nullptr)
735 , fFTSize(nullptr)
736 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700737{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000738 SkAutoMutexAcquire ac(gFTMutex);
739
bungeman9dc24682014-12-01 14:01:32 -0800740 if (!ref_ft_library()) {
741 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000742 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000743
744 // load the font file
bungemanaabd71c2016-03-01 15:15:09 -0800745 using UnrefFTFace = SkFunctionWrapper<void, skstd::remove_pointer_t<FT_Face>, unref_ft_face>;
bungeman7cfd46a2016-10-20 16:06:52 -0400746 using FT_FaceRef = skstd::remove_pointer_t<FT_Face>;
747 std::unique_ptr<FT_FaceRef, UnrefFTFace> ftFace(ref_ft_face(this->getTypeface()));
bungemanaabd71c2016-03-01 15:15:09 -0800748 if (nullptr == ftFace) {
749 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000750 return;
751 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000752
bungeman5f14c5e2014-12-05 12:26:44 -0800753 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000754
bungeman401ae2d2016-07-18 15:46:27 -0700755 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
756 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000757 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700758 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
759 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000760 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000761
reed@google.coma1bfa212012-03-08 21:57:12 +0000762 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
763
reed@android.com8a1c16f2008-12-17 15:59:43 +0000764 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000765 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000766 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000767 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000768
agl@chromium.org70a303f2010-05-10 14:15:50 +0000769 if (SkMask::kBW_Format == fRec.fMaskFormat) {
770 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
771 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000772 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000773 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000774 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000775 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000776 } else {
777 switch (fRec.getHinting()) {
778 case SkPaint::kNo_Hinting:
779 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000780 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000781 break;
782 case SkPaint::kSlight_Hinting:
783 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
784 break;
785 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000786 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000787 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700788#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
789 } else {
790 loadFlags = FT_LOAD_NO_AUTOHINT;
791#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000792 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000793 break;
794 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000795 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000796 loadFlags = FT_LOAD_FORCE_AUTOHINT;
797 break;
798 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000799 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000800 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000801 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000802 loadFlags = FT_LOAD_TARGET_LCD_V;
803 } else {
804 loadFlags = FT_LOAD_TARGET_LCD;
805 }
reed@google.comea2333d2011-03-14 16:44:56 +0000806 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000807 break;
808 default:
809 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
810 break;
811 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000812 }
813
reed@google.comeffc5012011-06-27 16:44:46 +0000814 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000815 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000816 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000817
reed@google.com96a9f7912011-05-06 11:49:30 +0000818 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
819 // advances, as fontconfig and cairo do.
820 // See http://code.google.com/p/skia/issues/detail?id=222.
821 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
822
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000823 // Use vertical layout if requested.
824 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
825 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
826 }
827
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000828 loadFlags |= FT_LOAD_COLOR;
829
reed@android.come4d0bc02009-07-24 19:53:20 +0000830 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000831 }
832
bungemanaabd71c2016-03-01 15:15:09 -0800833 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
mtklein5f939ab2016-03-16 10:28:35 -0700834 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([&ftFace]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800835 FT_Size size;
836 FT_Error err = FT_New_Size(ftFace.get(), &size);
837 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700838 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800839 return nullptr;
840 }
841 return size;
842 }());
843 if (nullptr == ftSize) {
844 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000845 return;
846 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847
bungemanaabd71c2016-03-01 15:15:09 -0800848 FT_Error err = FT_Activate_Size(ftSize.get());
849 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700850 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800851 return;
852 }
853
854 if (FT_IS_SCALABLE(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700855 err = FT_Set_Char_Size(ftFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000856 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700857 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
858 ftFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000859 return;
860 }
bungemanaabd71c2016-03-01 15:15:09 -0800861 } else if (FT_HAS_FIXED_SIZES(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700862 fStrikeIndex = chooseBitmapStrike(ftFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000863 if (fStrikeIndex == -1) {
bungeman401ae2d2016-07-18 15:46:27 -0700864 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n", ftFace->family_name, fScale.fY));
865 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000866 }
bungeman401ae2d2016-07-18 15:46:27 -0700867
868 err = FT_Select_Size(ftFace.get(), fStrikeIndex);
869 if (err != 0) {
870 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
871 ftFace->family_name, fStrikeIndex, err));
872 fStrikeIndex = -1;
873 return;
874 }
875
876 // A non-ideal size was picked, so recompute the matrix.
877 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
878 fMatrix22Scalar.preScale(fScale.x() / ftFace->size->metrics.x_ppem,
879 fScale.y() / ftFace->size->metrics.y_ppem);
880 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
881 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
882 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
883 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
884
885 // FreeType does not provide linear metrics for bitmap fonts.
886 linearMetrics = false;
887
888 // FreeType documentation says:
889 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
890 // Bitmap-only fonts ignore this flag.
891 //
892 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
893 // Force this flag off for bitmap only fonts.
894 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000895 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700896 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFace->family_name, fScale.fY));
897 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000898 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000899
bungemanaabd71c2016-03-01 15:15:09 -0800900 fFTSize = ftSize.release();
901 fFace = ftFace.release();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000902 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000903}
904
905SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000906 SkAutoMutexAcquire ac(gFTMutex);
907
halcanary96fcdcc2015-08-27 07:41:13 -0700908 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000909 FT_Done_Size(fFTSize);
910 }
911
halcanary96fcdcc2015-08-27 07:41:13 -0700912 if (fFace != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000913 unref_ft_face(fFace);
914 }
bungeman9dc24682014-12-01 14:01:32 -0800915
916 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000917}
918
919/* We call this before each use of the fFace, since we may be sharing
920 this face with other context (at different sizes).
921*/
922FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800923 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000924 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000926 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000927 }
halcanary96fcdcc2015-08-27 07:41:13 -0700928 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000929 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000930}
931
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000932unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000933 return fFace->num_glyphs;
934}
935
936uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -0800937 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000938 return SkToU16(FT_Get_Char_Index( fFace, uni ));
939}
940
reed@android.com9d3a9852010-01-08 14:07:42 +0000941SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -0800942 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +0000943 // iterate through each cmap entry, looking for matching glyph indices
944 FT_UInt glyphIndex;
945 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
946
947 while (glyphIndex != 0) {
948 if (glyphIndex == glyph) {
949 return charCode;
950 }
951 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
952 }
953
954 return 0;
955}
956
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700957static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
958 return SkFixedToScalar(x);
959}
960
reed@android.com8a1c16f2008-12-17 15:59:43 +0000961void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000962 /* unhinted and light hinted text have linearly scaled advances
963 * which are very cheap to compute with some font formats...
964 */
reed@google.combdc99882011-11-21 14:36:57 +0000965 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000966 SkAutoMutexAcquire ac(gFTMutex);
967
968 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000969 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000970 return;
971 }
972
973 FT_Error error;
974 FT_Fixed advance;
975
djsollen1b277042014-08-06 06:58:06 -0700976 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +0000977 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
978 &advance );
979 if (0 == error) {
980 glyph->fRsbDelta = 0;
981 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700982 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
983 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -0700984 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000985 return;
986 }
987 }
bungeman5ec443c2014-11-21 13:18:34 -0800988
reed@android.com8a1c16f2008-12-17 15:59:43 +0000989 /* otherwise, we need to load/hint the glyph, which is slower */
990 this->generateMetrics(glyph);
991 return;
992}
993
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000994void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
995 FT_BBox* bbox,
996 bool snapToPixelBoundary) {
997
998 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
999
1000 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001001 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1002 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001003 // negate dy since freetype-y-goes-up and skia-y-goes-down
1004 bbox->xMin += dx;
1005 bbox->yMin -= dy;
1006 bbox->xMax += dx;
1007 bbox->yMax -= dy;
1008 }
1009
1010 // outset the box to integral boundaries
1011 if (snapToPixelBoundary) {
1012 bbox->xMin &= ~63;
1013 bbox->yMin &= ~63;
1014 bbox->xMax = (bbox->xMax + 63) & ~63;
1015 bbox->yMax = (bbox->yMax + 63) & ~63;
1016 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001017
1018 // Must come after snapToPixelBoundary so that the width and height are
1019 // consistent. Otherwise asserts will fire later on when generating the
1020 // glyph image.
1021 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1022 FT_Vector vector;
1023 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1024 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1025 FT_Vector_Transform(&vector, &fMatrix22);
1026 bbox->xMin += vector.x;
1027 bbox->xMax += vector.x;
1028 bbox->yMin += vector.y;
1029 bbox->yMax += vector.y;
1030 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001031}
1032
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001033bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1034 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001035 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001036 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001037 }
1038 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001039 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001040 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001041 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001042 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1043 return true;
1044}
1045
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001046void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1047 if (isLCD(fRec)) {
1048 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001049 glyph->fHeight += gFTLibrary->lcdExtra();
1050 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001051 } else {
bungeman9dc24682014-12-01 14:01:32 -08001052 glyph->fWidth += gFTLibrary->lcdExtra();
1053 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001054 }
1055 }
1056}
1057
bungeman401ae2d2016-07-18 15:46:27 -07001058bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1059 // If subpixel rendering of a bitmap *can* be done.
1060 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1061 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1062 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001063
bungeman401ae2d2016-07-18 15:46:27 -07001064 // If subpixel rendering of a bitmap *should* be done.
1065 // 1. If the face is not scalable then always allow subpixel rendering.
1066 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1067 // 2. If the matrix is already not identity the bitmap will already be resampled,
1068 // so resampling slightly differently shouldn't make much difference.
1069 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1070
1071 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001072}
1073
reed@android.com8a1c16f2008-12-17 15:59:43 +00001074void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1075 SkAutoMutexAcquire ac(gFTMutex);
1076
1077 glyph->fRsbDelta = 0;
1078 glyph->fLsbDelta = 0;
1079
1080 FT_Error err;
1081
1082 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001083 glyph->zeroMetrics();
1084 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001085 }
1086
djsollen1b277042014-08-06 06:58:06 -07001087 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001088 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001089 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001090 return;
1091 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001092 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001093
1094 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001095 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001096 if (0 == fFace->glyph->outline.n_contours) {
1097 glyph->fWidth = 0;
1098 glyph->fHeight = 0;
1099 glyph->fTop = 0;
1100 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001101 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001102 FT_BBox bbox;
1103 getBBoxForCurrentGlyph(glyph, &bbox, true);
1104
1105 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1106 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1107 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1108 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1109
1110 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001111 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001112 break;
1113
1114 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001115 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1116 FT_Vector vector;
1117 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1118 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1119 FT_Vector_Transform(&vector, &fMatrix22);
1120 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1121 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1122 }
1123
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001124 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1125 glyph->fMaskFormat = SkMask::kARGB32_Format;
1126 }
1127
bungeman401ae2d2016-07-18 15:46:27 -07001128 {
1129 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1130 -SkIntToScalar(fFace->glyph->bitmap_top),
1131 SkIntToScalar(fFace->glyph->bitmap.width),
1132 SkIntToScalar(fFace->glyph->bitmap.rows));
1133 fMatrix22Scalar.mapRect(&rect);
1134 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1135 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1136 SkFixedToScalar(glyph->getSubYFixed()));
1137 }
1138 SkIRect irect = rect.roundOut();
1139 glyph->fWidth = SkToU16(irect.width());
1140 glyph->fHeight = SkToU16(irect.height());
1141 glyph->fTop = SkToS16(irect.top());
1142 glyph->fLeft = SkToS16(irect.left());
1143 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001144 break;
1145
1146 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001147 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001148 glyph->zeroMetrics();
1149 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001150 }
1151
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001152 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1153 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001154 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001155 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001156 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001157 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001158 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1159 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001160 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001161 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001162 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001163 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1164 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001165 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001166 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001167 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1168 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001169
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001170 if (fRec.fFlags & kDevKernText_Flag) {
1171 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1172 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001173 }
1174 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001175 }
1176
reed@android.com8a1c16f2008-12-17 15:59:43 +00001177#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001178 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001179#endif
1180}
1181
bungeman5ec443c2014-11-21 13:18:34 -08001182static void clear_glyph_image(const SkGlyph& glyph) {
1183 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1184}
reed@google.comea2333d2011-03-14 16:44:56 +00001185
bungeman@google.coma76de722012-10-26 19:35:54 +00001186void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001187 SkAutoMutexAcquire ac(gFTMutex);
1188
reed@android.com8a1c16f2008-12-17 15:59:43 +00001189 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001190 clear_glyph_image(glyph);
1191 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001192 }
1193
bungeman5ec443c2014-11-21 13:18:34 -08001194 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195 if (err != 0) {
1196 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
bungeman5ec443c2014-11-21 13:18:34 -08001197 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1198 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001199 return;
1200 }
1201
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001202 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001203 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1204 SkMatrix subpixelBitmapMatrix;
1205 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1206 subpixelBitmapMatrix = fMatrix22Scalar;
1207 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1208 SkFixedToScalar(glyph.getSubYFixed()));
1209 bitmapMatrix = &subpixelBitmapMatrix;
1210 }
1211 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001212}
1213
reed@android.com8a1c16f2008-12-17 15:59:43 +00001214
bungeman5ec443c2014-11-21 13:18:34 -08001215void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001216 SkAutoMutexAcquire ac(gFTMutex);
1217
caryclarka10742c2014-09-18 11:00:40 -07001218 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001219
1220 if (this->setupSize()) {
1221 path->reset();
1222 return;
1223 }
1224
1225 uint32_t flags = fLoadGlyphFlags;
1226 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1227 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1228
djsollen1b277042014-08-06 06:58:06 -07001229 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001230
1231 if (err != 0) {
1232 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001233 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001234 path->reset();
1235 return;
1236 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001237 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001238
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001239 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001240
1241 // The path's origin from FreeType is always the horizontal layout origin.
1242 // Offset the path so that it is relative to the vertical origin if needed.
1243 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1244 FT_Vector vector;
1245 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1246 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1247 FT_Vector_Transform(&vector, &fMatrix22);
1248 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1249 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001250}
1251
bungeman41078062014-07-07 08:16:37 -07001252void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001253 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001254 return;
1255 }
1256
bungeman41078062014-07-07 08:16:37 -07001257 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001258
1259 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001260 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001261 return;
1262 }
1263
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001264 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001265
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001266 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1267 SkScalar upem = SkIntToScalar(face->units_per_EM);
1268 if (!upem) {
1269 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1270 if (ttHeader) {
1271 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001272 }
1273 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001274
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001275 // use the os/2 table as a source of reasonable defaults.
1276 SkScalar x_height = 0.0f;
1277 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001278 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001279 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1280 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001281 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001282 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001283 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001284 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001285 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001286 }
1287
1288 // pull from format-specific metrics as needed
1289 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001290 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001291 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001292 // FreeType will always use HHEA metrics if they're not zero.
1293 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1294 // It also ignores the VDMX tables, which are also of interest here
1295 // (and override everything else when they apply).
1296 static const int kUseTypoMetricsMask = (1 << 7);
1297 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1298 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1299 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1300 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1301 } else {
1302 ascent = -SkIntToScalar(face->ascender) / upem;
1303 descent = -SkIntToScalar(face->descender) / upem;
1304 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1305 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001306 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1307 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1308 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1309 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001310 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001311 underlinePosition = -SkIntToScalar(face->underline_position +
1312 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001313
bungeman41078062014-07-07 08:16:37 -07001314 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1315 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1316
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001317 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001318 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001319 FT_BBox bbox;
1320 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001321 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1322 }
1323 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001324 if (!cap_height) {
1325 FT_BBox bbox;
1326 if (getCBoxForLetter('H', &bbox)) {
1327 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1328 }
1329 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001330 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1331 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1332 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1333 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1334 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001335 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001336 xmin = 0.0f;
1337 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1338 ymin = descent + leading;
1339 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001340 underlineThickness = 0;
1341 underlinePosition = 0;
1342
bungeman41078062014-07-07 08:16:37 -07001343 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1344 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001345 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001346 sk_bzero(metrics, sizeof(*metrics));
1347 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001348 }
1349
1350 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1351 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001352 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001353 }
1354 if (!avgCharWidth) {
1355 avgCharWidth = xmax - xmin;
1356 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001357 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001358 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001359 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001360
1361 // disallow negative linespacing
1362 if (leading < 0.0f) {
1363 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001364 }
1365
bungeman53790512016-07-21 13:32:09 -07001366 metrics->fTop = ymax * fScale.y();
1367 metrics->fAscent = ascent * fScale.y();
1368 metrics->fDescent = descent * fScale.y();
1369 metrics->fBottom = ymin * fScale.y();
1370 metrics->fLeading = leading * fScale.y();
1371 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1372 metrics->fXMin = xmin * fScale.y();
1373 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001374 metrics->fXHeight = x_height;
1375 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001376 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1377 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001378}
1379
djsollenfcfea992015-01-09 08:18:13 -08001380///////////////////////////////////////////////////////////////////////////////
1381
1382// hand-tuned value to reduce outline embolden strength
1383#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1384 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1385 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1386 #else
1387 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1388 #endif
1389#endif
1390
1391///////////////////////////////////////////////////////////////////////////////
1392
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001393void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1394{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001395 // check to see if the embolden bit is set
1396 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1397 return;
1398 }
1399
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001400 switch (glyph->format) {
1401 case FT_GLYPH_FORMAT_OUTLINE:
1402 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001403 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1404 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001405 FT_Outline_Embolden(&glyph->outline, strength);
1406 break;
1407 case FT_GLYPH_FORMAT_BITMAP:
1408 FT_GlyphSlot_Own_Bitmap(glyph);
1409 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1410 break;
1411 default:
1412 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001413 }
1414}
1415
reed@google.comb4162b12013-07-02 16:32:29 +00001416///////////////////////////////////////////////////////////////////////////////
1417
1418#include "SkUtils.h"
1419
1420static SkUnichar next_utf8(const void** chars) {
1421 return SkUTF8_NextUnichar((const char**)chars);
1422}
1423
1424static SkUnichar next_utf16(const void** chars) {
1425 return SkUTF16_NextUnichar((const uint16_t**)chars);
1426}
1427
1428static SkUnichar next_utf32(const void** chars) {
1429 const SkUnichar** uniChars = (const SkUnichar**)chars;
1430 SkUnichar uni = **uniChars;
1431 *uniChars += 1;
1432 return uni;
1433}
1434
1435typedef SkUnichar (*EncodingProc)(const void**);
1436
1437static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1438 static const EncodingProc gProcs[] = {
1439 next_utf8, next_utf16, next_utf32
1440 };
1441 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1442 return gProcs[enc];
1443}
1444
1445int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001446 uint16_t glyphs[], int glyphCount) const
1447{
reed@google.comb4162b12013-07-02 16:32:29 +00001448 AutoFTAccess fta(this);
1449 FT_Face face = fta.face();
1450 if (!face) {
1451 if (glyphs) {
1452 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1453 }
1454 return 0;
1455 }
1456
1457 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1458
halcanary96fcdcc2015-08-27 07:41:13 -07001459 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001460 for (int i = 0; i < glyphCount; ++i) {
1461 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1462 return i;
1463 }
1464 }
1465 return glyphCount;
1466 } else {
1467 int first = glyphCount;
1468 for (int i = 0; i < glyphCount; ++i) {
1469 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1470 glyphs[i] = SkToU16(id);
1471 if (0 == id && i < first) {
1472 first = i;
1473 }
1474 }
1475 return first;
1476 }
1477}
1478
1479int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001480 AutoFTAccess fta(this);
1481 FT_Face face = fta.face();
1482 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001483}
1484
bungeman@google.com839702b2013-08-07 17:09:22 +00001485SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001486 SkTypeface::LocalizedStrings* nameIter =
1487 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001488 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001489 SkString familyName;
1490 this->getFamilyName(&familyName);
1491 SkString language("und"); //undetermined
1492 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1493 }
1494 return nameIter;
1495}
1496
bungeman@google.comddc218e2013-08-01 22:29:43 +00001497int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1498 AutoFTAccess fta(this);
1499 FT_Face face = fta.face();
1500
1501 FT_ULong tableCount = 0;
1502 FT_Error error;
1503
halcanary96fcdcc2015-08-27 07:41:13 -07001504 // When 'tag' is nullptr, returns number of tables in 'length'.
1505 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001506 if (error) {
1507 return 0;
1508 }
1509
1510 if (tags) {
1511 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1512 FT_ULong tableTag;
1513 FT_ULong tablelength;
1514 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1515 if (error) {
1516 return 0;
1517 }
1518 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1519 }
1520 }
1521 return tableCount;
1522}
1523
1524size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1525 size_t length, void* data) const
1526{
1527 AutoFTAccess fta(this);
1528 FT_Face face = fta.face();
1529
1530 FT_ULong tableLength = 0;
1531 FT_Error error;
1532
1533 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001534 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001535 if (error) {
1536 return 0;
1537 }
1538
1539 if (offset > tableLength) {
1540 return 0;
1541 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001542 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001543 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001544 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1545 if (error) {
1546 return 0;
1547 }
1548 }
1549
1550 return size;
1551}
1552
reed@google.comb4162b12013-07-02 16:32:29 +00001553///////////////////////////////////////////////////////////////////////////////
1554///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001555
halcanary96fcdcc2015-08-27 07:41:13 -07001556SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001557 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1558 return;
bungeman14df8332014-10-28 15:07:23 -07001559 }
bungeman9dc24682014-12-01 14:01:32 -08001560 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001561}
1562SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001563 if (fLibrary) {
1564 FT_Done_Library(fLibrary);
1565 }
bungeman14df8332014-10-28 15:07:23 -07001566}
1567
bungemanf93d7112016-09-16 06:24:20 -07001568FT_Face SkTypeface_FreeType::Scanner::openFace(SkStreamAsset* stream, int ttcIndex,
bungeman14df8332014-10-28 15:07:23 -07001569 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001570{
halcanary96fcdcc2015-08-27 07:41:13 -07001571 if (fLibrary == nullptr) {
1572 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001573 }
1574
bungeman14df8332014-10-28 15:07:23 -07001575 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001576 memset(&args, 0, sizeof(args));
1577
1578 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001579
bsalomon49f085d2014-09-05 13:34:00 -07001580 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001581 args.flags = FT_OPEN_MEMORY;
1582 args.memory_base = (const FT_Byte*)memoryBase;
1583 args.memory_size = stream->getLength();
1584 } else {
bungeman14df8332014-10-28 15:07:23 -07001585 memset(ftStream, 0, sizeof(*ftStream));
1586 ftStream->size = stream->getLength();
1587 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001588 ftStream->read = sk_ft_stream_io;
1589 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001590
1591 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001592 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001593 }
1594
1595 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001596 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001597 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001598 }
1599 return face;
1600}
1601
bungemanf93d7112016-09-16 06:24:20 -07001602bool SkTypeface_FreeType::Scanner::recognizedFont(SkStreamAsset* stream, int* numFaces) const {
bungeman14df8332014-10-28 15:07:23 -07001603 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1604
1605 FT_StreamRec streamRec;
1606 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001607 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001608 return false;
1609 }
1610
1611 *numFaces = face->num_faces;
1612
1613 FT_Done_Face(face);
1614 return true;
1615}
1616
1617#include "SkTSearch.h"
1618bool SkTypeface_FreeType::Scanner::scanFont(
bungemanf93d7112016-09-16 06:24:20 -07001619 SkStreamAsset* stream, int ttcIndex,
bungeman41868fe2015-05-20 09:21:04 -07001620 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001621{
1622 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1623
1624 FT_StreamRec streamRec;
1625 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001626 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001627 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001628 }
1629
bungemana4c4a2d2014-10-20 13:33:19 -07001630 int weight = SkFontStyle::kNormal_Weight;
1631 int width = SkFontStyle::kNormal_Width;
1632 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001633 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001634 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001635 }
1636 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001637 slant = SkFontStyle::kItalic_Slant;
1638 }
1639
1640 PS_FontInfoRec psFontInfo;
1641 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1642 if (os2 && os2->version != 0xffff) {
1643 weight = os2->usWeightClass;
1644 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001645
1646 // OS/2::fsSelection bit 9 indicates oblique.
1647 if (SkToBool(os2->fsSelection & (1u << 9))) {
1648 slant = SkFontStyle::kOblique_Slant;
1649 }
bungemana4c4a2d2014-10-20 13:33:19 -07001650 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1651 static const struct {
1652 char const * const name;
1653 int const weight;
1654 } commonWeights [] = {
1655 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001656 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001657 { "black", SkFontStyle::kBlack_Weight },
1658 { "bold", SkFontStyle::kBold_Weight },
1659 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1660 { "demi", SkFontStyle::kSemiBold_Weight },
1661 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001662 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001663 { "extrabold", SkFontStyle::kExtraBold_Weight },
1664 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001665 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001666 { "heavy", SkFontStyle::kBlack_Weight },
1667 { "light", SkFontStyle::kLight_Weight },
1668 { "medium", SkFontStyle::kMedium_Weight },
1669 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001670 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001671 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001672 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001673 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001674 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001675 { "thin", SkFontStyle::kThin_Weight },
1676 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001677 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001678 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001679 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001680 { "ultralight", SkFontStyle::kExtraLight_Weight },
1681 };
1682 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001683 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001684 if (index >= 0) {
1685 weight = commonWeights[index].weight;
1686 } else {
bungeman14df8332014-10-28 15:07:23 -07001687 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001688 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001689 }
1690
1691 if (name) {
1692 name->set(face->family_name);
1693 }
1694 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001695 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001696 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001697 if (isFixedPitch) {
1698 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001699 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001700
bungeman41868fe2015-05-20 09:21:04 -07001701 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001702 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001703 FT_Error err = FT_Get_MM_Var(face, &variations);
1704 if (err) {
1705 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1706 face->family_name));
1707 return false;
1708 }
1709 SkAutoFree autoFreeVariations(variations);
1710
1711 axes->reset(variations->num_axis);
1712 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1713 const FT_Var_Axis& ftAxis = variations->axis[i];
1714 (*axes)[i].fTag = ftAxis.tag;
1715 (*axes)[i].fMinimum = ftAxis.minimum;
1716 (*axes)[i].fDefault = ftAxis.def;
1717 (*axes)[i].fMaximum = ftAxis.maximum;
1718 }
1719 }
bungeman41868fe2015-05-20 09:21:04 -07001720
reed@android.com8a1c16f2008-12-17 15:59:43 +00001721 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001722 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001723}
bungemanf6c71072016-01-21 14:17:47 -08001724
1725/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1726 AxisDefinitions axisDefinitions,
1727 const SkFontMgr::FontParameters::Axis* requestedAxes, int requestedAxisCount,
1728 SkFixed* axisValues,
1729 const SkString& name)
1730{
1731 for (int i = 0; i < axisDefinitions.count(); ++i) {
1732 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001733 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1734 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001735 axisValues[i] = axisDefinition.fDefault;
1736 for (int j = 0; j < requestedAxisCount; ++j) {
1737 const SkFontMgr::FontParameters::Axis& axisSpecified = requestedAxes[j];
1738 if (axisDefinition.fTag == axisSpecified.fTag) {
benjaminwagner64a3c952016-02-25 12:20:40 -08001739 const SkScalar axisValue = SkTPin(axisSpecified.fStyleValue, axisMin, axisMax);
1740 if (axisSpecified.fStyleValue != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001741 SkDEBUGF(("Requested font axis value out of range: "
1742 "%s '%c%c%c%c' %f; pinned to %f.\n",
1743 name.c_str(),
1744 (axisDefinition.fTag >> 24) & 0xFF,
1745 (axisDefinition.fTag >> 16) & 0xFF,
1746 (axisDefinition.fTag >> 8) & 0xFF,
1747 (axisDefinition.fTag ) & 0xFF,
1748 SkScalarToDouble(axisSpecified.fStyleValue),
benjaminwagner64a3c952016-02-25 12:20:40 -08001749 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001750 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001751 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001752 break;
1753 }
1754 }
1755 // TODO: warn on defaulted axis?
1756 }
1757
1758 SkDEBUGCODE(
1759 // Check for axis specified, but not matched in font.
1760 for (int i = 0; i < requestedAxisCount; ++i) {
1761 SkFourByteTag skTag = requestedAxes[i].fTag;
1762 bool found = false;
1763 for (int j = 0; j < axisDefinitions.count(); ++j) {
1764 if (skTag == axisDefinitions[j].fTag) {
1765 found = true;
1766 break;
1767 }
1768 }
1769 if (!found) {
1770 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1771 name.c_str(),
1772 (skTag >> 24) & 0xFF,
1773 (skTag >> 16) & 0xFF,
1774 (skTag >> 8) & 0xFF,
1775 (skTag) & 0xFF));
1776 }
1777 }
1778 )
1779}