blob: 4a1f12babe2adc07a876657ddfb9e5c1a5c17cf2 [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));
bungeman726cf902015-06-05 13:38:12 -0700450 (*glyphToUnicode)[glyphIndex] = charCode;
451 charCode = FT_Get_Next_Char(face, charCode, &glyphIndex);
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000452 }
453}
454
reed@google.com2689f612013-03-20 20:01:47 +0000455SkAdvancedTypefaceMetrics* SkTypeface_FreeType::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -0700456 PerGlyphInfo perGlyphInfo,
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000457 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +0000458 uint32_t glyphIDsCount) const {
reed@google.comb4162b12013-07-02 16:32:29 +0000459 AutoFTAccess fta(this);
460 FT_Face face = fta.face();
461 if (!face) {
halcanary96fcdcc2015-08-27 07:41:13 -0700462 return nullptr;
reed@google.comb4162b12013-07-02 16:32:29 +0000463 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000464
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000465 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
466 info->fFontName.set(FT_Get_Postscript_Name(face));
vandebo0f9bad02014-06-19 11:05:39 -0700467 info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag;
468 if (FT_HAS_MULTIPLE_MASTERS(face)) {
469 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
470 info->fFlags, SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag);
471 }
472 if (!canEmbed(face)) {
473 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
474 info->fFlags,
475 SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag);
476 }
477 if (!canSubset(face)) {
478 info->fFlags = SkTBitOr<SkAdvancedTypefaceMetrics::FontFlags>(
479 info->fFlags,
480 SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag);
481 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000482 info->fLastGlyphID = face->num_glyphs - 1;
483 info->fEmSize = 1000;
484
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000485 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000486 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000487 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000488 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000489 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000490 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000491 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000492 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000493 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000494 TT_Header* ttHeader;
bungemanf1491692016-07-22 11:19:24 -0700495 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000496 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000497 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000498 } else {
499 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000500 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000501
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000502 info->fStyle = 0;
bungemanf1491692016-07-22 11:19:24 -0700503 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000504 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700505 }
506 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000507 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700508 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000509
bungemanf1491692016-07-22 11:19:24 -0700510 PS_FontInfoRec psFontInfo;
511 TT_Postscript* postTable;
512 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
513 info->fItalicAngle = psFontInfo.italic_angle;
514 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
515 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000516 } else {
517 info->fItalicAngle = 0;
518 }
519
520 info->fAscent = face->ascender;
521 info->fDescent = face->descender;
522
523 // Figure out a good guess for StemV - Min width of i, I, !, 1.
524 // This probably isn't very good with an italic font.
525 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000526 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000527 char stem_chars[] = {'i', 'I', '!', '1'};
528 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
529 FT_BBox bbox;
530 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
531 int16_t width = bbox.xMax - bbox.xMin;
532 if (width > 0 && width < min_width) {
533 min_width = width;
534 info->fStemV = min_width;
535 }
536 }
537 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000538
bungemanf1491692016-07-22 11:19:24 -0700539 TT_PCLT* pcltTable;
540 TT_OS2* os2Table;
541 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
542 info->fCapHeight = pcltTable->CapHeight;
543 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
544 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000545 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700546 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000547 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700548 }
549 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000550 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700551 os2Table->version != 0xFFFF &&
552 os2Table->version >= 2)
553 {
554 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000555 } else {
556 // Figure out a good guess for CapHeight: average the height of M and X.
557 FT_BBox m_bbox, x_bbox;
558 bool got_m, got_x;
559 got_m = GetLetterCBox(face, 'M', &m_bbox);
560 got_x = GetLetterCBox(face, 'X', &x_bbox);
561 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700562 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000563 } else if (got_m && !got_x) {
564 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
565 } else if (!got_m && got_x) {
566 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000567 } else {
568 // Last resort, use the ascent.
569 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000570 }
571 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000572
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000573 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
574 face->bbox.xMax, face->bbox.yMin);
575
vandebo0f9bad02014-06-19 11:05:39 -0700576 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700577 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000578 }
579
reed39a9a502015-05-12 09:50:04 -0700580 if (perGlyphInfo & kHAdvance_PerGlyphInfo) {
bungemanf1491692016-07-22 11:19:24 -0700581 info->setGlyphWidths(
582 face->num_glyphs,
583 glyphIDs,
584 glyphIDsCount,
585 SkAdvancedTypefaceMetrics::GetAdvance([face](int gId, int16_t* data) {
586 FT_Fixed advance = 0;
587 if (FT_Get_Advances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
588 return false;
bungeman5ec443c2014-11-21 13:18:34 -0800589 }
bungemanf1491692016-07-22 11:19:24 -0700590 SkASSERT(data);
591 *data = advance;
592 return true;
593 })
594 );
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000595 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000596
bungemanf1491692016-07-22 11:19:24 -0700597 if (perGlyphInfo & kVAdvance_PerGlyphInfo && FT_HAS_VERTICAL(face)) {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000598 SkASSERT(false); // Not implemented yet.
599 }
600
reed39a9a502015-05-12 09:50:04 -0700601 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700602 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
603 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000604 // Postscript fonts may contain more than 255 glyphs, so we end up
605 // using multiple font descriptions with a glyph ordering. Record
606 // the name of each glyph.
bungemanf1491692016-07-22 11:19:24 -0700607 info->fGlyphNames.reset(new SkAutoTArray<SkString>(face->num_glyphs));
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000608 for (int gID = 0; gID < face->num_glyphs; gID++) {
609 char glyphName[128]; // PS limit for names is 127 bytes.
610 FT_Get_Glyph_Name(face, gID, glyphName, 128);
611 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000612 }
613 }
614
reed39a9a502015-05-12 09:50:04 -0700615 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700616 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
617 face->num_charmaps)
618 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000619 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
620 }
621
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000622 return info;
623}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000624
reed@google.com618ef5e2011-01-26 22:10:41 +0000625///////////////////////////////////////////////////////////////////////////
626
reed@google.com8ed436c2011-07-21 14:12:36 +0000627static bool bothZero(SkScalar a, SkScalar b) {
628 return 0 == a && 0 == b;
629}
630
631// returns false if there is any non-90-rotation or skew
632static bool isAxisAligned(const SkScalerContext::Rec& rec) {
633 return 0 == rec.fPreSkewX &&
634 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
635 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
636}
637
reeda9322c22016-04-12 06:47:05 -0700638SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
639 const SkDescriptor* desc) const {
halcanary385fe4d2015-08-26 13:07:48 -0700640 SkScalerContext_FreeType* c =
reeda9322c22016-04-12 06:47:05 -0700641 new SkScalerContext_FreeType(const_cast<SkTypeface_FreeType*>(this), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000642 if (!c->success()) {
halcanary385fe4d2015-08-26 13:07:48 -0700643 delete c;
halcanary96fcdcc2015-08-27 07:41:13 -0700644 c = nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000645 }
646 return c;
647}
648
649void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000650 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
651 //Cap the requested size as larger sizes give bogus values.
652 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800653 //Note that this also currently only protects against large text size requests,
654 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000655 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000656 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000657 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000658
bungemanec7e12f2015-01-21 11:55:16 -0800659 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800660 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
661 SkAutoMutexAcquire ama(gFTMutex);
662 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800663 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800664 // If the runtime Freetype library doesn't support LCD, disable it here.
665 rec->fMaskFormat = SkMask::kA8_Format;
666 }
667 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000668 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000669
reed@google.com618ef5e2011-01-26 22:10:41 +0000670 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000671 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000672 // collapse full->normal hinting if we're not doing LCD
673 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000674 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000675 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000676 if (SkPaint::kNo_Hinting != h) {
677 h = SkPaint::kSlight_Hinting;
678 }
679 }
680
reed@google.com8ed436c2011-07-21 14:12:36 +0000681 // rotated text looks bad with hinting, so we disable it as needed
682 if (!isAxisAligned(*rec)) {
683 h = SkPaint::kNo_Hinting;
684 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000685 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000686
bungeman@google.com97efada2012-07-30 20:40:50 +0000687#ifndef SK_GAMMA_APPLY_TO_A8
688 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700689 // SRGBTODO: Is this correct? Do we want contrast boost?
690 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000691 }
reed@google.com1ac83502012-02-28 17:06:02 +0000692#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000693}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000694
reed@google.com38c37dd2013-03-21 15:36:26 +0000695int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000696 AutoFTAccess fta(this);
697 FT_Face face = fta.face();
698 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000699}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000700
reed@google.com35fe7372013-10-30 15:07:03 +0000701bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
702 int count, int32_t adjustments[]) const {
703 AutoFTAccess fta(this);
704 FT_Face face = fta.face();
705 if (!face || !FT_HAS_KERNING(face)) {
706 return false;
707 }
708
709 for (int i = 0; i < count - 1; ++i) {
710 FT_Vector delta;
711 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
712 FT_KERNING_UNSCALED, &delta);
713 if (err) {
714 return false;
715 }
716 adjustments[i] = delta.x;
717 }
718 return true;
719}
720
bungeman401ae2d2016-07-18 15:46:27 -0700721/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800722static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700723 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700724 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000725 return -1;
726 }
bungeman401ae2d2016-07-18 15:46:27 -0700727
728 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000729 FT_Int chosenStrikeIndex = -1;
730 FT_Pos chosenPPEM = 0;
731 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700732 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
733 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000734 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700735 return strikeIndex;
736 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000737 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700738 if (chosenPPEM < strikePPEM) {
739 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000740 chosenStrikeIndex = strikeIndex;
741 }
742 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700743 // attempt to decrease chosenPPEM, but not below requestedPPEM
744 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
745 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000746 chosenStrikeIndex = strikeIndex;
747 }
748 }
749 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000750 return chosenStrikeIndex;
751}
752
reeda9322c22016-04-12 06:47:05 -0700753SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
754 const SkScalerContextEffects& effects,
755 const SkDescriptor* desc)
756 : SkScalerContext_FreeType_Base(typeface, effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800757 , fFace(nullptr)
758 , fFTSize(nullptr)
759 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700760{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000761 SkAutoMutexAcquire ac(gFTMutex);
762
bungeman9dc24682014-12-01 14:01:32 -0800763 if (!ref_ft_library()) {
764 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000765 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000766
767 // load the font file
bungemanaabd71c2016-03-01 15:15:09 -0800768 using UnrefFTFace = SkFunctionWrapper<void, skstd::remove_pointer_t<FT_Face>, unref_ft_face>;
mtklein5f939ab2016-03-16 10:28:35 -0700769 std::unique_ptr<skstd::remove_pointer_t<FT_Face>, UnrefFTFace> ftFace(ref_ft_face(typeface));
bungemanaabd71c2016-03-01 15:15:09 -0800770 if (nullptr == ftFace) {
771 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000772 return;
773 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000774
bungeman5f14c5e2014-12-05 12:26:44 -0800775 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000776
bungeman401ae2d2016-07-18 15:46:27 -0700777 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
778 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000779 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700780 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
781 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000782 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000783
reed@google.coma1bfa212012-03-08 21:57:12 +0000784 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
785
reed@android.com8a1c16f2008-12-17 15:59:43 +0000786 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000787 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000788 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000789 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790
agl@chromium.org70a303f2010-05-10 14:15:50 +0000791 if (SkMask::kBW_Format == fRec.fMaskFormat) {
792 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
793 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000794 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000795 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000796 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000797 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000798 } else {
799 switch (fRec.getHinting()) {
800 case SkPaint::kNo_Hinting:
801 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000802 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000803 break;
804 case SkPaint::kSlight_Hinting:
805 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
806 break;
807 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000808 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000809 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700810#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
811 } else {
812 loadFlags = FT_LOAD_NO_AUTOHINT;
813#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000814 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000815 break;
816 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000817 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000818 loadFlags = FT_LOAD_FORCE_AUTOHINT;
819 break;
820 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000821 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000822 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000823 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000824 loadFlags = FT_LOAD_TARGET_LCD_V;
825 } else {
826 loadFlags = FT_LOAD_TARGET_LCD;
827 }
reed@google.comea2333d2011-03-14 16:44:56 +0000828 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000829 break;
830 default:
831 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
832 break;
833 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000834 }
835
reed@google.comeffc5012011-06-27 16:44:46 +0000836 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000837 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000838 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000839
reed@google.com96a9f7912011-05-06 11:49:30 +0000840 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
841 // advances, as fontconfig and cairo do.
842 // See http://code.google.com/p/skia/issues/detail?id=222.
843 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
844
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000845 // Use vertical layout if requested.
846 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
847 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
848 }
849
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000850 loadFlags |= FT_LOAD_COLOR;
851
reed@android.come4d0bc02009-07-24 19:53:20 +0000852 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000853 }
854
bungemanaabd71c2016-03-01 15:15:09 -0800855 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
mtklein5f939ab2016-03-16 10:28:35 -0700856 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([&ftFace]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800857 FT_Size size;
858 FT_Error err = FT_New_Size(ftFace.get(), &size);
859 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700860 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800861 return nullptr;
862 }
863 return size;
864 }());
865 if (nullptr == ftSize) {
866 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000867 return;
868 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000869
bungemanaabd71c2016-03-01 15:15:09 -0800870 FT_Error err = FT_Activate_Size(ftSize.get());
871 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700872 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800873 return;
874 }
875
876 if (FT_IS_SCALABLE(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700877 err = FT_Set_Char_Size(ftFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000878 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700879 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
880 ftFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000881 return;
882 }
bungemanaabd71c2016-03-01 15:15:09 -0800883 } else if (FT_HAS_FIXED_SIZES(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700884 fStrikeIndex = chooseBitmapStrike(ftFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000885 if (fStrikeIndex == -1) {
bungeman401ae2d2016-07-18 15:46:27 -0700886 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n", ftFace->family_name, fScale.fY));
887 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000888 }
bungeman401ae2d2016-07-18 15:46:27 -0700889
890 err = FT_Select_Size(ftFace.get(), fStrikeIndex);
891 if (err != 0) {
892 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
893 ftFace->family_name, fStrikeIndex, err));
894 fStrikeIndex = -1;
895 return;
896 }
897
898 // A non-ideal size was picked, so recompute the matrix.
899 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
900 fMatrix22Scalar.preScale(fScale.x() / ftFace->size->metrics.x_ppem,
901 fScale.y() / ftFace->size->metrics.y_ppem);
902 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
903 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
904 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
905 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
906
907 // FreeType does not provide linear metrics for bitmap fonts.
908 linearMetrics = false;
909
910 // FreeType documentation says:
911 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
912 // Bitmap-only fonts ignore this flag.
913 //
914 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
915 // Force this flag off for bitmap only fonts.
916 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000917 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700918 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFace->family_name, fScale.fY));
919 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000920 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000921
bungemanaabd71c2016-03-01 15:15:09 -0800922 fFTSize = ftSize.release();
923 fFace = ftFace.release();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000924 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000925}
926
927SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000928 SkAutoMutexAcquire ac(gFTMutex);
929
halcanary96fcdcc2015-08-27 07:41:13 -0700930 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000931 FT_Done_Size(fFTSize);
932 }
933
halcanary96fcdcc2015-08-27 07:41:13 -0700934 if (fFace != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000935 unref_ft_face(fFace);
936 }
bungeman9dc24682014-12-01 14:01:32 -0800937
938 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000939}
940
941/* We call this before each use of the fFace, since we may be sharing
942 this face with other context (at different sizes).
943*/
944FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800945 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000946 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000947 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000948 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000949 }
halcanary96fcdcc2015-08-27 07:41:13 -0700950 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000951 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000952}
953
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000954unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000955 return fFace->num_glyphs;
956}
957
958uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -0800959 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960 return SkToU16(FT_Get_Char_Index( fFace, uni ));
961}
962
reed@android.com9d3a9852010-01-08 14:07:42 +0000963SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -0800964 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +0000965 // iterate through each cmap entry, looking for matching glyph indices
966 FT_UInt glyphIndex;
967 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
968
969 while (glyphIndex != 0) {
970 if (glyphIndex == glyph) {
971 return charCode;
972 }
973 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
974 }
975
976 return 0;
977}
978
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700979static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
980 return SkFixedToScalar(x);
981}
982
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000984 /* unhinted and light hinted text have linearly scaled advances
985 * which are very cheap to compute with some font formats...
986 */
reed@google.combdc99882011-11-21 14:36:57 +0000987 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000988 SkAutoMutexAcquire ac(gFTMutex);
989
990 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000991 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000992 return;
993 }
994
995 FT_Error error;
996 FT_Fixed advance;
997
djsollen1b277042014-08-06 06:58:06 -0700998 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +0000999 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
1000 &advance );
1001 if (0 == error) {
1002 glyph->fRsbDelta = 0;
1003 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001004 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
1005 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001006 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001007 return;
1008 }
1009 }
bungeman5ec443c2014-11-21 13:18:34 -08001010
reed@android.com8a1c16f2008-12-17 15:59:43 +00001011 /* otherwise, we need to load/hint the glyph, which is slower */
1012 this->generateMetrics(glyph);
1013 return;
1014}
1015
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001016void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
1017 FT_BBox* bbox,
1018 bool snapToPixelBoundary) {
1019
1020 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1021
1022 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +00001023 int dx = SkFixedToFDot6(glyph->getSubXFixed());
1024 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001025 // negate dy since freetype-y-goes-up and skia-y-goes-down
1026 bbox->xMin += dx;
1027 bbox->yMin -= dy;
1028 bbox->xMax += dx;
1029 bbox->yMax -= dy;
1030 }
1031
1032 // outset the box to integral boundaries
1033 if (snapToPixelBoundary) {
1034 bbox->xMin &= ~63;
1035 bbox->yMin &= ~63;
1036 bbox->xMax = (bbox->xMax + 63) & ~63;
1037 bbox->yMax = (bbox->yMax + 63) & ~63;
1038 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001039
1040 // Must come after snapToPixelBoundary so that the width and height are
1041 // consistent. Otherwise asserts will fire later on when generating the
1042 // glyph image.
1043 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1044 FT_Vector vector;
1045 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1046 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1047 FT_Vector_Transform(&vector, &fMatrix22);
1048 bbox->xMin += vector.x;
1049 bbox->xMax += vector.x;
1050 bbox->yMin += vector.y;
1051 bbox->yMax += vector.y;
1052 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001053}
1054
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001055bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1056 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001057 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001058 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001059 }
1060 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001061 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001062 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001063 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001064 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1065 return true;
1066}
1067
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001068void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1069 if (isLCD(fRec)) {
1070 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001071 glyph->fHeight += gFTLibrary->lcdExtra();
1072 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001073 } else {
bungeman9dc24682014-12-01 14:01:32 -08001074 glyph->fWidth += gFTLibrary->lcdExtra();
1075 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001076 }
1077 }
1078}
1079
bungeman401ae2d2016-07-18 15:46:27 -07001080bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1081 // If subpixel rendering of a bitmap *can* be done.
1082 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1083 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1084 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001085
bungeman401ae2d2016-07-18 15:46:27 -07001086 // If subpixel rendering of a bitmap *should* be done.
1087 // 1. If the face is not scalable then always allow subpixel rendering.
1088 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1089 // 2. If the matrix is already not identity the bitmap will already be resampled,
1090 // so resampling slightly differently shouldn't make much difference.
1091 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1092
1093 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001094}
1095
reed@android.com8a1c16f2008-12-17 15:59:43 +00001096void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1097 SkAutoMutexAcquire ac(gFTMutex);
1098
1099 glyph->fRsbDelta = 0;
1100 glyph->fLsbDelta = 0;
1101
1102 FT_Error err;
1103
1104 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001105 glyph->zeroMetrics();
1106 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001107 }
1108
djsollen1b277042014-08-06 06:58:06 -07001109 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001110 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001111 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001112 return;
1113 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001114 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001115
1116 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001117 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001118 if (0 == fFace->glyph->outline.n_contours) {
1119 glyph->fWidth = 0;
1120 glyph->fHeight = 0;
1121 glyph->fTop = 0;
1122 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001123 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001124 FT_BBox bbox;
1125 getBBoxForCurrentGlyph(glyph, &bbox, true);
1126
1127 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1128 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1129 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1130 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1131
1132 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001133 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001134 break;
1135
1136 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001137 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1138 FT_Vector vector;
1139 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1140 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1141 FT_Vector_Transform(&vector, &fMatrix22);
1142 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1143 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1144 }
1145
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001146 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1147 glyph->fMaskFormat = SkMask::kARGB32_Format;
1148 }
1149
bungeman401ae2d2016-07-18 15:46:27 -07001150 {
1151 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1152 -SkIntToScalar(fFace->glyph->bitmap_top),
1153 SkIntToScalar(fFace->glyph->bitmap.width),
1154 SkIntToScalar(fFace->glyph->bitmap.rows));
1155 fMatrix22Scalar.mapRect(&rect);
1156 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1157 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1158 SkFixedToScalar(glyph->getSubYFixed()));
1159 }
1160 SkIRect irect = rect.roundOut();
1161 glyph->fWidth = SkToU16(irect.width());
1162 glyph->fHeight = SkToU16(irect.height());
1163 glyph->fTop = SkToS16(irect.top());
1164 glyph->fLeft = SkToS16(irect.left());
1165 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001166 break;
1167
1168 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001169 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001170 glyph->zeroMetrics();
1171 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001172 }
1173
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001174 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1175 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001176 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001177 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001178 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001179 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001180 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1181 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001182 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001183 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001184 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001185 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1186 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001187 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001188 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001189 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1190 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001191
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001192 if (fRec.fFlags & kDevKernText_Flag) {
1193 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1194 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001195 }
1196 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001197 }
1198
reed@android.com8a1c16f2008-12-17 15:59:43 +00001199#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001200 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001201#endif
1202}
1203
bungeman5ec443c2014-11-21 13:18:34 -08001204static void clear_glyph_image(const SkGlyph& glyph) {
1205 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1206}
reed@google.comea2333d2011-03-14 16:44:56 +00001207
bungeman@google.coma76de722012-10-26 19:35:54 +00001208void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001209 SkAutoMutexAcquire ac(gFTMutex);
1210
reed@android.com8a1c16f2008-12-17 15:59:43 +00001211 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001212 clear_glyph_image(glyph);
1213 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001214 }
1215
bungeman5ec443c2014-11-21 13:18:34 -08001216 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001217 if (err != 0) {
1218 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 -08001219 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1220 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001221 return;
1222 }
1223
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001224 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001225 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1226 SkMatrix subpixelBitmapMatrix;
1227 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1228 subpixelBitmapMatrix = fMatrix22Scalar;
1229 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1230 SkFixedToScalar(glyph.getSubYFixed()));
1231 bitmapMatrix = &subpixelBitmapMatrix;
1232 }
1233 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001234}
1235
reed@android.com8a1c16f2008-12-17 15:59:43 +00001236
bungeman5ec443c2014-11-21 13:18:34 -08001237void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001238 SkAutoMutexAcquire ac(gFTMutex);
1239
caryclarka10742c2014-09-18 11:00:40 -07001240 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001241
1242 if (this->setupSize()) {
1243 path->reset();
1244 return;
1245 }
1246
1247 uint32_t flags = fLoadGlyphFlags;
1248 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1249 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1250
djsollen1b277042014-08-06 06:58:06 -07001251 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001252
1253 if (err != 0) {
1254 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001255 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001256 path->reset();
1257 return;
1258 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001259 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001260
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001261 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001262
1263 // The path's origin from FreeType is always the horizontal layout origin.
1264 // Offset the path so that it is relative to the vertical origin if needed.
1265 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1266 FT_Vector vector;
1267 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1268 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1269 FT_Vector_Transform(&vector, &fMatrix22);
1270 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1271 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001272}
1273
bungeman41078062014-07-07 08:16:37 -07001274void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001275 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001276 return;
1277 }
1278
bungeman41078062014-07-07 08:16:37 -07001279 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001280
1281 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001282 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001283 return;
1284 }
1285
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001286 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001287
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001288 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1289 SkScalar upem = SkIntToScalar(face->units_per_EM);
1290 if (!upem) {
1291 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1292 if (ttHeader) {
1293 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001294 }
1295 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001296
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001297 // use the os/2 table as a source of reasonable defaults.
1298 SkScalar x_height = 0.0f;
1299 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001300 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001301 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1302 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001303 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001304 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001305 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001306 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001307 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001308 }
1309
1310 // pull from format-specific metrics as needed
1311 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001312 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001313 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001314 // FreeType will always use HHEA metrics if they're not zero.
1315 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1316 // It also ignores the VDMX tables, which are also of interest here
1317 // (and override everything else when they apply).
1318 static const int kUseTypoMetricsMask = (1 << 7);
1319 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1320 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1321 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1322 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1323 } else {
1324 ascent = -SkIntToScalar(face->ascender) / upem;
1325 descent = -SkIntToScalar(face->descender) / upem;
1326 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1327 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001328 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1329 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1330 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1331 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001332 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001333 underlinePosition = -SkIntToScalar(face->underline_position +
1334 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001335
bungeman41078062014-07-07 08:16:37 -07001336 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1337 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1338
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001339 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001340 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001341 FT_BBox bbox;
1342 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001343 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1344 }
1345 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001346 if (!cap_height) {
1347 FT_BBox bbox;
1348 if (getCBoxForLetter('H', &bbox)) {
1349 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1350 }
1351 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001352 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1353 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1354 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1355 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1356 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001357 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001358 xmin = 0.0f;
1359 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1360 ymin = descent + leading;
1361 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001362 underlineThickness = 0;
1363 underlinePosition = 0;
1364
bungeman41078062014-07-07 08:16:37 -07001365 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1366 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001367 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001368 sk_bzero(metrics, sizeof(*metrics));
1369 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001370 }
1371
1372 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1373 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001374 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001375 }
1376 if (!avgCharWidth) {
1377 avgCharWidth = xmax - xmin;
1378 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001379 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001380 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001381 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001382
1383 // disallow negative linespacing
1384 if (leading < 0.0f) {
1385 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001386 }
1387
bungeman53790512016-07-21 13:32:09 -07001388 metrics->fTop = ymax * fScale.y();
1389 metrics->fAscent = ascent * fScale.y();
1390 metrics->fDescent = descent * fScale.y();
1391 metrics->fBottom = ymin * fScale.y();
1392 metrics->fLeading = leading * fScale.y();
1393 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1394 metrics->fXMin = xmin * fScale.y();
1395 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001396 metrics->fXHeight = x_height;
1397 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001398 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1399 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001400}
1401
djsollenfcfea992015-01-09 08:18:13 -08001402///////////////////////////////////////////////////////////////////////////////
1403
1404// hand-tuned value to reduce outline embolden strength
1405#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1406 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1407 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1408 #else
1409 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1410 #endif
1411#endif
1412
1413///////////////////////////////////////////////////////////////////////////////
1414
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001415void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1416{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001417 // check to see if the embolden bit is set
1418 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1419 return;
1420 }
1421
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001422 switch (glyph->format) {
1423 case FT_GLYPH_FORMAT_OUTLINE:
1424 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001425 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1426 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001427 FT_Outline_Embolden(&glyph->outline, strength);
1428 break;
1429 case FT_GLYPH_FORMAT_BITMAP:
1430 FT_GlyphSlot_Own_Bitmap(glyph);
1431 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1432 break;
1433 default:
1434 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001435 }
1436}
1437
reed@google.comb4162b12013-07-02 16:32:29 +00001438///////////////////////////////////////////////////////////////////////////////
1439
1440#include "SkUtils.h"
1441
1442static SkUnichar next_utf8(const void** chars) {
1443 return SkUTF8_NextUnichar((const char**)chars);
1444}
1445
1446static SkUnichar next_utf16(const void** chars) {
1447 return SkUTF16_NextUnichar((const uint16_t**)chars);
1448}
1449
1450static SkUnichar next_utf32(const void** chars) {
1451 const SkUnichar** uniChars = (const SkUnichar**)chars;
1452 SkUnichar uni = **uniChars;
1453 *uniChars += 1;
1454 return uni;
1455}
1456
1457typedef SkUnichar (*EncodingProc)(const void**);
1458
1459static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1460 static const EncodingProc gProcs[] = {
1461 next_utf8, next_utf16, next_utf32
1462 };
1463 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1464 return gProcs[enc];
1465}
1466
1467int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001468 uint16_t glyphs[], int glyphCount) const
1469{
reed@google.comb4162b12013-07-02 16:32:29 +00001470 AutoFTAccess fta(this);
1471 FT_Face face = fta.face();
1472 if (!face) {
1473 if (glyphs) {
1474 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1475 }
1476 return 0;
1477 }
1478
1479 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1480
halcanary96fcdcc2015-08-27 07:41:13 -07001481 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001482 for (int i = 0; i < glyphCount; ++i) {
1483 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1484 return i;
1485 }
1486 }
1487 return glyphCount;
1488 } else {
1489 int first = glyphCount;
1490 for (int i = 0; i < glyphCount; ++i) {
1491 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1492 glyphs[i] = SkToU16(id);
1493 if (0 == id && i < first) {
1494 first = i;
1495 }
1496 }
1497 return first;
1498 }
1499}
1500
1501int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001502 AutoFTAccess fta(this);
1503 FT_Face face = fta.face();
1504 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001505}
1506
bungeman@google.com839702b2013-08-07 17:09:22 +00001507SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001508 SkTypeface::LocalizedStrings* nameIter =
1509 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001510 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001511 SkString familyName;
1512 this->getFamilyName(&familyName);
1513 SkString language("und"); //undetermined
1514 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1515 }
1516 return nameIter;
1517}
1518
bungeman@google.comddc218e2013-08-01 22:29:43 +00001519int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1520 AutoFTAccess fta(this);
1521 FT_Face face = fta.face();
1522
1523 FT_ULong tableCount = 0;
1524 FT_Error error;
1525
halcanary96fcdcc2015-08-27 07:41:13 -07001526 // When 'tag' is nullptr, returns number of tables in 'length'.
1527 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001528 if (error) {
1529 return 0;
1530 }
1531
1532 if (tags) {
1533 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1534 FT_ULong tableTag;
1535 FT_ULong tablelength;
1536 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1537 if (error) {
1538 return 0;
1539 }
1540 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1541 }
1542 }
1543 return tableCount;
1544}
1545
1546size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1547 size_t length, void* data) const
1548{
1549 AutoFTAccess fta(this);
1550 FT_Face face = fta.face();
1551
1552 FT_ULong tableLength = 0;
1553 FT_Error error;
1554
1555 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001556 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001557 if (error) {
1558 return 0;
1559 }
1560
1561 if (offset > tableLength) {
1562 return 0;
1563 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001564 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001565 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001566 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1567 if (error) {
1568 return 0;
1569 }
1570 }
1571
1572 return size;
1573}
1574
reed@google.comb4162b12013-07-02 16:32:29 +00001575///////////////////////////////////////////////////////////////////////////////
1576///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001577
halcanary96fcdcc2015-08-27 07:41:13 -07001578SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001579 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1580 return;
bungeman14df8332014-10-28 15:07:23 -07001581 }
bungeman9dc24682014-12-01 14:01:32 -08001582 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001583}
1584SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001585 if (fLibrary) {
1586 FT_Done_Library(fLibrary);
1587 }
bungeman14df8332014-10-28 15:07:23 -07001588}
1589
1590FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1591 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001592{
halcanary96fcdcc2015-08-27 07:41:13 -07001593 if (fLibrary == nullptr) {
1594 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001595 }
1596
bungeman14df8332014-10-28 15:07:23 -07001597 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001598 memset(&args, 0, sizeof(args));
1599
1600 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001601
bsalomon49f085d2014-09-05 13:34:00 -07001602 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001603 args.flags = FT_OPEN_MEMORY;
1604 args.memory_base = (const FT_Byte*)memoryBase;
1605 args.memory_size = stream->getLength();
1606 } else {
bungeman14df8332014-10-28 15:07:23 -07001607 memset(ftStream, 0, sizeof(*ftStream));
1608 ftStream->size = stream->getLength();
1609 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001610 ftStream->read = sk_ft_stream_io;
1611 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001612
1613 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001614 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001615 }
1616
1617 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001618 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001619 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001620 }
1621 return face;
1622}
1623
1624bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1625 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1626
1627 FT_StreamRec streamRec;
1628 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001629 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001630 return false;
1631 }
1632
1633 *numFaces = face->num_faces;
1634
1635 FT_Done_Face(face);
1636 return true;
1637}
1638
1639#include "SkTSearch.h"
1640bool SkTypeface_FreeType::Scanner::scanFont(
bungeman41868fe2015-05-20 09:21:04 -07001641 SkStream* stream, int ttcIndex,
1642 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001643{
1644 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1645
1646 FT_StreamRec streamRec;
1647 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001648 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001649 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001650 }
1651
bungemana4c4a2d2014-10-20 13:33:19 -07001652 int weight = SkFontStyle::kNormal_Weight;
1653 int width = SkFontStyle::kNormal_Width;
1654 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001655 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001656 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001657 }
1658 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001659 slant = SkFontStyle::kItalic_Slant;
1660 }
1661
1662 PS_FontInfoRec psFontInfo;
1663 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1664 if (os2 && os2->version != 0xffff) {
1665 weight = os2->usWeightClass;
1666 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001667
1668 // OS/2::fsSelection bit 9 indicates oblique.
1669 if (SkToBool(os2->fsSelection & (1u << 9))) {
1670 slant = SkFontStyle::kOblique_Slant;
1671 }
bungemana4c4a2d2014-10-20 13:33:19 -07001672 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1673 static const struct {
1674 char const * const name;
1675 int const weight;
1676 } commonWeights [] = {
1677 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001678 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001679 { "black", SkFontStyle::kBlack_Weight },
1680 { "bold", SkFontStyle::kBold_Weight },
1681 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1682 { "demi", SkFontStyle::kSemiBold_Weight },
1683 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001684 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001685 { "extrabold", SkFontStyle::kExtraBold_Weight },
1686 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001687 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001688 { "heavy", SkFontStyle::kBlack_Weight },
1689 { "light", SkFontStyle::kLight_Weight },
1690 { "medium", SkFontStyle::kMedium_Weight },
1691 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001692 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001693 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001694 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001695 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001696 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001697 { "thin", SkFontStyle::kThin_Weight },
1698 { "ultra", SkFontStyle::kExtraBold_Weight },
1699 { "ultrablack", 1000 },
1700 { "ultrabold", SkFontStyle::kExtraBold_Weight },
1701 { "ultraheavy", 1000 },
1702 { "ultralight", SkFontStyle::kExtraLight_Weight },
1703 };
1704 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001705 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001706 if (index >= 0) {
1707 weight = commonWeights[index].weight;
1708 } else {
bungeman14df8332014-10-28 15:07:23 -07001709 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001710 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001711 }
1712
1713 if (name) {
1714 name->set(face->family_name);
1715 }
1716 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001717 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001718 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001719 if (isFixedPitch) {
1720 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001721 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001722
bungeman41868fe2015-05-20 09:21:04 -07001723 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001724 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001725 FT_Error err = FT_Get_MM_Var(face, &variations);
1726 if (err) {
1727 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1728 face->family_name));
1729 return false;
1730 }
1731 SkAutoFree autoFreeVariations(variations);
1732
1733 axes->reset(variations->num_axis);
1734 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1735 const FT_Var_Axis& ftAxis = variations->axis[i];
1736 (*axes)[i].fTag = ftAxis.tag;
1737 (*axes)[i].fMinimum = ftAxis.minimum;
1738 (*axes)[i].fDefault = ftAxis.def;
1739 (*axes)[i].fMaximum = ftAxis.maximum;
1740 }
1741 }
bungeman41868fe2015-05-20 09:21:04 -07001742
reed@android.com8a1c16f2008-12-17 15:59:43 +00001743 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001744 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001745}
bungemanf6c71072016-01-21 14:17:47 -08001746
1747/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1748 AxisDefinitions axisDefinitions,
1749 const SkFontMgr::FontParameters::Axis* requestedAxes, int requestedAxisCount,
1750 SkFixed* axisValues,
1751 const SkString& name)
1752{
1753 for (int i = 0; i < axisDefinitions.count(); ++i) {
1754 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001755 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1756 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001757 axisValues[i] = axisDefinition.fDefault;
1758 for (int j = 0; j < requestedAxisCount; ++j) {
1759 const SkFontMgr::FontParameters::Axis& axisSpecified = requestedAxes[j];
1760 if (axisDefinition.fTag == axisSpecified.fTag) {
benjaminwagner64a3c952016-02-25 12:20:40 -08001761 const SkScalar axisValue = SkTPin(axisSpecified.fStyleValue, axisMin, axisMax);
1762 if (axisSpecified.fStyleValue != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001763 SkDEBUGF(("Requested font axis value out of range: "
1764 "%s '%c%c%c%c' %f; pinned to %f.\n",
1765 name.c_str(),
1766 (axisDefinition.fTag >> 24) & 0xFF,
1767 (axisDefinition.fTag >> 16) & 0xFF,
1768 (axisDefinition.fTag >> 8) & 0xFF,
1769 (axisDefinition.fTag ) & 0xFF,
1770 SkScalarToDouble(axisSpecified.fStyleValue),
benjaminwagner64a3c952016-02-25 12:20:40 -08001771 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001772 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001773 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001774 break;
1775 }
1776 }
1777 // TODO: warn on defaulted axis?
1778 }
1779
1780 SkDEBUGCODE(
1781 // Check for axis specified, but not matched in font.
1782 for (int i = 0; i < requestedAxisCount; ++i) {
1783 SkFourByteTag skTag = requestedAxes[i].fTag;
1784 bool found = false;
1785 for (int j = 0; j < axisDefinitions.count(); ++j) {
1786 if (skTag == axisDefinitions[j].fTag) {
1787 found = true;
1788 break;
1789 }
1790 }
1791 if (!found) {
1792 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1793 name.c_str(),
1794 (skTag >> 24) & 0xFF,
1795 (skTag >> 16) & 0xFF,
1796 (skTag >> 8) & 0xFF,
1797 (skTag) & 0xFF));
1798 }
1799 }
1800 )
1801}