blob: 84a74af469b35b81f01d9fb168982065f478092b [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"
reed@android.com8a1c16f2008-12-17 15:59:43 +000017#include "SkMask.h"
bungeman@google.com97efada2012-07-30 20:40:50 +000018#include "SkMaskGamma.h"
bungeman@google.comd3fbd342014-04-15 15:52:07 +000019#include "SkMatrix22.h"
mtklein1b249332015-07-07 12:21:21 -070020#include "SkMutex.h"
bungeman@google.coma9802692013-08-07 02:45:25 +000021#include "SkOTUtils.h"
bungemand3ebb482015-08-05 13:57:49 -070022#include "SkPath.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000023#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000024#include "SkStream.h"
25#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000026#include "SkTemplates.h"
bungeman9dc24682014-12-01 14:01:32 -080027#include "SkTypes.h"
mtklein5f939ab2016-03-16 10:28:35 -070028#include <memory>
reed@android.com8a1c16f2008-12-17 15:59:43 +000029
bungeman@google.comfd668cf2012-08-24 17:46:11 +000030#if defined(SK_CAN_USE_DLOPEN)
31#include <dlfcn.h>
32#endif
reed@android.com8a1c16f2008-12-17 15:59:43 +000033#include <ft2build.h>
bungeman5ec443c2014-11-21 13:18:34 -080034#include FT_ADVANCES_H
35#include FT_BITMAP_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000036#include FT_FREETYPE_H
bungeman5ec443c2014-11-21 13:18:34 -080037#include FT_LCD_FILTER_H
bungeman9dc24682014-12-01 14:01:32 -080038#include FT_MODULE_H
bungeman41868fe2015-05-20 09:21:04 -070039#include FT_MULTIPLE_MASTERS_H
reed@android.com8a1c16f2008-12-17 15:59:43 +000040#include FT_OUTLINE_H
41#include FT_SIZES_H
bungeman9dc24682014-12-01 14:01:32 -080042#include FT_SYSTEM_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000043#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000044#include FT_TYPE1_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000045#include FT_XFREE86_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000046
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +000047// FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA
48// were introduced in FreeType 2.5.0.
49// The following may be removed once FreeType 2.5.0 is required to build.
50#ifndef FT_LOAD_COLOR
51# define FT_LOAD_COLOR ( 1L << 20 )
52# define FT_PIXEL_MODE_BGRA 7
53#endif
54
reed@android.com8a1c16f2008-12-17 15:59:43 +000055//#define ENABLE_GLYPH_SPEW // for tracing calls
56//#define DUMP_STRIKE_CREATION
bungeman5ec443c2014-11-21 13:18:34 -080057//#define SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
58//#define SK_FONTHOST_FREETYPE_RUNTIME_VERSION
reed@google.com1ac83502012-02-28 17:06:02 +000059//#define SK_GAMMA_APPLY_TO_A8
reed@google.com1ac83502012-02-28 17:06:02 +000060
reed@google.comeffc5012011-06-27 16:44:46 +000061static bool isLCD(const SkScalerContext::Rec& rec) {
bungeman9dc24682014-12-01 14:01:32 -080062 return SkMask::kLCD16_Format == rec.fMaskFormat;
reed@google.comeffc5012011-06-27 16:44:46 +000063}
64
reed@android.com8a1c16f2008-12-17 15:59:43 +000065//////////////////////////////////////////////////////////////////////////
66
bungeman9dc24682014-12-01 14:01:32 -080067extern "C" {
68 static void* sk_ft_alloc(FT_Memory, long size) {
69 return sk_malloc_throw(size);
70 }
71 static void sk_ft_free(FT_Memory, void* block) {
72 sk_free(block);
73 }
74 static void* sk_ft_realloc(FT_Memory, long cur_size, long new_size, void* block) {
75 return sk_realloc_throw(block, new_size);
76 }
77};
halcanary96fcdcc2015-08-27 07:41:13 -070078FT_MemoryRec_ gFTMemory = { nullptr, sk_ft_alloc, sk_ft_free, sk_ft_realloc };
bungeman9dc24682014-12-01 14:01:32 -080079
80class FreeTypeLibrary : SkNoncopyable {
81public:
halcanary96fcdcc2015-08-27 07:41:13 -070082 FreeTypeLibrary() : fLibrary(nullptr), fIsLCDSupported(false), fLCDExtra(0) {
bungeman9dc24682014-12-01 14:01:32 -080083 if (FT_New_Library(&gFTMemory, &fLibrary)) {
84 return;
85 }
86 FT_Add_Default_Modules(fLibrary);
87
88 // Setup LCD filtering. This reduces color fringes for LCD smoothed glyphs.
89 // Default { 0x10, 0x40, 0x70, 0x40, 0x10 } adds up to 0x110, simulating ink spread.
90 // SetLcdFilter must be called before SetLcdFilterWeights.
91 if (FT_Library_SetLcdFilter(fLibrary, FT_LCD_FILTER_DEFAULT) == 0) {
92 fIsLCDSupported = true;
93 fLCDExtra = 2; //Using a filter adds one full pixel to each side.
94
95#ifdef SK_FONTHOST_FREETYPE_USE_NORMAL_LCD_FILTER
96 // Adds to 0x110 simulating ink spread, but provides better results than default.
97 static unsigned char gGaussianLikeHeavyWeights[] = { 0x1A, 0x43, 0x56, 0x43, 0x1A, };
98
99# if SK_FONTHOST_FREETYPE_RUNTIME_VERSION > 0x020400
100 FT_Library_SetLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
101# elif SK_CAN_USE_DLOPEN == 1
102 //The FreeType library is already loaded, so symbols are available in process.
halcanary96fcdcc2015-08-27 07:41:13 -0700103 void* self = dlopen(nullptr, RTLD_LAZY);
bungeman9dc24682014-12-01 14:01:32 -0800104 if (self) {
105 FT_Library_SetLcdFilterWeightsProc setLcdFilterWeights;
106 //The following cast is non-standard, but safe for POSIX.
107 *reinterpret_cast<void**>(&setLcdFilterWeights) =
108 dlsym(self, "FT_Library_SetLcdFilterWeights");
109 dlclose(self);
110
111 if (setLcdFilterWeights) {
112 setLcdFilterWeights(fLibrary, gGaussianLikeHeavyWeights);
113 }
114 }
115# endif
116#endif
117 }
118 }
119 ~FreeTypeLibrary() {
120 if (fLibrary) {
121 FT_Done_Library(fLibrary);
122 }
123 }
124
125 FT_Library library() { return fLibrary; }
126 bool isLCDSupported() { return fIsLCDSupported; }
127 int lcdExtra() { return fLCDExtra; }
128
129private:
130 FT_Library fLibrary;
131 bool fIsLCDSupported;
132 int fLCDExtra;
133
134 // FT_Library_SetLcdFilterWeights was introduced in FreeType 2.4.0.
135 // The following platforms provide FreeType of at least 2.4.0.
136 // Ubuntu >= 11.04 (previous deprecated April 2013)
137 // Debian >= 6.0 (good)
138 // OpenSuse >= 11.4 (previous deprecated January 2012 / Nov 2013 for Evergreen 11.2)
139 // Fedora >= 14 (good)
140 // Android >= Gingerbread (good)
141 typedef FT_Error (*FT_Library_SetLcdFilterWeightsProc)(FT_Library, unsigned char*);
142};
143
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144struct SkFaceRec;
145
reed086eea92016-05-04 17:12:46 -0700146SK_DECLARE_STATIC_MUTEX(gFTMutex);
bungeman9dc24682014-12-01 14:01:32 -0800147static FreeTypeLibrary* gFTLibrary;
148static SkFaceRec* gFaceRecHead;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000149
bungemanaabd71c2016-03-01 15:15:09 -0800150// Private to ref_ft_library and unref_ft_library
bungeman9dc24682014-12-01 14:01:32 -0800151static int gFTCount;
bungeman@google.comfd668cf2012-08-24 17:46:11 +0000152
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000153// Caller must lock gFTMutex before calling this function.
bungeman9dc24682014-12-01 14:01:32 -0800154static bool ref_ft_library() {
bungeman5ec443c2014-11-21 13:18:34 -0800155 gFTMutex.assertHeld();
bungeman9dc24682014-12-01 14:01:32 -0800156 SkASSERT(gFTCount >= 0);
bungeman5ec443c2014-11-21 13:18:34 -0800157
bungeman9dc24682014-12-01 14:01:32 -0800158 if (0 == gFTCount) {
halcanary96fcdcc2015-08-27 07:41:13 -0700159 SkASSERT(nullptr == gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700160 gFTLibrary = new FreeTypeLibrary;
reed@google.comea2333d2011-03-14 16:44:56 +0000161 }
bungeman9dc24682014-12-01 14:01:32 -0800162 ++gFTCount;
163 return gFTLibrary->library();
agl@chromium.org309485b2009-07-21 17:41:32 +0000164}
165
bungeman9dc24682014-12-01 14:01:32 -0800166// Caller must lock gFTMutex before calling this function.
167static void unref_ft_library() {
168 gFTMutex.assertHeld();
169 SkASSERT(gFTCount > 0);
commit-bot@chromium.orgba9354b2014-02-10 19:58:49 +0000170
bungeman9dc24682014-12-01 14:01:32 -0800171 --gFTCount;
172 if (0 == gFTCount) {
bungemanaabd71c2016-03-01 15:15:09 -0800173 SkASSERT(nullptr == gFaceRecHead);
halcanary96fcdcc2015-08-27 07:41:13 -0700174 SkASSERT(nullptr != gFTLibrary);
halcanary385fe4d2015-08-26 13:07:48 -0700175 delete gFTLibrary;
halcanary96fcdcc2015-08-27 07:41:13 -0700176 SkDEBUGCODE(gFTLibrary = nullptr;)
bungeman9dc24682014-12-01 14:01:32 -0800177 }
reed@google.comfb2fdcc2012-10-17 15:49:36 +0000178}
179
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000180class SkScalerContext_FreeType : public SkScalerContext_FreeType_Base {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000181public:
reeda9322c22016-04-12 06:47:05 -0700182 SkScalerContext_FreeType(SkTypeface*, const SkScalerContextEffects&, const SkDescriptor* desc);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000183 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000184
reed@android.com62900b42009-02-11 15:07:19 +0000185 bool success() const {
halcanary96fcdcc2015-08-27 07:41:13 -0700186 return fFTSize != nullptr && fFace != nullptr;
reed@android.com62900b42009-02-11 15:07:19 +0000187 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000188
189protected:
mtklein36352bf2015-03-25 18:17:31 -0700190 unsigned generateGlyphCount() override;
191 uint16_t generateCharToGlyph(SkUnichar uni) override;
192 void generateAdvance(SkGlyph* glyph) override;
193 void generateMetrics(SkGlyph* glyph) override;
194 void generateImage(const SkGlyph& glyph) override;
195 void generatePath(const SkGlyph& glyph, SkPath* path) override;
196 void generateFontMetrics(SkPaint::FontMetrics*) override;
197 SkUnichar generateGlyphToChar(uint16_t glyph) override;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000198
199private:
bungeman401ae2d2016-07-18 15:46:27 -0700200 FT_Face fFace; // Shared face from gFaceRecHead.
201 FT_Size fFTSize; // The size on the fFace for this scaler.
202 FT_Int fStrikeIndex;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000203
bungeman401ae2d2016-07-18 15:46:27 -0700204 /** The rest of the matrix after FreeType handles the size.
205 * With outline font rasterization this is handled by FreeType with FT_Set_Transform.
206 * With bitmap only fonts this matrix must be applied to scale the bitmap.
207 */
208 SkMatrix fMatrix22Scalar;
209 /** Same as fMatrix22Scalar, but in FreeType units and space. */
210 FT_Matrix fMatrix22;
211 /** The actual size requested. */
212 SkVector fScale;
213
214 uint32_t fLoadGlyphFlags;
215 bool fDoLinearMetrics;
216 bool fLCDIsVert;
reed@google.comf073b332013-05-06 12:21:16 +0000217
reed@android.com8a1c16f2008-12-17 15:59:43 +0000218 FT_Error setupSize();
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000219 void getBBoxForCurrentGlyph(SkGlyph* glyph, FT_BBox* bbox,
220 bool snapToPixelBoundary = false);
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000221 bool getCBoxForLetter(char letter, FT_BBox* bbox);
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000222 // Caller must lock gFTMutex before calling this function.
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000223 void updateGlyphIfLCD(SkGlyph* glyph);
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +0000224 // Caller must lock gFTMutex before calling this function.
225 // update FreeType2 glyph slot with glyph emboldened
226 void emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph);
bungeman401ae2d2016-07-18 15:46:27 -0700227 bool shouldSubpixelBitmap(const SkGlyph&, const SkMatrix&);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000228};
229
230///////////////////////////////////////////////////////////////////////////
231///////////////////////////////////////////////////////////////////////////
232
reed@android.com8a1c16f2008-12-17 15:59:43 +0000233struct SkFaceRec {
bungeman52b64b42015-01-27 10:41:17 -0800234 SkFaceRec* fNext;
235 FT_Face fFace;
236 FT_StreamRec fFTStream;
237 SkAutoTDelete<SkStreamAsset> fSkStream;
238 uint32_t fRefCnt;
239 uint32_t fFontID;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000240
scroggoa1193e42015-01-21 12:09:53 -0800241 // assumes ownership of the stream, will delete when its done
bungeman52b64b42015-01-27 10:41:17 -0800242 SkFaceRec(SkStreamAsset* strm, uint32_t fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000243};
244
245extern "C" {
bungeman52b64b42015-01-27 10:41:17 -0800246 static unsigned long sk_ft_stream_io(FT_Stream ftStream,
bungeman9dc24682014-12-01 14:01:32 -0800247 unsigned long offset,
248 unsigned char* buffer,
249 unsigned long count)
250 {
bungeman52b64b42015-01-27 10:41:17 -0800251 SkStreamAsset* stream = static_cast<SkStreamAsset*>(ftStream->descriptor.pointer);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000252
253 if (count) {
bungeman52b64b42015-01-27 10:41:17 -0800254 if (!stream->seek(offset)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000255 return 0;
bungeman9dc24682014-12-01 14:01:32 -0800256 }
bungeman52b64b42015-01-27 10:41:17 -0800257 count = stream->read(buffer, count);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000258 }
259 return count;
260 }
261
bungeman9dc24682014-12-01 14:01:32 -0800262 static void sk_ft_stream_close(FT_Stream) {}
reed@android.com8a1c16f2008-12-17 15:59:43 +0000263}
264
bungeman52b64b42015-01-27 10:41:17 -0800265SkFaceRec::SkFaceRec(SkStreamAsset* stream, uint32_t fontID)
halcanary96fcdcc2015-08-27 07:41:13 -0700266 : fNext(nullptr), fSkStream(stream), fRefCnt(1), fFontID(fontID)
bungeman52b64b42015-01-27 10:41:17 -0800267{
reed@android.com4516f472009-06-29 16:25:36 +0000268 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000269 fFTStream.size = fSkStream->getLength();
270 fFTStream.descriptor.pointer = fSkStream;
bungeman9dc24682014-12-01 14:01:32 -0800271 fFTStream.read = sk_ft_stream_io;
272 fFTStream.close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000273}
274
bungeman41868fe2015-05-20 09:21:04 -0700275static void ft_face_setup_axes(FT_Face face, const SkFontData& data) {
276 if (!(face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS)) {
277 return;
278 }
279
280 SkDEBUGCODE(
halcanary96fcdcc2015-08-27 07:41:13 -0700281 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -0700282 if (FT_Get_MM_Var(face, &variations)) {
283 SkDEBUGF(("INFO: font %s claims variations, but none found.\n", face->family_name));
284 return;
285 }
286 SkAutoFree autoFreeVariations(variations);
287
288 if (static_cast<FT_UInt>(data.getAxisCount()) != variations->num_axis) {
289 SkDEBUGF(("INFO: font %s has %d variations, but %d were specified.\n",
290 face->family_name, variations->num_axis, data.getAxisCount()));
291 return;
292 }
293 )
294
295 SkAutoSTMalloc<4, FT_Fixed> coords(data.getAxisCount());
296 for (int i = 0; i < data.getAxisCount(); ++i) {
297 coords[i] = data.getAxis()[i];
298 }
299 if (FT_Set_Var_Design_Coordinates(face, data.getAxisCount(), coords.get())) {
300 SkDEBUGF(("INFO: font %s has variations, but specified variations could not be set.\n",
301 face->family_name));
302 return;
303 }
304}
bungeman41868fe2015-05-20 09:21:04 -0700305
reed@android.com62900b42009-02-11 15:07:19 +0000306// Will return 0 on failure
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000307// Caller must lock gFTMutex before calling this function.
bungeman13a007d2015-06-19 05:09:39 -0700308static FT_Face ref_ft_face(const SkTypeface* typeface) {
bungeman5ec443c2014-11-21 13:18:34 -0800309 gFTMutex.assertHeld();
310
reed@google.com2cdc6712013-03-21 18:22:00 +0000311 const SkFontID fontID = typeface->uniqueID();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000312 SkFaceRec* rec = gFaceRecHead;
313 while (rec) {
314 if (rec->fFontID == fontID) {
315 SkASSERT(rec->fFace);
316 rec->fRefCnt += 1;
bungeman13a007d2015-06-19 05:09:39 -0700317 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000318 }
319 rec = rec->fNext;
320 }
321
bungeman41868fe2015-05-20 09:21:04 -0700322 SkAutoTDelete<SkFontData> data(typeface->createFontData());
halcanary96fcdcc2015-08-27 07:41:13 -0700323 if (nullptr == data || !data->hasStream()) {
324 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000325 }
326
bungeman52b64b42015-01-27 10:41:17 -0800327 // this passes ownership of stream to the rec
halcanary385fe4d2015-08-26 13:07:48 -0700328 rec = new SkFaceRec(data->detachStream(), fontID);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000329
bungeman9dc24682014-12-01 14:01:32 -0800330 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000331 memset(&args, 0, sizeof(args));
bungeman41868fe2015-05-20 09:21:04 -0700332 const void* memoryBase = rec->fSkStream->getMemoryBase();
bsalomon49f085d2014-09-05 13:34:00 -0700333 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000334 args.flags = FT_OPEN_MEMORY;
335 args.memory_base = (const FT_Byte*)memoryBase;
bungeman41868fe2015-05-20 09:21:04 -0700336 args.memory_size = rec->fSkStream->getLength();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000337 } else {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338 args.flags = FT_OPEN_STREAM;
339 args.stream = &rec->fFTStream;
340 }
341
bungeman41868fe2015-05-20 09:21:04 -0700342 FT_Error err = FT_Open_Face(gFTLibrary->library(), &args, data->getIndex(), &rec->fFace);
343 if (err) {
bungeman5ec443c2014-11-21 13:18:34 -0800344 SkDEBUGF(("ERROR: unable to open font '%x'\n", fontID));
halcanary385fe4d2015-08-26 13:07:48 -0700345 delete rec;
halcanary96fcdcc2015-08-27 07:41:13 -0700346 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000347 }
bungeman9dc24682014-12-01 14:01:32 -0800348 SkASSERT(rec->fFace);
bungeman41868fe2015-05-20 09:21:04 -0700349
bungeman41868fe2015-05-20 09:21:04 -0700350 ft_face_setup_axes(rec->fFace, *data);
bungeman41868fe2015-05-20 09:21:04 -0700351
bungeman726cf902015-06-05 13:38:12 -0700352 // FreeType will set the charmap to the "most unicode" cmap if it exists.
halcanary96fcdcc2015-08-27 07:41:13 -0700353 // If there are no unicode cmaps, the charmap is set to nullptr.
bungeman726cf902015-06-05 13:38:12 -0700354 // However, "symbol" cmaps should also be considered "fallback unicode" cmaps
355 // because they are effectively private use area only (even if they aren't).
356 // This is the last on the fallback list at
357 // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
358 if (!rec->fFace->charmap) {
359 FT_Select_Charmap(rec->fFace, FT_ENCODING_MS_SYMBOL);
360 }
361
bungeman9dc24682014-12-01 14:01:32 -0800362 rec->fNext = gFaceRecHead;
363 gFaceRecHead = rec;
bungeman13a007d2015-06-19 05:09:39 -0700364 return rec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000365}
366
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000367// Caller must lock gFTMutex before calling this function.
caryclarkfe7ada72016-03-21 06:55:52 -0700368extern void unref_ft_face(FT_Face face);
369void unref_ft_face(FT_Face face) {
bungeman5ec443c2014-11-21 13:18:34 -0800370 gFTMutex.assertHeld();
371
reed@android.com8a1c16f2008-12-17 15:59:43 +0000372 SkFaceRec* rec = gFaceRecHead;
halcanary96fcdcc2015-08-27 07:41:13 -0700373 SkFaceRec* prev = nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000374 while (rec) {
375 SkFaceRec* next = rec->fNext;
376 if (rec->fFace == face) {
377 if (--rec->fRefCnt == 0) {
378 if (prev) {
379 prev->fNext = next;
380 } else {
381 gFaceRecHead = next;
382 }
383 FT_Done_Face(face);
halcanary385fe4d2015-08-26 13:07:48 -0700384 delete rec;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000385 }
386 return;
387 }
388 prev = rec;
389 rec = next;
390 }
tomhudson@google.com0c00f212011-12-28 14:59:50 +0000391 SkDEBUGFAIL("shouldn't get here, face not in list");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000392}
393
reed@google.comb4162b12013-07-02 16:32:29 +0000394class AutoFTAccess {
395public:
halcanary96fcdcc2015-08-27 07:41:13 -0700396 AutoFTAccess(const SkTypeface* tf) : fFace(nullptr) {
reed@google.comb4162b12013-07-02 16:32:29 +0000397 gFTMutex.acquire();
bungeman9dc24682014-12-01 14:01:32 -0800398 if (!ref_ft_library()) {
399 sk_throw();
reed@google.comb4162b12013-07-02 16:32:29 +0000400 }
bungeman13a007d2015-06-19 05:09:39 -0700401 fFace = ref_ft_face(tf);
reed@google.comb4162b12013-07-02 16:32:29 +0000402 }
403
404 ~AutoFTAccess() {
405 if (fFace) {
406 unref_ft_face(fFace);
407 }
bungeman9dc24682014-12-01 14:01:32 -0800408 unref_ft_library();
reed@google.comb4162b12013-07-02 16:32:29 +0000409 gFTMutex.release();
410 }
411
reed@google.comb4162b12013-07-02 16:32:29 +0000412 FT_Face face() { return fFace; }
413
414private:
reed@google.comb4162b12013-07-02 16:32:29 +0000415 FT_Face fFace;
416};
417
reed@android.com8a1c16f2008-12-17 15:59:43 +0000418///////////////////////////////////////////////////////////////////////////
419
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000420static bool canEmbed(FT_Face face) {
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000421 FT_UShort fsType = FT_Get_FSType_Flags(face);
422 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
423 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000424}
425
vandebo0f9bad02014-06-19 11:05:39 -0700426static bool canSubset(FT_Face face) {
vandebo0f9bad02014-06-19 11:05:39 -0700427 FT_UShort fsType = FT_Get_FSType_Flags(face);
428 return (fsType & FT_FSTYPE_NO_SUBSETTING) == 0;
vandebo0f9bad02014-06-19 11:05:39 -0700429}
430
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000431static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
432 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
433 if (!glyph_id)
434 return false;
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000435 if (FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE) != 0)
436 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000437 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
438 return true;
439}
440
bungeman5ec443c2014-11-21 13:18:34 -0800441static void populate_glyph_to_unicode(FT_Face& face, SkTDArray<SkUnichar>* glyphToUnicode) {
halcanaryf8c74a12016-04-20 08:37:43 -0700442 FT_Long numGlyphs = face->num_glyphs;
443 glyphToUnicode->setCount(SkToInt(numGlyphs));
444 sk_bzero(glyphToUnicode->begin(), sizeof((*glyphToUnicode)[0]) * numGlyphs);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000445
bungeman726cf902015-06-05 13:38:12 -0700446 FT_UInt glyphIndex;
447 SkUnichar charCode = FT_Get_First_Char(face, &glyphIndex);
448 while (glyphIndex) {
halcanaryf8c74a12016-04-20 08:37:43 -0700449 SkASSERT(glyphIndex < SkToUInt(numGlyphs));
halcanary5f1d0f62016-09-13 08:08:38 -0700450 // Use the first character that maps to this glyphID. https://crbug.com/359065
451 if (0 == (*glyphToUnicode)[glyphIndex]) {
452 (*glyphToUnicode)[glyphIndex] = charCode;
453 }
bungeman726cf902015-06-05 13:38:12 -0700454 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000455 }
456}
457
reed@google.com2689f612013-03-20 20:01:47 +0000458SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700459 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000460 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000461 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000462 AutoFTAccess fta(this);
463 FT_Face face = fta.face();
464 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700465 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000466 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000467
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000468 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
469 info->fFontName.set(FT_Get_Postscript_Name(face));
halcanary32875882016-08-16 09:36:23 -0700470
vandebo0f9bad02014-06-19 11:05:39 -0700471 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700472 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700473 }
474 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700475 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700476 }
477 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700478 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700479 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000480 info->fLastGlyphID = face->num_glyphs - 1;
481 info->fEmSize = 1000;
482
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000483 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000484 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000485 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000486 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000487 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000488 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000489 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000490 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000491 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000492 TT_Header* ttHeader;
bungemanf1491692016-07-22 11:19:24 -0700493 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000494 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000495 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000496 } else {
497 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000498 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000499
halcanary32875882016-08-16 09:36:23 -0700500 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700501 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000502 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700503 }
504 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000505 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700506 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000507
bungemanf1491692016-07-22 11:19:24 -0700508 PS_FontInfoRec psFontInfo;
509 TT_Postscript* postTable;
510 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
511 info->fItalicAngle = psFontInfo.italic_angle;
512 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
513 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000514 } else {
515 info->fItalicAngle = 0;
516 }
517
518 info->fAscent = face->ascender;
519 info->fDescent = face->descender;
520
521 // Figure out a good guess for StemV - Min width of i, I, !, 1.
522 // This probably isn't very good with an italic font.
523 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000524 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000525 char stem_chars[] = {'i', 'I', '!', '1'};
526 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
527 FT_BBox bbox;
528 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
529 int16_t width = bbox.xMax - bbox.xMin;
530 if (width > 0 && width < min_width) {
531 min_width = width;
532 info->fStemV = min_width;
533 }
534 }
535 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000536
bungemanf1491692016-07-22 11:19:24 -0700537 TT_PCLT* pcltTable;
538 TT_OS2* os2Table;
539 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
540 info->fCapHeight = pcltTable->CapHeight;
541 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
542 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000543 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700544 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000545 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700546 }
547 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000548 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700549 os2Table->version != 0xFFFF &&
550 os2Table->version >= 2)
551 {
552 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000553 } else {
554 // Figure out a good guess for CapHeight: average the height of M and X.
555 FT_BBox m_bbox, x_bbox;
556 bool got_m, got_x;
557 got_m = GetLetterCBox(face, 'M', &m_bbox);
558 got_x = GetLetterCBox(face, 'X', &x_bbox);
559 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700560 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000561 } else if (got_m && !got_x) {
562 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
563 } else if (!got_m && got_x) {
564 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000565 } else {
566 // Last resort, use the ascent.
567 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000568 }
569 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000570
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000571 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
572 face->bbox.xMax, face->bbox.yMin);
573
vandebo0f9bad02014-06-19 11:05:39 -0700574 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700575 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000576 }
577
reed39a9a502015-05-12 09:50:04 -0700578 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700579 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
580 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000581 // Postscript fonts may contain more than 255 glyphs, so we end up
582 // using multiple font descriptions with a glyph ordering. Record
583 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700584 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000585 for (int gID = 0; gID < face->num_glyphs; gID++) {
586 char glyphName[128]; // PS limit for names is 127 bytes.
587 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700588 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000589 }
590 }
591
reed39a9a502015-05-12 09:50:04 -0700592 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700593 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
594 face->num_charmaps)
595 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000596 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
597 }
598
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000599 return info;
600}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000601
reed@google.com618ef5e2011-01-26 22:10:41 +0000602///////////////////////////////////////////////////////////////////////////
603
reed@google.com8ed436c2011-07-21 14:12:36 +0000604static bool bothZero(SkScalar a, SkScalar b) {
605 return 0 == a && 0 == b;
606}
607
608// returns false if there is any non-90-rotation or skew
609static bool isAxisAligned(const SkScalerContext::Rec& rec) {
610 return 0 == rec.fPreSkewX &&
611 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
612 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
613}
614
reeda9322c22016-04-12 06:47:05 -0700615SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
616 const SkDescriptor* desc) const {
halcanary385fe4d2015-08-26 13:07:48 -0700617 SkScalerContext_FreeType* c =
reeda9322c22016-04-12 06:47:05 -0700618 new SkScalerContext_FreeType(const_cast<SkTypeface_FreeType*>(this), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000619 if (!c->success()) {
halcanary385fe4d2015-08-26 13:07:48 -0700620 delete c;
halcanary96fcdcc2015-08-27 07:41:13 -0700621 c = nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000622 }
623 return c;
624}
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
reeda9322c22016-04-12 06:47:05 -0700730SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
731 const SkScalerContextEffects& effects,
732 const SkDescriptor* desc)
733 : SkScalerContext_FreeType_Base(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>;
mtklein5f939ab2016-03-16 10:28:35 -0700746 std::unique_ptr<skstd::remove_pointer_t<FT_Face>, UnrefFTFace> ftFace(ref_ft_face(typeface));
bungemanaabd71c2016-03-01 15:15:09 -0800747 if (nullptr == ftFace) {
748 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000749 return;
750 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000751
bungeman5f14c5e2014-12-05 12:26:44 -0800752 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000753
bungeman401ae2d2016-07-18 15:46:27 -0700754 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
755 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000756 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700757 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
758 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000759 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000760
reed@google.coma1bfa212012-03-08 21:57:12 +0000761 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
762
reed@android.com8a1c16f2008-12-17 15:59:43 +0000763 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000764 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000765 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000766 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000767
agl@chromium.org70a303f2010-05-10 14:15:50 +0000768 if (SkMask::kBW_Format == fRec.fMaskFormat) {
769 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
770 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000771 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000772 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000773 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000774 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000775 } else {
776 switch (fRec.getHinting()) {
777 case SkPaint::kNo_Hinting:
778 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000779 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000780 break;
781 case SkPaint::kSlight_Hinting:
782 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
783 break;
784 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000785 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000786 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700787#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
788 } else {
789 loadFlags = FT_LOAD_NO_AUTOHINT;
790#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000791 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000792 break;
793 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000794 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000795 loadFlags = FT_LOAD_FORCE_AUTOHINT;
796 break;
797 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000798 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000799 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000800 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000801 loadFlags = FT_LOAD_TARGET_LCD_V;
802 } else {
803 loadFlags = FT_LOAD_TARGET_LCD;
804 }
reed@google.comea2333d2011-03-14 16:44:56 +0000805 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000806 break;
807 default:
808 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
809 break;
810 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000811 }
812
reed@google.comeffc5012011-06-27 16:44:46 +0000813 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000814 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000815 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000816
reed@google.com96a9f7912011-05-06 11:49:30 +0000817 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
818 // advances, as fontconfig and cairo do.
819 // See http://code.google.com/p/skia/issues/detail?id=222.
820 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
821
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000822 // Use vertical layout if requested.
823 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
824 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
825 }
826
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000827 loadFlags |= FT_LOAD_COLOR;
828
reed@android.come4d0bc02009-07-24 19:53:20 +0000829 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000830 }
831
bungemanaabd71c2016-03-01 15:15:09 -0800832 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
mtklein5f939ab2016-03-16 10:28:35 -0700833 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([&ftFace]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800834 FT_Size size;
835 FT_Error err = FT_New_Size(ftFace.get(), &size);
836 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700837 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800838 return nullptr;
839 }
840 return size;
841 }());
842 if (nullptr == ftSize) {
843 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000844 return;
845 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000846
bungemanaabd71c2016-03-01 15:15:09 -0800847 FT_Error err = FT_Activate_Size(ftSize.get());
848 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700849 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800850 return;
851 }
852
853 if (FT_IS_SCALABLE(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700854 err = FT_Set_Char_Size(ftFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000855 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700856 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
857 ftFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000858 return;
859 }
bungemanaabd71c2016-03-01 15:15:09 -0800860 } else if (FT_HAS_FIXED_SIZES(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700861 fStrikeIndex = chooseBitmapStrike(ftFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000862 if (fStrikeIndex == -1) {
bungeman401ae2d2016-07-18 15:46:27 -0700863 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n", ftFace->family_name, fScale.fY));
864 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000865 }
bungeman401ae2d2016-07-18 15:46:27 -0700866
867 err = FT_Select_Size(ftFace.get(), fStrikeIndex);
868 if (err != 0) {
869 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
870 ftFace->family_name, fStrikeIndex, err));
871 fStrikeIndex = -1;
872 return;
873 }
874
875 // A non-ideal size was picked, so recompute the matrix.
876 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
877 fMatrix22Scalar.preScale(fScale.x() / ftFace->size->metrics.x_ppem,
878 fScale.y() / ftFace->size->metrics.y_ppem);
879 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
880 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
881 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
882 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
883
884 // FreeType does not provide linear metrics for bitmap fonts.
885 linearMetrics = false;
886
887 // FreeType documentation says:
888 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
889 // Bitmap-only fonts ignore this flag.
890 //
891 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
892 // Force this flag off for bitmap only fonts.
893 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000894 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700895 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFace->family_name, fScale.fY));
896 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000897 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000898
bungemanaabd71c2016-03-01 15:15:09 -0800899 fFTSize = ftSize.release();
900 fFace = ftFace.release();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000901 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000902}
903
904SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000905 SkAutoMutexAcquire ac(gFTMutex);
906
halcanary96fcdcc2015-08-27 07:41:13 -0700907 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000908 FT_Done_Size(fFTSize);
909 }
910
halcanary96fcdcc2015-08-27 07:41:13 -0700911 if (fFace != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000912 unref_ft_face(fFace);
913 }
bungeman9dc24682014-12-01 14:01:32 -0800914
915 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000916}
917
918/* We call this before each use of the fFace, since we may be sharing
919 this face with other context (at different sizes).
920*/
921FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800922 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000923 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000924 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000925 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000926 }
halcanary96fcdcc2015-08-27 07:41:13 -0700927 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000928 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000929}
930
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000931unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000932 return fFace->num_glyphs;
933}
934
935uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -0800936 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000937 return SkToU16(FT_Get_Char_Index( fFace, uni ));
938}
939
reed@android.com9d3a9852010-01-08 14:07:42 +0000940SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -0800941 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +0000942 // iterate through each cmap entry, looking for matching glyph indices
943 FT_UInt glyphIndex;
944 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
945
946 while (glyphIndex != 0) {
947 if (glyphIndex == glyph) {
948 return charCode;
949 }
950 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
951 }
952
953 return 0;
954}
955
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700956static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
957 return SkFixedToScalar(x);
958}
959
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000961 /* unhinted and light hinted text have linearly scaled advances
962 * which are very cheap to compute with some font formats...
963 */
reed@google.combdc99882011-11-21 14:36:57 +0000964 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000965 SkAutoMutexAcquire ac(gFTMutex);
966
967 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000968 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000969 return;
970 }
971
972 FT_Error error;
973 FT_Fixed advance;
974
djsollen1b277042014-08-06 06:58:06 -0700975 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +0000976 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
977 &advance );
978 if (0 == error) {
979 glyph->fRsbDelta = 0;
980 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700981 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
982 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -0700983 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000984 return;
985 }
986 }
bungeman5ec443c2014-11-21 13:18:34 -0800987
reed@android.com8a1c16f2008-12-17 15:59:43 +0000988 /* otherwise, we need to load/hint the glyph, which is slower */
989 this->generateMetrics(glyph);
990 return;
991}
992
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000993void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
994 FT_BBox* bbox,
995 bool snapToPixelBoundary) {
996
997 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
998
999 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001000 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1001 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001002 // negate dy since freetype-y-goes-up and skia-y-goes-down
1003 bbox->xMin += dx;
1004 bbox->yMin -= dy;
1005 bbox->xMax += dx;
1006 bbox->yMax -= dy;
1007 }
1008
1009 // outset the box to integral boundaries
1010 if (snapToPixelBoundary) {
1011 bbox->xMin &= ~63;
1012 bbox->yMin &= ~63;
1013 bbox->xMax = (bbox->xMax + 63) & ~63;
1014 bbox->yMax = (bbox->yMax + 63) & ~63;
1015 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001016
1017 // Must come after snapToPixelBoundary so that the width and height are
1018 // consistent. Otherwise asserts will fire later on when generating the
1019 // glyph image.
1020 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1021 FT_Vector vector;
1022 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1023 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1024 FT_Vector_Transform(&vector, &fMatrix22);
1025 bbox->xMin += vector.x;
1026 bbox->xMax += vector.x;
1027 bbox->yMin += vector.y;
1028 bbox->yMax += vector.y;
1029 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001030}
1031
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001032bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1033 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001034 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001035 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001036 }
1037 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001038 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001039 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001040 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001041 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1042 return true;
1043}
1044
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001045void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1046 if (isLCD(fRec)) {
1047 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001048 glyph->fHeight += gFTLibrary->lcdExtra();
1049 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001050 } else {
bungeman9dc24682014-12-01 14:01:32 -08001051 glyph->fWidth += gFTLibrary->lcdExtra();
1052 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001053 }
1054 }
1055}
1056
bungeman401ae2d2016-07-18 15:46:27 -07001057bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1058 // If subpixel rendering of a bitmap *can* be done.
1059 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1060 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1061 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001062
bungeman401ae2d2016-07-18 15:46:27 -07001063 // If subpixel rendering of a bitmap *should* be done.
1064 // 1. If the face is not scalable then always allow subpixel rendering.
1065 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1066 // 2. If the matrix is already not identity the bitmap will already be resampled,
1067 // so resampling slightly differently shouldn't make much difference.
1068 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1069
1070 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001071}
1072
reed@android.com8a1c16f2008-12-17 15:59:43 +00001073void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1074 SkAutoMutexAcquire ac(gFTMutex);
1075
1076 glyph->fRsbDelta = 0;
1077 glyph->fLsbDelta = 0;
1078
1079 FT_Error err;
1080
1081 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001082 glyph->zeroMetrics();
1083 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001084 }
1085
djsollen1b277042014-08-06 06:58:06 -07001086 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001087 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001088 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001089 return;
1090 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001091 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001092
1093 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001094 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001095 if (0 == fFace->glyph->outline.n_contours) {
1096 glyph->fWidth = 0;
1097 glyph->fHeight = 0;
1098 glyph->fTop = 0;
1099 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001100 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001101 FT_BBox bbox;
1102 getBBoxForCurrentGlyph(glyph, &bbox, true);
1103
1104 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1105 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1106 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1107 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1108
1109 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001110 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001111 break;
1112
1113 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001114 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1115 FT_Vector vector;
1116 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1117 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1118 FT_Vector_Transform(&vector, &fMatrix22);
1119 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1120 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1121 }
1122
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001123 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1124 glyph->fMaskFormat = SkMask::kARGB32_Format;
1125 }
1126
bungeman401ae2d2016-07-18 15:46:27 -07001127 {
1128 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1129 -SkIntToScalar(fFace->glyph->bitmap_top),
1130 SkIntToScalar(fFace->glyph->bitmap.width),
1131 SkIntToScalar(fFace->glyph->bitmap.rows));
1132 fMatrix22Scalar.mapRect(&rect);
1133 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1134 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1135 SkFixedToScalar(glyph->getSubYFixed()));
1136 }
1137 SkIRect irect = rect.roundOut();
1138 glyph->fWidth = SkToU16(irect.width());
1139 glyph->fHeight = SkToU16(irect.height());
1140 glyph->fTop = SkToS16(irect.top());
1141 glyph->fLeft = SkToS16(irect.left());
1142 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001143 break;
1144
1145 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001146 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001147 glyph->zeroMetrics();
1148 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001149 }
1150
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001151 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1152 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001153 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001154 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001155 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001156 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001157 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1158 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001159 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001160 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001161 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001162 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1163 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001164 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001165 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001166 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1167 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001168
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001169 if (fRec.fFlags & kDevKernText_Flag) {
1170 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1171 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001172 }
1173 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001174 }
1175
reed@android.com8a1c16f2008-12-17 15:59:43 +00001176#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001177 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001178#endif
1179}
1180
bungeman5ec443c2014-11-21 13:18:34 -08001181static void clear_glyph_image(const SkGlyph& glyph) {
1182 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1183}
reed@google.comea2333d2011-03-14 16:44:56 +00001184
bungeman@google.coma76de722012-10-26 19:35:54 +00001185void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001186 SkAutoMutexAcquire ac(gFTMutex);
1187
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001189 clear_glyph_image(glyph);
1190 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001191 }
1192
bungeman5ec443c2014-11-21 13:18:34 -08001193 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001194 if (err != 0) {
1195 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 -08001196 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1197 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001198 return;
1199 }
1200
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001201 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001202 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1203 SkMatrix subpixelBitmapMatrix;
1204 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1205 subpixelBitmapMatrix = fMatrix22Scalar;
1206 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1207 SkFixedToScalar(glyph.getSubYFixed()));
1208 bitmapMatrix = &subpixelBitmapMatrix;
1209 }
1210 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001211}
1212
reed@android.com8a1c16f2008-12-17 15:59:43 +00001213
bungeman5ec443c2014-11-21 13:18:34 -08001214void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001215 SkAutoMutexAcquire ac(gFTMutex);
1216
caryclarka10742c2014-09-18 11:00:40 -07001217 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001218
1219 if (this->setupSize()) {
1220 path->reset();
1221 return;
1222 }
1223
1224 uint32_t flags = fLoadGlyphFlags;
1225 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1226 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1227
djsollen1b277042014-08-06 06:58:06 -07001228 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001229
1230 if (err != 0) {
1231 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001232 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001233 path->reset();
1234 return;
1235 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001236 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001237
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001238 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001239
1240 // The path's origin from FreeType is always the horizontal layout origin.
1241 // Offset the path so that it is relative to the vertical origin if needed.
1242 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1243 FT_Vector vector;
1244 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1245 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1246 FT_Vector_Transform(&vector, &fMatrix22);
1247 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1248 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001249}
1250
bungeman41078062014-07-07 08:16:37 -07001251void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001252 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253 return;
1254 }
1255
bungeman41078062014-07-07 08:16:37 -07001256 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001257
1258 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001259 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001260 return;
1261 }
1262
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001263 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001264
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001265 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1266 SkScalar upem = SkIntToScalar(face->units_per_EM);
1267 if (!upem) {
1268 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1269 if (ttHeader) {
1270 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001271 }
1272 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001273
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001274 // use the os/2 table as a source of reasonable defaults.
1275 SkScalar x_height = 0.0f;
1276 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001277 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001278 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1279 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001280 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001281 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001282 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001283 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001284 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001285 }
1286
1287 // pull from format-specific metrics as needed
1288 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001289 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001290 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001291 // FreeType will always use HHEA metrics if they're not zero.
1292 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1293 // It also ignores the VDMX tables, which are also of interest here
1294 // (and override everything else when they apply).
1295 static const int kUseTypoMetricsMask = (1 << 7);
1296 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1297 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1298 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1299 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1300 } else {
1301 ascent = -SkIntToScalar(face->ascender) / upem;
1302 descent = -SkIntToScalar(face->descender) / upem;
1303 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1304 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001305 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1306 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1307 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1308 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001309 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001310 underlinePosition = -SkIntToScalar(face->underline_position +
1311 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001312
bungeman41078062014-07-07 08:16:37 -07001313 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1314 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1315
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001316 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001317 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001318 FT_BBox bbox;
1319 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001320 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1321 }
1322 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001323 if (!cap_height) {
1324 FT_BBox bbox;
1325 if (getCBoxForLetter('H', &bbox)) {
1326 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1327 }
1328 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001329 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1330 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1331 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1332 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1333 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001334 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001335 xmin = 0.0f;
1336 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1337 ymin = descent + leading;
1338 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001339 underlineThickness = 0;
1340 underlinePosition = 0;
1341
bungeman41078062014-07-07 08:16:37 -07001342 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1343 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001344 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001345 sk_bzero(metrics, sizeof(*metrics));
1346 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001347 }
1348
1349 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1350 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001351 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001352 }
1353 if (!avgCharWidth) {
1354 avgCharWidth = xmax - xmin;
1355 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001356 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001357 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001358 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001359
1360 // disallow negative linespacing
1361 if (leading < 0.0f) {
1362 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001363 }
1364
bungeman53790512016-07-21 13:32:09 -07001365 metrics->fTop = ymax * fScale.y();
1366 metrics->fAscent = ascent * fScale.y();
1367 metrics->fDescent = descent * fScale.y();
1368 metrics->fBottom = ymin * fScale.y();
1369 metrics->fLeading = leading * fScale.y();
1370 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1371 metrics->fXMin = xmin * fScale.y();
1372 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001373 metrics->fXHeight = x_height;
1374 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001375 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1376 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001377}
1378
djsollenfcfea992015-01-09 08:18:13 -08001379///////////////////////////////////////////////////////////////////////////////
1380
1381// hand-tuned value to reduce outline embolden strength
1382#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1383 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1384 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1385 #else
1386 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1387 #endif
1388#endif
1389
1390///////////////////////////////////////////////////////////////////////////////
1391
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001392void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1393{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001394 // check to see if the embolden bit is set
1395 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1396 return;
1397 }
1398
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001399 switch (glyph->format) {
1400 case FT_GLYPH_FORMAT_OUTLINE:
1401 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001402 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1403 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001404 FT_Outline_Embolden(&glyph->outline, strength);
1405 break;
1406 case FT_GLYPH_FORMAT_BITMAP:
1407 FT_GlyphSlot_Own_Bitmap(glyph);
1408 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1409 break;
1410 default:
1411 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001412 }
1413}
1414
reed@google.comb4162b12013-07-02 16:32:29 +00001415///////////////////////////////////////////////////////////////////////////////
1416
1417#include "SkUtils.h"
1418
1419static SkUnichar next_utf8(const void** chars) {
1420 return SkUTF8_NextUnichar((const char**)chars);
1421}
1422
1423static SkUnichar next_utf16(const void** chars) {
1424 return SkUTF16_NextUnichar((const uint16_t**)chars);
1425}
1426
1427static SkUnichar next_utf32(const void** chars) {
1428 const SkUnichar** uniChars = (const SkUnichar**)chars;
1429 SkUnichar uni = **uniChars;
1430 *uniChars += 1;
1431 return uni;
1432}
1433
1434typedef SkUnichar (*EncodingProc)(const void**);
1435
1436static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1437 static const EncodingProc gProcs[] = {
1438 next_utf8, next_utf16, next_utf32
1439 };
1440 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1441 return gProcs[enc];
1442}
1443
1444int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001445 uint16_t glyphs[], int glyphCount) const
1446{
reed@google.comb4162b12013-07-02 16:32:29 +00001447 AutoFTAccess fta(this);
1448 FT_Face face = fta.face();
1449 if (!face) {
1450 if (glyphs) {
1451 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1452 }
1453 return 0;
1454 }
1455
1456 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1457
halcanary96fcdcc2015-08-27 07:41:13 -07001458 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001459 for (int i = 0; i < glyphCount; ++i) {
1460 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1461 return i;
1462 }
1463 }
1464 return glyphCount;
1465 } else {
1466 int first = glyphCount;
1467 for (int i = 0; i < glyphCount; ++i) {
1468 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1469 glyphs[i] = SkToU16(id);
1470 if (0 == id && i < first) {
1471 first = i;
1472 }
1473 }
1474 return first;
1475 }
1476}
1477
1478int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001479 AutoFTAccess fta(this);
1480 FT_Face face = fta.face();
1481 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001482}
1483
bungeman@google.com839702b2013-08-07 17:09:22 +00001484SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001485 SkTypeface::LocalizedStrings* nameIter =
1486 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001487 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001488 SkString familyName;
1489 this->getFamilyName(&familyName);
1490 SkString language("und"); //undetermined
1491 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1492 }
1493 return nameIter;
1494}
1495
bungeman@google.comddc218e2013-08-01 22:29:43 +00001496int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1497 AutoFTAccess fta(this);
1498 FT_Face face = fta.face();
1499
1500 FT_ULong tableCount = 0;
1501 FT_Error error;
1502
halcanary96fcdcc2015-08-27 07:41:13 -07001503 // When 'tag' is nullptr, returns number of tables in 'length'.
1504 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001505 if (error) {
1506 return 0;
1507 }
1508
1509 if (tags) {
1510 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1511 FT_ULong tableTag;
1512 FT_ULong tablelength;
1513 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1514 if (error) {
1515 return 0;
1516 }
1517 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1518 }
1519 }
1520 return tableCount;
1521}
1522
1523size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1524 size_t length, void* data) const
1525{
1526 AutoFTAccess fta(this);
1527 FT_Face face = fta.face();
1528
1529 FT_ULong tableLength = 0;
1530 FT_Error error;
1531
1532 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001533 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001534 if (error) {
1535 return 0;
1536 }
1537
1538 if (offset > tableLength) {
1539 return 0;
1540 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001541 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001542 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001543 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1544 if (error) {
1545 return 0;
1546 }
1547 }
1548
1549 return size;
1550}
1551
reed@google.comb4162b12013-07-02 16:32:29 +00001552///////////////////////////////////////////////////////////////////////////////
1553///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001554
halcanary96fcdcc2015-08-27 07:41:13 -07001555SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001556 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1557 return;
bungeman14df8332014-10-28 15:07:23 -07001558 }
bungeman9dc24682014-12-01 14:01:32 -08001559 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001560}
1561SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001562 if (fLibrary) {
1563 FT_Done_Library(fLibrary);
1564 }
bungeman14df8332014-10-28 15:07:23 -07001565}
1566
1567FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1568 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001569{
halcanary96fcdcc2015-08-27 07:41:13 -07001570 if (fLibrary == nullptr) {
1571 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001572 }
1573
bungeman14df8332014-10-28 15:07:23 -07001574 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001575 memset(&args, 0, sizeof(args));
1576
1577 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001578
bsalomon49f085d2014-09-05 13:34:00 -07001579 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001580 args.flags = FT_OPEN_MEMORY;
1581 args.memory_base = (const FT_Byte*)memoryBase;
1582 args.memory_size = stream->getLength();
1583 } else {
bungeman14df8332014-10-28 15:07:23 -07001584 memset(ftStream, 0, sizeof(*ftStream));
1585 ftStream->size = stream->getLength();
1586 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001587 ftStream->read = sk_ft_stream_io;
1588 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001589
1590 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001591 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001592 }
1593
1594 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001595 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001596 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001597 }
1598 return face;
1599}
1600
1601bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1602 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1603
1604 FT_StreamRec streamRec;
1605 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001606 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001607 return false;
1608 }
1609
1610 *numFaces = face->num_faces;
1611
1612 FT_Done_Face(face);
1613 return true;
1614}
1615
1616#include "SkTSearch.h"
1617bool SkTypeface_FreeType::Scanner::scanFont(
bungeman41868fe2015-05-20 09:21:04 -07001618 SkStream* stream, int ttcIndex,
1619 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001620{
1621 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1622
1623 FT_StreamRec streamRec;
1624 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001625 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001626 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001627 }
1628
bungemana4c4a2d2014-10-20 13:33:19 -07001629 int weight = SkFontStyle::kNormal_Weight;
1630 int width = SkFontStyle::kNormal_Width;
1631 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001632 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001633 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001634 }
1635 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001636 slant = SkFontStyle::kItalic_Slant;
1637 }
1638
1639 PS_FontInfoRec psFontInfo;
1640 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1641 if (os2 && os2->version != 0xffff) {
1642 weight = os2->usWeightClass;
1643 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001644
1645 // OS/2::fsSelection bit 9 indicates oblique.
1646 if (SkToBool(os2->fsSelection & (1u << 9))) {
1647 slant = SkFontStyle::kOblique_Slant;
1648 }
bungemana4c4a2d2014-10-20 13:33:19 -07001649 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1650 static const struct {
1651 char const * const name;
1652 int const weight;
1653 } commonWeights [] = {
1654 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001655 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001656 { "black", SkFontStyle::kBlack_Weight },
1657 { "bold", SkFontStyle::kBold_Weight },
1658 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1659 { "demi", SkFontStyle::kSemiBold_Weight },
1660 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001661 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001662 { "extrabold", SkFontStyle::kExtraBold_Weight },
1663 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001664 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001665 { "heavy", SkFontStyle::kBlack_Weight },
1666 { "light", SkFontStyle::kLight_Weight },
1667 { "medium", SkFontStyle::kMedium_Weight },
1668 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001669 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001670 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001671 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001672 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001673 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001674 { "thin", SkFontStyle::kThin_Weight },
1675 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001676 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001677 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001678 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001679 { "ultralight", SkFontStyle::kExtraLight_Weight },
1680 };
1681 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001682 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001683 if (index >= 0) {
1684 weight = commonWeights[index].weight;
1685 } else {
bungeman14df8332014-10-28 15:07:23 -07001686 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001687 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001688 }
1689
1690 if (name) {
1691 name->set(face->family_name);
1692 }
1693 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001694 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001695 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001696 if (isFixedPitch) {
1697 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001698 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001699
bungeman41868fe2015-05-20 09:21:04 -07001700 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001701 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001702 FT_Error err = FT_Get_MM_Var(face, &variations);
1703 if (err) {
1704 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1705 face->family_name));
1706 return false;
1707 }
1708 SkAutoFree autoFreeVariations(variations);
1709
1710 axes->reset(variations->num_axis);
1711 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1712 const FT_Var_Axis& ftAxis = variations->axis[i];
1713 (*axes)[i].fTag = ftAxis.tag;
1714 (*axes)[i].fMinimum = ftAxis.minimum;
1715 (*axes)[i].fDefault = ftAxis.def;
1716 (*axes)[i].fMaximum = ftAxis.maximum;
1717 }
1718 }
bungeman41868fe2015-05-20 09:21:04 -07001719
reed@android.com8a1c16f2008-12-17 15:59:43 +00001720 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001721 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001722}
bungemanf6c71072016-01-21 14:17:47 -08001723
1724/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1725 AxisDefinitions axisDefinitions,
1726 const SkFontMgr::FontParameters::Axis* requestedAxes, int requestedAxisCount,
1727 SkFixed* axisValues,
1728 const SkString& name)
1729{
1730 for (int i = 0; i < axisDefinitions.count(); ++i) {
1731 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001732 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1733 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001734 axisValues[i] = axisDefinition.fDefault;
1735 for (int j = 0; j < requestedAxisCount; ++j) {
1736 const SkFontMgr::FontParameters::Axis& axisSpecified = requestedAxes[j];
1737 if (axisDefinition.fTag == axisSpecified.fTag) {
benjaminwagner64a3c952016-02-25 12:20:40 -08001738 const SkScalar axisValue = SkTPin(axisSpecified.fStyleValue, axisMin, axisMax);
1739 if (axisSpecified.fStyleValue != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001740 SkDEBUGF(("Requested font axis value out of range: "
1741 "%s '%c%c%c%c' %f; pinned to %f.\n",
1742 name.c_str(),
1743 (axisDefinition.fTag >> 24) & 0xFF,
1744 (axisDefinition.fTag >> 16) & 0xFF,
1745 (axisDefinition.fTag >> 8) & 0xFF,
1746 (axisDefinition.fTag ) & 0xFF,
1747 SkScalarToDouble(axisSpecified.fStyleValue),
benjaminwagner64a3c952016-02-25 12:20:40 -08001748 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001749 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001750 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001751 break;
1752 }
1753 }
1754 // TODO: warn on defaulted axis?
1755 }
1756
1757 SkDEBUGCODE(
1758 // Check for axis specified, but not matched in font.
1759 for (int i = 0; i < requestedAxisCount; ++i) {
1760 SkFourByteTag skTag = requestedAxes[i].fTag;
1761 bool found = false;
1762 for (int j = 0; j < axisDefinitions.count(); ++j) {
1763 if (skTag == axisDefinitions[j].fTag) {
1764 found = true;
1765 break;
1766 }
1767 }
1768 if (!found) {
1769 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1770 name.c_str(),
1771 (skTag >> 24) & 0xFF,
1772 (skTag >> 16) & 0xFF,
1773 (skTag >> 8) & 0xFF,
1774 (skTag) & 0xFF));
1775 }
1776 }
1777 )
1778}