blob: 6681c9c1ef4f42b0a448cebf644a7c14ac6f6c0c [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));
halcanary32875882016-08-16 09:36:23 -0700467
vandebo0f9bad02014-06-19 11:05:39 -0700468 if (FT_HAS_MULTIPLE_MASTERS(face)) {
halcanary32875882016-08-16 09:36:23 -0700469 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700470 }
471 if (!canEmbed(face)) {
halcanary32875882016-08-16 09:36:23 -0700472 info->fFlags |= SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700473 }
474 if (!canSubset(face)) {
halcanary32875882016-08-16 09:36:23 -0700475 info->fFlags |= SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag;
vandebo0f9bad02014-06-19 11:05:39 -0700476 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000477 info->fLastGlyphID = face->num_glyphs - 1;
478 info->fEmSize = 1000;
479
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000480 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000481 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000482 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000483 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000484 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000485 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000486 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000487 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000488 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000489 TT_Header* ttHeader;
bungemanf1491692016-07-22 11:19:24 -0700490 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head)) != nullptr) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000491 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000492 }
bungeman@google.com4d71db82013-12-02 19:10:02 +0000493 } else {
494 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000495 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000496
halcanary32875882016-08-16 09:36:23 -0700497 info->fStyle = (SkAdvancedTypefaceMetrics::StyleFlags)0;
bungemanf1491692016-07-22 11:19:24 -0700498 if (FT_IS_FIXED_WIDTH(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000499 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
bungemanf1491692016-07-22 11:19:24 -0700500 }
501 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000502 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
bungemanf1491692016-07-22 11:19:24 -0700503 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000504
bungemanf1491692016-07-22 11:19:24 -0700505 PS_FontInfoRec psFontInfo;
506 TT_Postscript* postTable;
507 if (FT_Get_PS_Font_Info(face, &psFontInfo) == 0) {
508 info->fItalicAngle = psFontInfo.italic_angle;
509 } else if ((postTable = (TT_Postscript*)FT_Get_Sfnt_Table(face, ft_sfnt_post)) != nullptr) {
510 info->fItalicAngle = SkFixedToScalar(postTable->italicAngle);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000511 } else {
512 info->fItalicAngle = 0;
513 }
514
515 info->fAscent = face->ascender;
516 info->fDescent = face->descender;
517
518 // Figure out a good guess for StemV - Min width of i, I, !, 1.
519 // This probably isn't very good with an italic font.
520 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000521 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000522 char stem_chars[] = {'i', 'I', '!', '1'};
523 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
524 FT_BBox bbox;
525 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
526 int16_t width = bbox.xMax - bbox.xMin;
527 if (width > 0 && width < min_width) {
528 min_width = width;
529 info->fStemV = min_width;
530 }
531 }
532 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000533
bungemanf1491692016-07-22 11:19:24 -0700534 TT_PCLT* pcltTable;
535 TT_OS2* os2Table;
536 if ((pcltTable = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != nullptr) {
537 info->fCapHeight = pcltTable->CapHeight;
538 uint8_t serif_style = pcltTable->SerifStyle & 0x3F;
539 if (2 <= serif_style && serif_style <= 6) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000540 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
bungemanf1491692016-07-22 11:19:24 -0700541 } else if (9 <= serif_style && serif_style <= 12) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000542 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
bungemanf1491692016-07-22 11:19:24 -0700543 }
544 } else if (((os2Table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != nullptr) &&
bungeman@google.comcbe1b542013-12-16 17:02:39 +0000545 // sCapHeight is available only when version 2 or later.
bungemanf1491692016-07-22 11:19:24 -0700546 os2Table->version != 0xFFFF &&
547 os2Table->version >= 2)
548 {
549 info->fCapHeight = os2Table->sCapHeight;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000550 } else {
551 // Figure out a good guess for CapHeight: average the height of M and X.
552 FT_BBox m_bbox, x_bbox;
553 bool got_m, got_x;
554 got_m = GetLetterCBox(face, 'M', &m_bbox);
555 got_x = GetLetterCBox(face, 'X', &x_bbox);
556 if (got_m && got_x) {
bungemanf1491692016-07-22 11:19:24 -0700557 info->fCapHeight = ((m_bbox.yMax - m_bbox.yMin) + (x_bbox.yMax - x_bbox.yMin)) / 2;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000558 } else if (got_m && !got_x) {
559 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
560 } else if (!got_m && got_x) {
561 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
bungeman@google.com12bd4a02013-12-19 19:34:22 +0000562 } else {
563 // Last resort, use the ascent.
564 info->fCapHeight = info->fAscent;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000565 }
566 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000567
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000568 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
569 face->bbox.xMax, face->bbox.yMin);
570
vandebo0f9bad02014-06-19 11:05:39 -0700571 if (!FT_IS_SCALABLE(face)) {
reed39a9a502015-05-12 09:50:04 -0700572 perGlyphInfo = kNo_PerGlyphInfo;
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000573 }
574
reed39a9a502015-05-12 09:50:04 -0700575 if (perGlyphInfo & kGlyphNames_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700576 info->fType == SkAdvancedTypefaceMetrics::kType1_Font)
577 {
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000578 // Postscript fonts may contain more than 255 glyphs, so we end up
579 // using multiple font descriptions with a glyph ordering. Record
580 // the name of each glyph.
halcanary8b1d32c2016-08-08 09:09:59 -0700581 info->fGlyphNames.reset(face->num_glyphs);
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000582 for (int gID = 0; gID < face->num_glyphs; gID++) {
583 char glyphName[128]; // PS limit for names is 127 bytes.
584 FT_Get_Glyph_Name(face, gID, glyphName, 128);
halcanary8b1d32c2016-08-08 09:09:59 -0700585 info->fGlyphNames[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000586 }
587 }
588
reed39a9a502015-05-12 09:50:04 -0700589 if (perGlyphInfo & kToUnicode_PerGlyphInfo &&
bungemanf1491692016-07-22 11:19:24 -0700590 info->fType != SkAdvancedTypefaceMetrics::kType1_Font &&
591 face->num_charmaps)
592 {
vandebo@chromium.org6744d492011-05-09 18:13:47 +0000593 populate_glyph_to_unicode(face, &(info->fGlyphToUnicode));
594 }
595
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000596 return info;
597}
vandebo@chromium.org37ad8fb2011-08-18 02:38:50 +0000598
reed@google.com618ef5e2011-01-26 22:10:41 +0000599///////////////////////////////////////////////////////////////////////////
600
reed@google.com8ed436c2011-07-21 14:12:36 +0000601static bool bothZero(SkScalar a, SkScalar b) {
602 return 0 == a && 0 == b;
603}
604
605// returns false if there is any non-90-rotation or skew
606static bool isAxisAligned(const SkScalerContext::Rec& rec) {
607 return 0 == rec.fPreSkewX &&
608 (bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
609 bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
610}
611
reeda9322c22016-04-12 06:47:05 -0700612SkScalerContext* SkTypeface_FreeType::onCreateScalerContext(const SkScalerContextEffects& effects,
613 const SkDescriptor* desc) const {
halcanary385fe4d2015-08-26 13:07:48 -0700614 SkScalerContext_FreeType* c =
reeda9322c22016-04-12 06:47:05 -0700615 new SkScalerContext_FreeType(const_cast<SkTypeface_FreeType*>(this), effects, desc);
reed@google.com0da48612013-03-19 16:06:52 +0000616 if (!c->success()) {
halcanary385fe4d2015-08-26 13:07:48 -0700617 delete c;
halcanary96fcdcc2015-08-27 07:41:13 -0700618 c = nullptr;
reed@google.com0da48612013-03-19 16:06:52 +0000619 }
620 return c;
621}
622
623void SkTypeface_FreeType::onFilterRec(SkScalerContextRec* rec) const {
bungeman@google.com8cf32262012-04-02 14:34:30 +0000624 //BOGUS: http://code.google.com/p/chromium/issues/detail?id=121119
625 //Cap the requested size as larger sizes give bogus values.
626 //Remove when http://code.google.com/p/skia/issues/detail?id=554 is fixed.
bungemanaabd71c2016-03-01 15:15:09 -0800627 //Note that this also currently only protects against large text size requests,
628 //the total matrix is not taken into account here.
bungeman@google.com5582e632012-04-02 14:51:54 +0000629 if (rec->fTextSize > SkIntToScalar(1 << 14)) {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000630 rec->fTextSize = SkIntToScalar(1 << 14);
bungeman@google.com8cf32262012-04-02 14:34:30 +0000631 }
skia.committer@gmail.coma27096b2012-08-30 14:38:00 +0000632
bungemanec7e12f2015-01-21 11:55:16 -0800633 if (isLCD(*rec)) {
bungemand4742fa2015-01-21 11:19:22 -0800634 // TODO: re-work so that FreeType is set-up and selected by the SkFontMgr.
635 SkAutoMutexAcquire ama(gFTMutex);
636 ref_ft_library();
bungemanec7e12f2015-01-21 11:55:16 -0800637 if (!gFTLibrary->isLCDSupported()) {
bungemand4742fa2015-01-21 11:19:22 -0800638 // If the runtime Freetype library doesn't support LCD, disable it here.
639 rec->fMaskFormat = SkMask::kA8_Format;
640 }
641 unref_ft_library();
reed@google.com618ef5e2011-01-26 22:10:41 +0000642 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000643
reed@google.com618ef5e2011-01-26 22:10:41 +0000644 SkPaint::Hinting h = rec->getHinting();
reed@google.comeffc5012011-06-27 16:44:46 +0000645 if (SkPaint::kFull_Hinting == h && !isLCD(*rec)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000646 // collapse full->normal hinting if we're not doing LCD
647 h = SkPaint::kNormal_Hinting;
reed@google.com618ef5e2011-01-26 22:10:41 +0000648 }
bungeman@google.comf4f2b802012-03-08 19:19:51 +0000649 if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag)) {
reed@google.com1ac83502012-02-28 17:06:02 +0000650 if (SkPaint::kNo_Hinting != h) {
651 h = SkPaint::kSlight_Hinting;
652 }
653 }
654
reed@google.com8ed436c2011-07-21 14:12:36 +0000655 // rotated text looks bad with hinting, so we disable it as needed
656 if (!isAxisAligned(*rec)) {
657 h = SkPaint::kNo_Hinting;
658 }
reed@google.com618ef5e2011-01-26 22:10:41 +0000659 rec->setHinting(h);
reed@google.comffe49f52011-11-22 19:42:41 +0000660
bungeman@google.com97efada2012-07-30 20:40:50 +0000661#ifndef SK_GAMMA_APPLY_TO_A8
662 if (!isLCD(*rec)) {
brianosmana1e8f8d2016-04-08 06:47:54 -0700663 // SRGBTODO: Is this correct? Do we want contrast boost?
664 rec->ignorePreBlend();
reed@google.comffe49f52011-11-22 19:42:41 +0000665 }
reed@google.com1ac83502012-02-28 17:06:02 +0000666#endif
reed@google.com618ef5e2011-01-26 22:10:41 +0000667}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000668
reed@google.com38c37dd2013-03-21 15:36:26 +0000669int SkTypeface_FreeType::onGetUPEM() const {
reed@google.comb4162b12013-07-02 16:32:29 +0000670 AutoFTAccess fta(this);
671 FT_Face face = fta.face();
672 return face ? face->units_per_EM : 0;
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000673}
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000674
reed@google.com35fe7372013-10-30 15:07:03 +0000675bool SkTypeface_FreeType::onGetKerningPairAdjustments(const uint16_t glyphs[],
676 int count, int32_t adjustments[]) const {
677 AutoFTAccess fta(this);
678 FT_Face face = fta.face();
679 if (!face || !FT_HAS_KERNING(face)) {
680 return false;
681 }
682
683 for (int i = 0; i < count - 1; ++i) {
684 FT_Vector delta;
685 FT_Error err = FT_Get_Kerning(face, glyphs[i], glyphs[i+1],
686 FT_KERNING_UNSCALED, &delta);
687 if (err) {
688 return false;
689 }
690 adjustments[i] = delta.x;
691 }
692 return true;
693}
694
bungeman401ae2d2016-07-18 15:46:27 -0700695/** Returns the bitmap strike equal to or just larger than the requested size. */
benjaminwagner45345622016-02-19 15:30:20 -0800696static FT_Int chooseBitmapStrike(FT_Face face, FT_F26Dot6 scaleY) {
halcanary96fcdcc2015-08-27 07:41:13 -0700697 if (face == nullptr) {
bungeman401ae2d2016-07-18 15:46:27 -0700698 SkDEBUGF(("chooseBitmapStrike aborted due to nullptr face.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000699 return -1;
700 }
bungeman401ae2d2016-07-18 15:46:27 -0700701
702 FT_Pos requestedPPEM = scaleY; // FT_Bitmap_Size::y_ppem is in 26.6 format.
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000703 FT_Int chosenStrikeIndex = -1;
704 FT_Pos chosenPPEM = 0;
705 for (FT_Int strikeIndex = 0; strikeIndex < face->num_fixed_sizes; ++strikeIndex) {
bungeman401ae2d2016-07-18 15:46:27 -0700706 FT_Pos strikePPEM = face->available_sizes[strikeIndex].y_ppem;
707 if (strikePPEM == requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000708 // exact match - our search stops here
bungeman401ae2d2016-07-18 15:46:27 -0700709 return strikeIndex;
710 } else if (chosenPPEM < requestedPPEM) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000711 // attempt to increase chosenPPEM
bungeman401ae2d2016-07-18 15:46:27 -0700712 if (chosenPPEM < strikePPEM) {
713 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000714 chosenStrikeIndex = strikeIndex;
715 }
716 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700717 // attempt to decrease chosenPPEM, but not below requestedPPEM
718 if (requestedPPEM < strikePPEM && strikePPEM < chosenPPEM) {
719 chosenPPEM = strikePPEM;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000720 chosenStrikeIndex = strikeIndex;
721 }
722 }
723 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000724 return chosenStrikeIndex;
725}
726
reeda9322c22016-04-12 06:47:05 -0700727SkScalerContext_FreeType::SkScalerContext_FreeType(SkTypeface* typeface,
728 const SkScalerContextEffects& effects,
729 const SkDescriptor* desc)
730 : SkScalerContext_FreeType_Base(typeface, effects, desc)
bungemanaabd71c2016-03-01 15:15:09 -0800731 , fFace(nullptr)
732 , fFTSize(nullptr)
733 , fStrikeIndex(-1)
bungeman13a007d2015-06-19 05:09:39 -0700734{
reed@android.com8a1c16f2008-12-17 15:59:43 +0000735 SkAutoMutexAcquire ac(gFTMutex);
736
bungeman9dc24682014-12-01 14:01:32 -0800737 if (!ref_ft_library()) {
738 sk_throw();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000739 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000740
741 // load the font file
bungemanaabd71c2016-03-01 15:15:09 -0800742 using UnrefFTFace = SkFunctionWrapper<void, skstd::remove_pointer_t<FT_Face>, unref_ft_face>;
mtklein5f939ab2016-03-16 10:28:35 -0700743 std::unique_ptr<skstd::remove_pointer_t<FT_Face>, UnrefFTFace> ftFace(ref_ft_face(typeface));
bungemanaabd71c2016-03-01 15:15:09 -0800744 if (nullptr == ftFace) {
745 SkDEBUGF(("Could not create FT_Face.\n"));
reed@android.com62900b42009-02-11 15:07:19 +0000746 return;
747 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000748
bungeman5f14c5e2014-12-05 12:26:44 -0800749 fRec.computeMatrices(SkScalerContextRec::kFull_PreMatrixScale, &fScale, &fMatrix22Scalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000750
bungeman401ae2d2016-07-18 15:46:27 -0700751 FT_F26Dot6 scaleX = SkScalarToFDot6(fScale.fX);
752 FT_F26Dot6 scaleY = SkScalarToFDot6(fScale.fY);
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000753 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
bungeman401ae2d2016-07-18 15:46:27 -0700754 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
755 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
bungeman@google.comd3fbd342014-04-15 15:52:07 +0000756 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000757
reed@google.coma1bfa212012-03-08 21:57:12 +0000758 fLCDIsVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
759
reed@android.com8a1c16f2008-12-17 15:59:43 +0000760 // compute the flags we send to Load_Glyph
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000761 bool linearMetrics = SkToBool(fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000762 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000763 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000764
agl@chromium.org70a303f2010-05-10 14:15:50 +0000765 if (SkMask::kBW_Format == fRec.fMaskFormat) {
766 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
767 loadFlags = FT_LOAD_TARGET_MONO;
reed@google.comeffc5012011-06-27 16:44:46 +0000768 if (fRec.getHinting() == SkPaint::kNo_Hinting) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000769 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000770 linearMetrics = true;
reed@google.comeffc5012011-06-27 16:44:46 +0000771 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000772 } else {
773 switch (fRec.getHinting()) {
774 case SkPaint::kNo_Hinting:
775 loadFlags = FT_LOAD_NO_HINTING;
reed@google.combdc99882011-11-21 14:36:57 +0000776 linearMetrics = true;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000777 break;
778 case SkPaint::kSlight_Hinting:
779 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
780 break;
781 case SkPaint::kNormal_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000782 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000783 loadFlags = FT_LOAD_FORCE_AUTOHINT;
djsollen858a7892014-08-20 07:03:23 -0700784#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
785 } else {
786 loadFlags = FT_LOAD_NO_AUTOHINT;
787#endif
bungeman@google.comf6f56872014-01-23 19:01:36 +0000788 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000789 break;
790 case SkPaint::kFull_Hinting:
bungeman@google.comf6f56872014-01-23 19:01:36 +0000791 if (fRec.fFlags & SkScalerContext::kForceAutohinting_Flag) {
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000792 loadFlags = FT_LOAD_FORCE_AUTOHINT;
793 break;
794 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000795 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comeffc5012011-06-27 16:44:46 +0000796 if (isLCD(fRec)) {
reed@google.coma1bfa212012-03-08 21:57:12 +0000797 if (fLCDIsVert) {
reed@google.comeffc5012011-06-27 16:44:46 +0000798 loadFlags = FT_LOAD_TARGET_LCD_V;
799 } else {
800 loadFlags = FT_LOAD_TARGET_LCD;
801 }
reed@google.comea2333d2011-03-14 16:44:56 +0000802 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000803 break;
804 default:
805 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
806 break;
807 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000808 }
809
reed@google.comeffc5012011-06-27 16:44:46 +0000810 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0) {
agl@chromium.orge0d08992009-08-07 19:19:23 +0000811 loadFlags |= FT_LOAD_NO_BITMAP;
reed@google.comeffc5012011-06-27 16:44:46 +0000812 }
agl@chromium.orge0d08992009-08-07 19:19:23 +0000813
reed@google.com96a9f7912011-05-06 11:49:30 +0000814 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
815 // advances, as fontconfig and cairo do.
816 // See http://code.google.com/p/skia/issues/detail?id=222.
817 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
818
bungeman@google.com8ff8a192012-09-25 20:38:28 +0000819 // Use vertical layout if requested.
820 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
821 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
822 }
823
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000824 loadFlags |= FT_LOAD_COLOR;
825
reed@android.come4d0bc02009-07-24 19:53:20 +0000826 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000827 }
828
bungemanaabd71c2016-03-01 15:15:09 -0800829 using DoneFTSize = SkFunctionWrapper<FT_Error, skstd::remove_pointer_t<FT_Size>, FT_Done_Size>;
mtklein5f939ab2016-03-16 10:28:35 -0700830 std::unique_ptr<skstd::remove_pointer_t<FT_Size>, DoneFTSize> ftSize([&ftFace]() -> FT_Size {
bungemanaabd71c2016-03-01 15:15:09 -0800831 FT_Size size;
832 FT_Error err = FT_New_Size(ftFace.get(), &size);
833 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700834 SkDEBUGF(("FT_New_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800835 return nullptr;
836 }
837 return size;
838 }());
839 if (nullptr == ftSize) {
840 SkDEBUGF(("Could not create FT_Size.\n"));
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000841 return;
842 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000843
bungemanaabd71c2016-03-01 15:15:09 -0800844 FT_Error err = FT_Activate_Size(ftSize.get());
845 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700846 SkDEBUGF(("FT_Activate_Size(%s) returned 0x%x.\n", ftFace->family_name, err));
bungemanaabd71c2016-03-01 15:15:09 -0800847 return;
848 }
849
850 if (FT_IS_SCALABLE(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700851 err = FT_Set_Char_Size(ftFace.get(), scaleX, scaleY, 72, 72);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000852 if (err != 0) {
bungeman401ae2d2016-07-18 15:46:27 -0700853 SkDEBUGF(("FT_Set_CharSize(%s, %f, %f) returned 0x%x.\n",
854 ftFace->family_name, fScale.fX, fScale.fY, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000855 return;
856 }
bungemanaabd71c2016-03-01 15:15:09 -0800857 } else if (FT_HAS_FIXED_SIZES(ftFace)) {
bungeman401ae2d2016-07-18 15:46:27 -0700858 fStrikeIndex = chooseBitmapStrike(ftFace.get(), scaleY);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000859 if (fStrikeIndex == -1) {
bungeman401ae2d2016-07-18 15:46:27 -0700860 SkDEBUGF(("No glyphs for font \"%s\" size %f.\n", ftFace->family_name, fScale.fY));
861 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000862 }
bungeman401ae2d2016-07-18 15:46:27 -0700863
864 err = FT_Select_Size(ftFace.get(), fStrikeIndex);
865 if (err != 0) {
866 SkDEBUGF(("FT_Select_Size(%s, %d) returned 0x%x.\n",
867 ftFace->family_name, fStrikeIndex, err));
868 fStrikeIndex = -1;
869 return;
870 }
871
872 // A non-ideal size was picked, so recompute the matrix.
873 // This adjusts for the difference between FT_Set_Char_Size and FT_Select_Size.
874 fMatrix22Scalar.preScale(fScale.x() / ftFace->size->metrics.x_ppem,
875 fScale.y() / ftFace->size->metrics.y_ppem);
876 fMatrix22.xx = SkScalarToFixed(fMatrix22Scalar.getScaleX());
877 fMatrix22.xy = SkScalarToFixed(-fMatrix22Scalar.getSkewX());
878 fMatrix22.yx = SkScalarToFixed(-fMatrix22Scalar.getSkewY());
879 fMatrix22.yy = SkScalarToFixed(fMatrix22Scalar.getScaleY());
880
881 // FreeType does not provide linear metrics for bitmap fonts.
882 linearMetrics = false;
883
884 // FreeType documentation says:
885 // FT_LOAD_NO_BITMAP -- Ignore bitmap strikes when loading.
886 // Bitmap-only fonts ignore this flag.
887 //
888 // However, in FreeType 2.5.1 color bitmap only fonts do not ignore this flag.
889 // Force this flag off for bitmap only fonts.
890 fLoadGlyphFlags &= ~FT_LOAD_NO_BITMAP;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000891 } else {
bungeman401ae2d2016-07-18 15:46:27 -0700892 SkDEBUGF(("Unknown kind of font \"%s\" size %f.\n", fFace->family_name, fScale.fY));
893 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000894 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000895
bungemanaabd71c2016-03-01 15:15:09 -0800896 fFTSize = ftSize.release();
897 fFace = ftFace.release();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000898 fDoLinearMetrics = linearMetrics;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000899}
900
901SkScalerContext_FreeType::~SkScalerContext_FreeType() {
scroggo@google.com94bc60f2012-10-04 20:45:06 +0000902 SkAutoMutexAcquire ac(gFTMutex);
903
halcanary96fcdcc2015-08-27 07:41:13 -0700904 if (fFTSize != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000905 FT_Done_Size(fFTSize);
906 }
907
halcanary96fcdcc2015-08-27 07:41:13 -0700908 if (fFace != nullptr) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000909 unref_ft_face(fFace);
910 }
bungeman9dc24682014-12-01 14:01:32 -0800911
912 unref_ft_library();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000913}
914
915/* We call this before each use of the fFace, since we may be sharing
916 this face with other context (at different sizes).
917*/
918FT_Error SkScalerContext_FreeType::setupSize() {
bungeman3f846ae2015-11-03 11:07:20 -0800919 gFTMutex.assertHeld();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000920 FT_Error err = FT_Activate_Size(fFTSize);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000921 if (err != 0) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000922 return err;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000923 }
halcanary96fcdcc2015-08-27 07:41:13 -0700924 FT_Set_Transform(fFace, &fMatrix22, nullptr);
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +0000925 return 0;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000926}
927
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000928unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000929 return fFace->num_glyphs;
930}
931
932uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
bungeman3f846ae2015-11-03 11:07:20 -0800933 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000934 return SkToU16(FT_Get_Char_Index( fFace, uni ));
935}
936
reed@android.com9d3a9852010-01-08 14:07:42 +0000937SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
bungeman3f846ae2015-11-03 11:07:20 -0800938 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com9d3a9852010-01-08 14:07:42 +0000939 // iterate through each cmap entry, looking for matching glyph indices
940 FT_UInt glyphIndex;
941 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
942
943 while (glyphIndex != 0) {
944 if (glyphIndex == glyph) {
945 return charCode;
946 }
947 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
948 }
949
950 return 0;
951}
952
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700953static SkScalar SkFT_FixedToScalar(FT_Fixed x) {
954 return SkFixedToScalar(x);
955}
956
reed@android.com8a1c16f2008-12-17 15:59:43 +0000957void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000958 /* unhinted and light hinted text have linearly scaled advances
959 * which are very cheap to compute with some font formats...
960 */
reed@google.combdc99882011-11-21 14:36:57 +0000961 if (fDoLinearMetrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000962 SkAutoMutexAcquire ac(gFTMutex);
963
964 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000965 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000966 return;
967 }
968
969 FT_Error error;
970 FT_Fixed advance;
971
djsollen1b277042014-08-06 06:58:06 -0700972 error = FT_Get_Advance( fFace, glyph->getGlyphID(),
reed@android.com8a1c16f2008-12-17 15:59:43 +0000973 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
974 &advance );
975 if (0 == error) {
976 glyph->fRsbDelta = 0;
977 glyph->fLsbDelta = 0;
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700978 const SkScalar advanceScalar = SkFT_FixedToScalar(advance);
979 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -0700980 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000981 return;
982 }
983 }
bungeman5ec443c2014-11-21 13:18:34 -0800984
reed@android.com8a1c16f2008-12-17 15:59:43 +0000985 /* otherwise, we need to load/hint the glyph, which is slower */
986 this->generateMetrics(glyph);
987 return;
988}
989
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000990void SkScalerContext_FreeType::getBBoxForCurrentGlyph(SkGlyph* glyph,
991 FT_BBox* bbox,
992 bool snapToPixelBoundary) {
993
994 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
995
996 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
george@mozilla.comc59b5da2012-08-23 00:39:08 +0000997 int dx = SkFixedToFDot6(glyph->getSubXFixed());
998 int dy = SkFixedToFDot6(glyph->getSubYFixed());
djsollen@google.comd8b599c2012-03-19 19:44:19 +0000999 // negate dy since freetype-y-goes-up and skia-y-goes-down
1000 bbox->xMin += dx;
1001 bbox->yMin -= dy;
1002 bbox->xMax += dx;
1003 bbox->yMax -= dy;
1004 }
1005
1006 // outset the box to integral boundaries
1007 if (snapToPixelBoundary) {
1008 bbox->xMin &= ~63;
1009 bbox->yMin &= ~63;
1010 bbox->xMax = (bbox->xMax + 63) & ~63;
1011 bbox->yMax = (bbox->yMax + 63) & ~63;
1012 }
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001013
1014 // Must come after snapToPixelBoundary so that the width and height are
1015 // consistent. Otherwise asserts will fire later on when generating the
1016 // glyph image.
1017 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1018 FT_Vector vector;
1019 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1020 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1021 FT_Vector_Transform(&vector, &fMatrix22);
1022 bbox->xMin += vector.x;
1023 bbox->xMax += vector.x;
1024 bbox->yMin += vector.y;
1025 bbox->yMax += vector.y;
1026 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001027}
1028
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001029bool SkScalerContext_FreeType::getCBoxForLetter(char letter, FT_BBox* bbox) {
1030 const FT_UInt glyph_id = FT_Get_Char_Index(fFace, letter);
bungeman5ec443c2014-11-21 13:18:34 -08001031 if (!glyph_id) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001032 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001033 }
1034 if (FT_Load_Glyph(fFace, glyph_id, fLoadGlyphFlags) != 0) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001035 return false;
bungeman5ec443c2014-11-21 13:18:34 -08001036 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001037 emboldenIfNeeded(fFace, fFace->glyph);
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001038 FT_Outline_Get_CBox(&fFace->glyph->outline, bbox);
1039 return true;
1040}
1041
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001042void SkScalerContext_FreeType::updateGlyphIfLCD(SkGlyph* glyph) {
1043 if (isLCD(fRec)) {
1044 if (fLCDIsVert) {
bungeman9dc24682014-12-01 14:01:32 -08001045 glyph->fHeight += gFTLibrary->lcdExtra();
1046 glyph->fTop -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001047 } else {
bungeman9dc24682014-12-01 14:01:32 -08001048 glyph->fWidth += gFTLibrary->lcdExtra();
1049 glyph->fLeft -= gFTLibrary->lcdExtra() >> 1;
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001050 }
1051 }
1052}
1053
bungeman401ae2d2016-07-18 15:46:27 -07001054bool SkScalerContext_FreeType::shouldSubpixelBitmap(const SkGlyph& glyph, const SkMatrix& matrix) {
1055 // If subpixel rendering of a bitmap *can* be done.
1056 bool mechanism = fFace->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
1057 fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag &&
1058 (glyph.getSubXFixed() || glyph.getSubYFixed());
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001059
bungeman401ae2d2016-07-18 15:46:27 -07001060 // If subpixel rendering of a bitmap *should* be done.
1061 // 1. If the face is not scalable then always allow subpixel rendering.
1062 // Otherwise, if the font has an 8ppem strike 7 will subpixel render but 8 won't.
1063 // 2. If the matrix is already not identity the bitmap will already be resampled,
1064 // so resampling slightly differently shouldn't make much difference.
1065 bool policy = !FT_IS_SCALABLE(fFace) || !matrix.isIdentity();
1066
1067 return mechanism && policy;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001068}
1069
reed@android.com8a1c16f2008-12-17 15:59:43 +00001070void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
1071 SkAutoMutexAcquire ac(gFTMutex);
1072
1073 glyph->fRsbDelta = 0;
1074 glyph->fLsbDelta = 0;
1075
1076 FT_Error err;
1077
1078 if (this->setupSize()) {
bungeman13a007d2015-06-19 05:09:39 -07001079 glyph->zeroMetrics();
1080 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001081 }
1082
djsollen1b277042014-08-06 06:58:06 -07001083 err = FT_Load_Glyph( fFace, glyph->getGlyphID(), fLoadGlyphFlags );
reed@android.com8a1c16f2008-12-17 15:59:43 +00001084 if (err != 0) {
reed@android.com62900b42009-02-11 15:07:19 +00001085 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001086 return;
1087 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001088 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001089
1090 switch ( fFace->glyph->format ) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001091 case FT_GLYPH_FORMAT_OUTLINE:
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001092 if (0 == fFace->glyph->outline.n_contours) {
1093 glyph->fWidth = 0;
1094 glyph->fHeight = 0;
1095 glyph->fTop = 0;
1096 glyph->fLeft = 0;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001097 } else {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001098 FT_BBox bbox;
1099 getBBoxForCurrentGlyph(glyph, &bbox, true);
1100
1101 glyph->fWidth = SkToU16(SkFDot6Floor(bbox.xMax - bbox.xMin));
1102 glyph->fHeight = SkToU16(SkFDot6Floor(bbox.yMax - bbox.yMin));
1103 glyph->fTop = -SkToS16(SkFDot6Floor(bbox.yMax));
1104 glyph->fLeft = SkToS16(SkFDot6Floor(bbox.xMin));
1105
1106 updateGlyphIfLCD(glyph);
bungeman@google.com0f0c2882011-11-04 15:47:41 +00001107 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001108 break;
1109
1110 case FT_GLYPH_FORMAT_BITMAP:
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001111 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1112 FT_Vector vector;
1113 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1114 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1115 FT_Vector_Transform(&vector, &fMatrix22);
1116 fFace->glyph->bitmap_left += SkFDot6Floor(vector.x);
1117 fFace->glyph->bitmap_top += SkFDot6Floor(vector.y);
1118 }
1119
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001120 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
1121 glyph->fMaskFormat = SkMask::kARGB32_Format;
1122 }
1123
bungeman401ae2d2016-07-18 15:46:27 -07001124 {
1125 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(fFace->glyph->bitmap_left),
1126 -SkIntToScalar(fFace->glyph->bitmap_top),
1127 SkIntToScalar(fFace->glyph->bitmap.width),
1128 SkIntToScalar(fFace->glyph->bitmap.rows));
1129 fMatrix22Scalar.mapRect(&rect);
1130 if (this->shouldSubpixelBitmap(*glyph, fMatrix22Scalar)) {
1131 rect.offset(SkFixedToScalar(glyph->getSubXFixed()),
1132 SkFixedToScalar(glyph->getSubYFixed()));
1133 }
1134 SkIRect irect = rect.roundOut();
1135 glyph->fWidth = SkToU16(irect.width());
1136 glyph->fHeight = SkToU16(irect.height());
1137 glyph->fTop = SkToS16(irect.top());
1138 glyph->fLeft = SkToS16(irect.left());
1139 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001140 break;
1141
1142 default:
tomhudson@google.com0c00f212011-12-28 14:59:50 +00001143 SkDEBUGFAIL("unknown glyph format");
bungeman13a007d2015-06-19 05:09:39 -07001144 glyph->zeroMetrics();
1145 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001146 }
1147
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001148 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1149 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001150 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearVertAdvance);
bungeman401ae2d2016-07-18 15:46:27 -07001151 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getSkewX() * advanceScalar);
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001152 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getScaleY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001153 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001154 glyph->fAdvanceX = -SkFDot6ToFloat(fFace->glyph->advance.x);
1155 glyph->fAdvanceY = SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001156 }
bungeman@google.com34f10262012-03-23 18:11:47 +00001157 } else {
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001158 if (fDoLinearMetrics) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001159 const SkScalar advanceScalar = SkFT_FixedToScalar(fFace->glyph->linearHoriAdvance);
1160 glyph->fAdvanceX = SkScalarToFloat(fMatrix22Scalar.getScaleX() * advanceScalar);
bungeman401ae2d2016-07-18 15:46:27 -07001161 glyph->fAdvanceY = SkScalarToFloat(fMatrix22Scalar.getSkewY() * advanceScalar);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001162 } else {
benjaminwagner6b3eacb2016-03-24 19:07:58 -07001163 glyph->fAdvanceX = SkFDot6ToFloat(fFace->glyph->advance.x);
1164 glyph->fAdvanceY = -SkFDot6ToFloat(fFace->glyph->advance.y);
bungeman@google.com34f10262012-03-23 18:11:47 +00001165
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001166 if (fRec.fFlags & kDevKernText_Flag) {
1167 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
1168 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001169 }
1170 }
djsollen@google.comd8b599c2012-03-19 19:44:19 +00001171 }
1172
reed@android.com8a1c16f2008-12-17 15:59:43 +00001173#ifdef ENABLE_GLYPH_SPEW
djsollen1b277042014-08-06 06:58:06 -07001174 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(), fLoadGlyphFlags, glyph->fWidth));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001175#endif
1176}
1177
bungeman5ec443c2014-11-21 13:18:34 -08001178static void clear_glyph_image(const SkGlyph& glyph) {
1179 sk_bzero(glyph.fImage, glyph.rowBytes() * glyph.fHeight);
1180}
reed@google.comea2333d2011-03-14 16:44:56 +00001181
bungeman@google.coma76de722012-10-26 19:35:54 +00001182void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001183 SkAutoMutexAcquire ac(gFTMutex);
1184
reed@android.com8a1c16f2008-12-17 15:59:43 +00001185 if (this->setupSize()) {
bungeman5ec443c2014-11-21 13:18:34 -08001186 clear_glyph_image(glyph);
1187 return;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188 }
1189
bungeman5ec443c2014-11-21 13:18:34 -08001190 FT_Error err = FT_Load_Glyph(fFace, glyph.getGlyphID(), fLoadGlyphFlags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001191 if (err != 0) {
1192 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 -08001193 glyph.getGlyphID(), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
1194 clear_glyph_image(glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195 return;
1196 }
1197
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001198 emboldenIfNeeded(fFace, fFace->glyph);
bungeman401ae2d2016-07-18 15:46:27 -07001199 SkMatrix* bitmapMatrix = &fMatrix22Scalar;
1200 SkMatrix subpixelBitmapMatrix;
1201 if (this->shouldSubpixelBitmap(glyph, *bitmapMatrix)) {
1202 subpixelBitmapMatrix = fMatrix22Scalar;
1203 subpixelBitmapMatrix.postTranslate(SkFixedToScalar(glyph.getSubXFixed()),
1204 SkFixedToScalar(glyph.getSubYFixed()));
1205 bitmapMatrix = &subpixelBitmapMatrix;
1206 }
1207 generateGlyphImage(fFace, glyph, *bitmapMatrix);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001208}
1209
reed@android.com8a1c16f2008-12-17 15:59:43 +00001210
bungeman5ec443c2014-11-21 13:18:34 -08001211void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph, SkPath* path) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001212 SkAutoMutexAcquire ac(gFTMutex);
1213
caryclarka10742c2014-09-18 11:00:40 -07001214 SkASSERT(path);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001215
1216 if (this->setupSize()) {
1217 path->reset();
1218 return;
1219 }
1220
1221 uint32_t flags = fLoadGlyphFlags;
1222 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1223 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1224
djsollen1b277042014-08-06 06:58:06 -07001225 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(), flags);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001226
1227 if (err != 0) {
1228 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
djsollen1b277042014-08-06 06:58:06 -07001229 glyph.getGlyphID(), flags, err));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001230 path->reset();
1231 return;
1232 }
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001233 emboldenIfNeeded(fFace, fFace->glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001234
sugoi@google.com66a58ac2013-03-05 20:40:52 +00001235 generateGlyphPath(fFace, path);
bungeman@google.com8ff8a192012-09-25 20:38:28 +00001236
1237 // The path's origin from FreeType is always the horizontal layout origin.
1238 // Offset the path so that it is relative to the vertical origin if needed.
1239 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1240 FT_Vector vector;
1241 vector.x = fFace->glyph->metrics.vertBearingX - fFace->glyph->metrics.horiBearingX;
1242 vector.y = -fFace->glyph->metrics.vertBearingY - fFace->glyph->metrics.horiBearingY;
1243 FT_Vector_Transform(&vector, &fMatrix22);
1244 path->offset(SkFDot6ToScalar(vector.x), -SkFDot6ToScalar(vector.y));
1245 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001246}
1247
bungeman41078062014-07-07 08:16:37 -07001248void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001249 if (nullptr == metrics) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001250 return;
1251 }
1252
bungeman41078062014-07-07 08:16:37 -07001253 SkAutoMutexAcquire ac(gFTMutex);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001254
1255 if (this->setupSize()) {
bungeman41078062014-07-07 08:16:37 -07001256 sk_bzero(metrics, sizeof(*metrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001257 return;
1258 }
1259
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001260 FT_Face face = fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001261
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001262 // fetch units/EM from "head" table if needed (ie for bitmap fonts)
1263 SkScalar upem = SkIntToScalar(face->units_per_EM);
1264 if (!upem) {
1265 TT_Header* ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face, ft_sfnt_head);
1266 if (ttHeader) {
1267 upem = SkIntToScalar(ttHeader->Units_Per_EM);
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001268 }
1269 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001270
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001271 // use the os/2 table as a source of reasonable defaults.
1272 SkScalar x_height = 0.0f;
1273 SkScalar avgCharWidth = 0.0f;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001274 SkScalar cap_height = 0.0f;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001275 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1276 if (os2) {
bungeman53790512016-07-21 13:32:09 -07001277 x_height = SkIntToScalar(os2->sxHeight) / upem * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001278 avgCharWidth = SkIntToScalar(os2->xAvgCharWidth) / upem;
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001279 if (os2->version != 0xFFFF && os2->version >= 2) {
bungeman53790512016-07-21 13:32:09 -07001280 cap_height = SkIntToScalar(os2->sCapHeight) / upem * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001281 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001282 }
1283
1284 // pull from format-specific metrics as needed
1285 SkScalar ascent, descent, leading, xmin, xmax, ymin, ymax;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001286 SkScalar underlineThickness, underlinePosition;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001287 if (face->face_flags & FT_FACE_FLAG_SCALABLE) { // scalable outline font
bungeman665b0382015-03-19 10:43:57 -07001288 // FreeType will always use HHEA metrics if they're not zero.
1289 // It completely ignores the OS/2 fsSelection::UseTypoMetrics bit.
1290 // It also ignores the VDMX tables, which are also of interest here
1291 // (and override everything else when they apply).
1292 static const int kUseTypoMetricsMask = (1 << 7);
1293 if (os2 && os2->version != 0xFFFF && (os2->fsSelection & kUseTypoMetricsMask)) {
1294 ascent = -SkIntToScalar(os2->sTypoAscender) / upem;
1295 descent = -SkIntToScalar(os2->sTypoDescender) / upem;
1296 leading = SkIntToScalar(os2->sTypoLineGap) / upem;
1297 } else {
1298 ascent = -SkIntToScalar(face->ascender) / upem;
1299 descent = -SkIntToScalar(face->descender) / upem;
1300 leading = SkIntToScalar(face->height + (face->descender - face->ascender)) / upem;
1301 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001302 xmin = SkIntToScalar(face->bbox.xMin) / upem;
1303 xmax = SkIntToScalar(face->bbox.xMax) / upem;
1304 ymin = -SkIntToScalar(face->bbox.yMin) / upem;
1305 ymax = -SkIntToScalar(face->bbox.yMax) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001306 underlineThickness = SkIntToScalar(face->underline_thickness) / upem;
commit-bot@chromium.orgd3031aa2014-05-14 14:54:51 +00001307 underlinePosition = -SkIntToScalar(face->underline_position +
1308 face->underline_thickness / 2) / upem;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001309
bungeman41078062014-07-07 08:16:37 -07001310 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1311 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
1312
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001313 // we may be able to synthesize x_height and cap_height from outline
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001314 if (!x_height) {
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001315 FT_BBox bbox;
1316 if (getCBoxForLetter('x', &bbox)) {
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001317 x_height = SkIntToScalar(bbox.yMax) / 64.0f;
1318 }
1319 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001320 if (!cap_height) {
1321 FT_BBox bbox;
1322 if (getCBoxForLetter('H', &bbox)) {
1323 cap_height = SkIntToScalar(bbox.yMax) / 64.0f;
1324 }
1325 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001326 } else if (fStrikeIndex != -1) { // bitmap strike metrics
1327 SkScalar xppem = SkIntToScalar(face->size->metrics.x_ppem);
1328 SkScalar yppem = SkIntToScalar(face->size->metrics.y_ppem);
1329 ascent = -SkIntToScalar(face->size->metrics.ascender) / (yppem * 64.0f);
1330 descent = -SkIntToScalar(face->size->metrics.descender) / (yppem * 64.0f);
bungeman53790512016-07-21 13:32:09 -07001331 leading = (SkIntToScalar(face->size->metrics.height) / (yppem * 64.0f)) + ascent - descent;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001332 xmin = 0.0f;
1333 xmax = SkIntToScalar(face->available_sizes[fStrikeIndex].width) / xppem;
1334 ymin = descent + leading;
1335 ymax = ascent - descent;
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001336 underlineThickness = 0;
1337 underlinePosition = 0;
1338
bungeman41078062014-07-07 08:16:37 -07001339 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1340 metrics->fFlags &= ~SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001341 } else {
caryclarkfe7ada72016-03-21 06:55:52 -07001342 sk_bzero(metrics, sizeof(*metrics));
1343 return;
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001344 }
1345
1346 // synthesize elements that were not provided by the os/2 table or format-specific metrics
1347 if (!x_height) {
bungeman53790512016-07-21 13:32:09 -07001348 x_height = -ascent * fScale.y();
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001349 }
1350 if (!avgCharWidth) {
1351 avgCharWidth = xmax - xmin;
1352 }
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001353 if (!cap_height) {
bungeman53790512016-07-21 13:32:09 -07001354 cap_height = -ascent * fScale.y();
bungeman@google.comcbe1b542013-12-16 17:02:39 +00001355 }
bungeman@google.comc9a8a7e2013-12-10 18:09:36 +00001356
1357 // disallow negative linespacing
1358 if (leading < 0.0f) {
1359 leading = 0.0f;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001360 }
1361
bungeman53790512016-07-21 13:32:09 -07001362 metrics->fTop = ymax * fScale.y();
1363 metrics->fAscent = ascent * fScale.y();
1364 metrics->fDescent = descent * fScale.y();
1365 metrics->fBottom = ymin * fScale.y();
1366 metrics->fLeading = leading * fScale.y();
1367 metrics->fAvgCharWidth = avgCharWidth * fScale.y();
1368 metrics->fXMin = xmin * fScale.y();
1369 metrics->fXMax = xmax * fScale.y();
bungeman7316b102014-10-29 12:46:52 -07001370 metrics->fXHeight = x_height;
1371 metrics->fCapHeight = cap_height;
bungeman53790512016-07-21 13:32:09 -07001372 metrics->fUnderlineThickness = underlineThickness * fScale.y();
1373 metrics->fUnderlinePosition = underlinePosition * fScale.y();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001374}
1375
djsollenfcfea992015-01-09 08:18:13 -08001376///////////////////////////////////////////////////////////////////////////////
1377
1378// hand-tuned value to reduce outline embolden strength
1379#ifndef SK_OUTLINE_EMBOLDEN_DIVISOR
1380 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
1381 #define SK_OUTLINE_EMBOLDEN_DIVISOR 34
1382 #else
1383 #define SK_OUTLINE_EMBOLDEN_DIVISOR 24
1384 #endif
1385#endif
1386
1387///////////////////////////////////////////////////////////////////////////////
1388
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001389void SkScalerContext_FreeType::emboldenIfNeeded(FT_Face face, FT_GlyphSlot glyph)
1390{
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001391 // check to see if the embolden bit is set
1392 if (0 == (fRec.fFlags & SkScalerContext::kEmbolden_Flag)) {
1393 return;
1394 }
1395
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001396 switch (glyph->format) {
1397 case FT_GLYPH_FORMAT_OUTLINE:
1398 FT_Pos strength;
djsollenfcfea992015-01-09 08:18:13 -08001399 strength = FT_MulFix(face->units_per_EM, face->size->metrics.y_scale)
1400 / SK_OUTLINE_EMBOLDEN_DIVISOR;
commit-bot@chromium.org921d2b32014-04-01 19:03:07 +00001401 FT_Outline_Embolden(&glyph->outline, strength);
1402 break;
1403 case FT_GLYPH_FORMAT_BITMAP:
1404 FT_GlyphSlot_Own_Bitmap(glyph);
1405 FT_Bitmap_Embolden(glyph->library, &glyph->bitmap, kBitmapEmboldenStrength, 0);
1406 break;
1407 default:
1408 SkDEBUGFAIL("unknown glyph format");
commit-bot@chromium.org6fa81d72013-12-26 15:50:29 +00001409 }
1410}
1411
reed@google.comb4162b12013-07-02 16:32:29 +00001412///////////////////////////////////////////////////////////////////////////////
1413
1414#include "SkUtils.h"
1415
1416static SkUnichar next_utf8(const void** chars) {
1417 return SkUTF8_NextUnichar((const char**)chars);
1418}
1419
1420static SkUnichar next_utf16(const void** chars) {
1421 return SkUTF16_NextUnichar((const uint16_t**)chars);
1422}
1423
1424static SkUnichar next_utf32(const void** chars) {
1425 const SkUnichar** uniChars = (const SkUnichar**)chars;
1426 SkUnichar uni = **uniChars;
1427 *uniChars += 1;
1428 return uni;
1429}
1430
1431typedef SkUnichar (*EncodingProc)(const void**);
1432
1433static EncodingProc find_encoding_proc(SkTypeface::Encoding enc) {
1434 static const EncodingProc gProcs[] = {
1435 next_utf8, next_utf16, next_utf32
1436 };
1437 SkASSERT((size_t)enc < SK_ARRAY_COUNT(gProcs));
1438 return gProcs[enc];
1439}
1440
1441int SkTypeface_FreeType::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman726cf902015-06-05 13:38:12 -07001442 uint16_t glyphs[], int glyphCount) const
1443{
reed@google.comb4162b12013-07-02 16:32:29 +00001444 AutoFTAccess fta(this);
1445 FT_Face face = fta.face();
1446 if (!face) {
1447 if (glyphs) {
1448 sk_bzero(glyphs, glyphCount * sizeof(glyphs[0]));
1449 }
1450 return 0;
1451 }
1452
1453 EncodingProc next_uni_proc = find_encoding_proc(encoding);
1454
halcanary96fcdcc2015-08-27 07:41:13 -07001455 if (nullptr == glyphs) {
reed@google.comb4162b12013-07-02 16:32:29 +00001456 for (int i = 0; i < glyphCount; ++i) {
1457 if (0 == FT_Get_Char_Index(face, next_uni_proc(&chars))) {
1458 return i;
1459 }
1460 }
1461 return glyphCount;
1462 } else {
1463 int first = glyphCount;
1464 for (int i = 0; i < glyphCount; ++i) {
1465 unsigned id = FT_Get_Char_Index(face, next_uni_proc(&chars));
1466 glyphs[i] = SkToU16(id);
1467 if (0 == id && i < first) {
1468 first = i;
1469 }
1470 }
1471 return first;
1472 }
1473}
1474
1475int SkTypeface_FreeType::onCountGlyphs() const {
bungeman572f8792016-04-29 15:05:02 -07001476 AutoFTAccess fta(this);
1477 FT_Face face = fta.face();
1478 return face ? face->num_glyphs : 0;
reed@google.comb4162b12013-07-02 16:32:29 +00001479}
1480
bungeman@google.com839702b2013-08-07 17:09:22 +00001481SkTypeface::LocalizedStrings* SkTypeface_FreeType::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001482 SkTypeface::LocalizedStrings* nameIter =
1483 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001484 if (nullptr == nameIter) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001485 SkString familyName;
1486 this->getFamilyName(&familyName);
1487 SkString language("und"); //undetermined
1488 nameIter = new SkOTUtils::LocalizedStrings_SingleName(familyName, language);
1489 }
1490 return nameIter;
1491}
1492
bungeman@google.comddc218e2013-08-01 22:29:43 +00001493int SkTypeface_FreeType::onGetTableTags(SkFontTableTag tags[]) const {
1494 AutoFTAccess fta(this);
1495 FT_Face face = fta.face();
1496
1497 FT_ULong tableCount = 0;
1498 FT_Error error;
1499
halcanary96fcdcc2015-08-27 07:41:13 -07001500 // When 'tag' is nullptr, returns number of tables in 'length'.
1501 error = FT_Sfnt_Table_Info(face, 0, nullptr, &tableCount);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001502 if (error) {
1503 return 0;
1504 }
1505
1506 if (tags) {
1507 for (FT_ULong tableIndex = 0; tableIndex < tableCount; ++tableIndex) {
1508 FT_ULong tableTag;
1509 FT_ULong tablelength;
1510 error = FT_Sfnt_Table_Info(face, tableIndex, &tableTag, &tablelength);
1511 if (error) {
1512 return 0;
1513 }
1514 tags[tableIndex] = static_cast<SkFontTableTag>(tableTag);
1515 }
1516 }
1517 return tableCount;
1518}
1519
1520size_t SkTypeface_FreeType::onGetTableData(SkFontTableTag tag, size_t offset,
1521 size_t length, void* data) const
1522{
1523 AutoFTAccess fta(this);
1524 FT_Face face = fta.face();
1525
1526 FT_ULong tableLength = 0;
1527 FT_Error error;
1528
1529 // When 'length' is 0 it is overwritten with the full table length; 'offset' is ignored.
halcanary96fcdcc2015-08-27 07:41:13 -07001530 error = FT_Load_Sfnt_Table(face, tag, 0, nullptr, &tableLength);
bungeman@google.comddc218e2013-08-01 22:29:43 +00001531 if (error) {
1532 return 0;
1533 }
1534
1535 if (offset > tableLength) {
1536 return 0;
1537 }
bungeman@google.com5ecd4fa2013-08-01 22:48:21 +00001538 FT_ULong size = SkTMin((FT_ULong)length, tableLength - (FT_ULong)offset);
bsalomon49f085d2014-09-05 13:34:00 -07001539 if (data) {
bungeman@google.comddc218e2013-08-01 22:29:43 +00001540 error = FT_Load_Sfnt_Table(face, tag, offset, reinterpret_cast<FT_Byte*>(data), &size);
1541 if (error) {
1542 return 0;
1543 }
1544 }
1545
1546 return size;
1547}
1548
reed@google.comb4162b12013-07-02 16:32:29 +00001549///////////////////////////////////////////////////////////////////////////////
1550///////////////////////////////////////////////////////////////////////////////
reed@android.com8a1c16f2008-12-17 15:59:43 +00001551
halcanary96fcdcc2015-08-27 07:41:13 -07001552SkTypeface_FreeType::Scanner::Scanner() : fLibrary(nullptr) {
bungeman9dc24682014-12-01 14:01:32 -08001553 if (FT_New_Library(&gFTMemory, &fLibrary)) {
1554 return;
bungeman14df8332014-10-28 15:07:23 -07001555 }
bungeman9dc24682014-12-01 14:01:32 -08001556 FT_Add_Default_Modules(fLibrary);
bungeman14df8332014-10-28 15:07:23 -07001557}
1558SkTypeface_FreeType::Scanner::~Scanner() {
bungeman9dc24682014-12-01 14:01:32 -08001559 if (fLibrary) {
1560 FT_Done_Library(fLibrary);
1561 }
bungeman14df8332014-10-28 15:07:23 -07001562}
1563
1564FT_Face SkTypeface_FreeType::Scanner::openFace(SkStream* stream, int ttcIndex,
1565 FT_Stream ftStream) const
bungeman32501a12014-10-28 12:03:55 -07001566{
halcanary96fcdcc2015-08-27 07:41:13 -07001567 if (fLibrary == nullptr) {
1568 return nullptr;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001569 }
1570
bungeman14df8332014-10-28 15:07:23 -07001571 FT_Open_Args args;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001572 memset(&args, 0, sizeof(args));
1573
1574 const void* memoryBase = stream->getMemoryBase();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001575
bsalomon49f085d2014-09-05 13:34:00 -07001576 if (memoryBase) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001577 args.flags = FT_OPEN_MEMORY;
1578 args.memory_base = (const FT_Byte*)memoryBase;
1579 args.memory_size = stream->getLength();
1580 } else {
bungeman14df8332014-10-28 15:07:23 -07001581 memset(ftStream, 0, sizeof(*ftStream));
1582 ftStream->size = stream->getLength();
1583 ftStream->descriptor.pointer = stream;
bungeman9dc24682014-12-01 14:01:32 -08001584 ftStream->read = sk_ft_stream_io;
1585 ftStream->close = sk_ft_stream_close;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001586
1587 args.flags = FT_OPEN_STREAM;
bungeman14df8332014-10-28 15:07:23 -07001588 args.stream = ftStream;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001589 }
1590
1591 FT_Face face;
bungeman14df8332014-10-28 15:07:23 -07001592 if (FT_Open_Face(fLibrary, &args, ttcIndex, &face)) {
halcanary96fcdcc2015-08-27 07:41:13 -07001593 return nullptr;
bungeman14df8332014-10-28 15:07:23 -07001594 }
1595 return face;
1596}
1597
1598bool SkTypeface_FreeType::Scanner::recognizedFont(SkStream* stream, int* numFaces) const {
1599 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1600
1601 FT_StreamRec streamRec;
1602 FT_Face face = this->openFace(stream, -1, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001603 if (nullptr == face) {
bungeman14df8332014-10-28 15:07:23 -07001604 return false;
1605 }
1606
1607 *numFaces = face->num_faces;
1608
1609 FT_Done_Face(face);
1610 return true;
1611}
1612
1613#include "SkTSearch.h"
1614bool SkTypeface_FreeType::Scanner::scanFont(
bungeman41868fe2015-05-20 09:21:04 -07001615 SkStream* stream, int ttcIndex,
1616 SkString* name, SkFontStyle* style, bool* isFixedPitch, AxisDefinitions* axes) const
bungeman14df8332014-10-28 15:07:23 -07001617{
1618 SkAutoMutexAcquire libraryLock(fLibraryMutex);
1619
1620 FT_StreamRec streamRec;
1621 FT_Face face = this->openFace(stream, ttcIndex, &streamRec);
halcanary96fcdcc2015-08-27 07:41:13 -07001622 if (nullptr == face) {
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001623 return false;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001624 }
1625
bungemana4c4a2d2014-10-20 13:33:19 -07001626 int weight = SkFontStyle::kNormal_Weight;
1627 int width = SkFontStyle::kNormal_Width;
1628 SkFontStyle::Slant slant = SkFontStyle::kUpright_Slant;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001629 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
bungemana4c4a2d2014-10-20 13:33:19 -07001630 weight = SkFontStyle::kBold_Weight;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001631 }
1632 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
bungemana4c4a2d2014-10-20 13:33:19 -07001633 slant = SkFontStyle::kItalic_Slant;
1634 }
1635
1636 PS_FontInfoRec psFontInfo;
1637 TT_OS2* os2 = static_cast<TT_OS2*>(FT_Get_Sfnt_Table(face, ft_sfnt_os2));
1638 if (os2 && os2->version != 0xffff) {
1639 weight = os2->usWeightClass;
1640 width = os2->usWidthClass;
bungemanb4bb7d82016-04-27 10:21:04 -07001641
1642 // OS/2::fsSelection bit 9 indicates oblique.
1643 if (SkToBool(os2->fsSelection & (1u << 9))) {
1644 slant = SkFontStyle::kOblique_Slant;
1645 }
bungemana4c4a2d2014-10-20 13:33:19 -07001646 } else if (0 == FT_Get_PS_Font_Info(face, &psFontInfo) && psFontInfo.weight) {
1647 static const struct {
1648 char const * const name;
1649 int const weight;
1650 } commonWeights [] = {
1651 // There are probably more common names, but these are known to exist.
bungemand803cda2015-04-16 14:22:46 -07001652 { "all", SkFontStyle::kNormal_Weight }, // Multiple Masters usually default to normal.
bungemana4c4a2d2014-10-20 13:33:19 -07001653 { "black", SkFontStyle::kBlack_Weight },
1654 { "bold", SkFontStyle::kBold_Weight },
1655 { "book", (SkFontStyle::kNormal_Weight + SkFontStyle::kLight_Weight)/2 },
1656 { "demi", SkFontStyle::kSemiBold_Weight },
1657 { "demibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001658 { "extra", SkFontStyle::kExtraBold_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001659 { "extrabold", SkFontStyle::kExtraBold_Weight },
1660 { "extralight", SkFontStyle::kExtraLight_Weight },
bungeman14df8332014-10-28 15:07:23 -07001661 { "hairline", SkFontStyle::kThin_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001662 { "heavy", SkFontStyle::kBlack_Weight },
1663 { "light", SkFontStyle::kLight_Weight },
1664 { "medium", SkFontStyle::kMedium_Weight },
1665 { "normal", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001666 { "plain", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001667 { "regular", SkFontStyle::kNormal_Weight },
bungeman14df8332014-10-28 15:07:23 -07001668 { "roman", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001669 { "semibold", SkFontStyle::kSemiBold_Weight },
bungeman14df8332014-10-28 15:07:23 -07001670 { "standard", SkFontStyle::kNormal_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001671 { "thin", SkFontStyle::kThin_Weight },
1672 { "ultra", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001673 { "ultrablack", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001674 { "ultrabold", SkFontStyle::kExtraBold_Weight },
bungeman6e45bda2016-07-25 15:11:49 -07001675 { "ultraheavy", SkFontStyle::kExtraBlack_Weight },
bungemana4c4a2d2014-10-20 13:33:19 -07001676 { "ultralight", SkFontStyle::kExtraLight_Weight },
1677 };
1678 int const index = SkStrLCSearch(&commonWeights[0].name, SK_ARRAY_COUNT(commonWeights),
bungemand2ae7282014-10-22 08:25:44 -07001679 psFontInfo.weight, sizeof(commonWeights[0]));
bungemana4c4a2d2014-10-20 13:33:19 -07001680 if (index >= 0) {
1681 weight = commonWeights[index].weight;
1682 } else {
bungeman14df8332014-10-28 15:07:23 -07001683 SkDEBUGF(("Do not know weight for: %s (%s) \n", face->family_name, psFontInfo.weight));
bungemana4c4a2d2014-10-20 13:33:19 -07001684 }
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001685 }
1686
1687 if (name) {
1688 name->set(face->family_name);
1689 }
1690 if (style) {
bungemana4c4a2d2014-10-20 13:33:19 -07001691 *style = SkFontStyle(weight, width, slant);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001692 }
bungeman@google.comfe747652013-03-25 19:36:11 +00001693 if (isFixedPitch) {
1694 *isFixedPitch = FT_IS_FIXED_WIDTH(face);
reed@google.com5b31b0f2011-02-23 14:41:42 +00001695 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001696
bungeman41868fe2015-05-20 09:21:04 -07001697 if (axes && face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
halcanary96fcdcc2015-08-27 07:41:13 -07001698 FT_MM_Var* variations = nullptr;
bungeman41868fe2015-05-20 09:21:04 -07001699 FT_Error err = FT_Get_MM_Var(face, &variations);
1700 if (err) {
1701 SkDEBUGF(("INFO: font %s claims to have variations, but none found.\n",
1702 face->family_name));
1703 return false;
1704 }
1705 SkAutoFree autoFreeVariations(variations);
1706
1707 axes->reset(variations->num_axis);
1708 for (FT_UInt i = 0; i < variations->num_axis; ++i) {
1709 const FT_Var_Axis& ftAxis = variations->axis[i];
1710 (*axes)[i].fTag = ftAxis.tag;
1711 (*axes)[i].fMinimum = ftAxis.minimum;
1712 (*axes)[i].fDefault = ftAxis.def;
1713 (*axes)[i].fMaximum = ftAxis.maximum;
1714 }
1715 }
bungeman41868fe2015-05-20 09:21:04 -07001716
reed@android.com8a1c16f2008-12-17 15:59:43 +00001717 FT_Done_Face(face);
djsollen@google.com4dc686d2012-02-15 21:03:45 +00001718 return true;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001719}
bungemanf6c71072016-01-21 14:17:47 -08001720
1721/*static*/ void SkTypeface_FreeType::Scanner::computeAxisValues(
1722 AxisDefinitions axisDefinitions,
1723 const SkFontMgr::FontParameters::Axis* requestedAxes, int requestedAxisCount,
1724 SkFixed* axisValues,
1725 const SkString& name)
1726{
1727 for (int i = 0; i < axisDefinitions.count(); ++i) {
1728 const Scanner::AxisDefinition& axisDefinition = axisDefinitions[i];
benjaminwagner64a3c952016-02-25 12:20:40 -08001729 const SkScalar axisMin = SkFixedToScalar(axisDefinition.fMinimum);
1730 const SkScalar axisMax = SkFixedToScalar(axisDefinition.fMaximum);
bungemanf6c71072016-01-21 14:17:47 -08001731 axisValues[i] = axisDefinition.fDefault;
1732 for (int j = 0; j < requestedAxisCount; ++j) {
1733 const SkFontMgr::FontParameters::Axis& axisSpecified = requestedAxes[j];
1734 if (axisDefinition.fTag == axisSpecified.fTag) {
benjaminwagner64a3c952016-02-25 12:20:40 -08001735 const SkScalar axisValue = SkTPin(axisSpecified.fStyleValue, axisMin, axisMax);
1736 if (axisSpecified.fStyleValue != axisValue) {
bungemanf6c71072016-01-21 14:17:47 -08001737 SkDEBUGF(("Requested font axis value out of range: "
1738 "%s '%c%c%c%c' %f; pinned to %f.\n",
1739 name.c_str(),
1740 (axisDefinition.fTag >> 24) & 0xFF,
1741 (axisDefinition.fTag >> 16) & 0xFF,
1742 (axisDefinition.fTag >> 8) & 0xFF,
1743 (axisDefinition.fTag ) & 0xFF,
1744 SkScalarToDouble(axisSpecified.fStyleValue),
benjaminwagner64a3c952016-02-25 12:20:40 -08001745 SkScalarToDouble(axisValue)));
bungemanf6c71072016-01-21 14:17:47 -08001746 }
benjaminwagner64a3c952016-02-25 12:20:40 -08001747 axisValues[i] = SkScalarToFixed(axisValue);
bungemanf6c71072016-01-21 14:17:47 -08001748 break;
1749 }
1750 }
1751 // TODO: warn on defaulted axis?
1752 }
1753
1754 SkDEBUGCODE(
1755 // Check for axis specified, but not matched in font.
1756 for (int i = 0; i < requestedAxisCount; ++i) {
1757 SkFourByteTag skTag = requestedAxes[i].fTag;
1758 bool found = false;
1759 for (int j = 0; j < axisDefinitions.count(); ++j) {
1760 if (skTag == axisDefinitions[j].fTag) {
1761 found = true;
1762 break;
1763 }
1764 }
1765 if (!found) {
1766 SkDEBUGF(("Requested font axis not found: %s '%c%c%c%c'\n",
1767 name.c_str(),
1768 (skTag >> 24) & 0xFF,
1769 (skTag >> 16) & 0xFF,
1770 (skTag >> 8) & 0xFF,
1771 (skTag) & 0xFF));
1772 }
1773 }
1774 )
1775}