blob: 5ed66c883a2071b6699a0332a1324ada4122ac0c [file] [log] [blame]
reed@android.com8a1c16f2008-12-17 15:59:43 +00001/* libs/graphics/ports/SkFontHost_FreeType.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
reed@android.com8a1c16f2008-12-17 15:59:43 +000018#include "SkBitmap.h"
19#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000020#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000021#include "SkDescriptor.h"
22#include "SkFDot6.h"
23#include "SkFontHost.h"
24#include "SkMask.h"
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +000025#include "SkAdvancedTypefaceMetrics.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000026#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027#include "SkStream.h"
28#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000029#include "SkTemplates.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000030#include "SkThread.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000031
32#include <ft2build.h>
33#include FT_FREETYPE_H
34#include FT_OUTLINE_H
35#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000036#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000037#include FT_TYPE1_TABLES_H
agl@chromium.orge76073b2010-06-04 20:31:17 +000038#include FT_BITMAP_H
agl@chromium.org36bb6972010-06-04 20:57:16 +000039// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
40#include FT_SYNTHESIS_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000041#include FT_XFREE86_H
agl@chromium.org309485b2009-07-21 17:41:32 +000042#include FT_LCD_FILTER_H
agl@chromium.org309485b2009-07-21 17:41:32 +000043
reed@android.com8a1c16f2008-12-17 15:59:43 +000044#ifdef FT_ADVANCES_H
45#include FT_ADVANCES_H
46#endif
47
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000048#if 0
49// Also include the files by name for build tools which require this.
50#include <freetype/freetype.h>
51#include <freetype/ftoutln.h>
52#include <freetype/ftsizes.h>
53#include <freetype/tttables.h>
54#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000055#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000056#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000057#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000058#endif
59
reed@android.com8a1c16f2008-12-17 15:59:43 +000060//#define ENABLE_GLYPH_SPEW // for tracing calls
61//#define DUMP_STRIKE_CREATION
62
63#ifdef SK_DEBUG
64 #define SkASSERT_CONTINUE(pred) \
65 do { \
66 if (!(pred)) \
67 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
68 } while (false)
69#else
70 #define SkASSERT_CONTINUE(pred)
71#endif
72
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000073using namespace skia_advanced_typeface_metrics_utils;
74
reed@android.com8a1c16f2008-12-17 15:59:43 +000075//////////////////////////////////////////////////////////////////////////
76
77struct SkFaceRec;
78
79static SkMutex gFTMutex;
80static int gFTCount;
81static FT_Library gFTLibrary;
82static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000083static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
84static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000085
86/////////////////////////////////////////////////////////////////////////
87
agl@chromium.orge76073b2010-06-04 20:31:17 +000088// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
89// This value was chosen by eyeballing the result in Firefox and trying to match it.
90static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
91
agl@chromium.org309485b2009-07-21 17:41:32 +000092static bool
93InitFreetype() {
94 FT_Error err = FT_Init_FreeType(&gFTLibrary);
reed@google.comea2333d2011-03-14 16:44:56 +000095 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +000096 return false;
reed@google.comea2333d2011-03-14 16:44:56 +000097 }
agl@chromium.org309485b2009-07-21 17:41:32 +000098
agl@chromium.org309485b2009-07-21 17:41:32 +000099 // Setup LCD filtering. This reduces colour fringes for LCD rendered
100 // glyphs.
101 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000102 gLCDSupport = err == 0;
reed@android.com61608aa2009-07-31 14:52:54 +0000103 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000104
105 return true;
106}
107
reed@android.com8a1c16f2008-12-17 15:59:43 +0000108class SkScalerContext_FreeType : public SkScalerContext {
109public:
110 SkScalerContext_FreeType(const SkDescriptor* desc);
111 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000112
reed@android.com62900b42009-02-11 15:07:19 +0000113 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000114 return fFaceRec != NULL &&
115 fFTSize != NULL &&
116 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000117 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000118
119protected:
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000120 virtual unsigned generateGlyphCount();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000121 virtual uint16_t generateCharToGlyph(SkUnichar uni);
122 virtual void generateAdvance(SkGlyph* glyph);
123 virtual void generateMetrics(SkGlyph* glyph);
124 virtual void generateImage(const SkGlyph& glyph);
125 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
126 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
127 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000128 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000129
130private:
131 SkFaceRec* fFaceRec;
132 FT_Face fFace; // reference to shared face in gFaceRecHead
133 FT_Size fFTSize; // our own copy
134 SkFixed fScaleX, fScaleY;
135 FT_Matrix fMatrix22;
136 uint32_t fLoadGlyphFlags;
137
138 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000139 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000140};
141
142///////////////////////////////////////////////////////////////////////////
143///////////////////////////////////////////////////////////////////////////
144
145#include "SkStream.h"
146
147struct SkFaceRec {
148 SkFaceRec* fNext;
149 FT_Face fFace;
150 FT_StreamRec fFTStream;
151 SkStream* fSkStream;
152 uint32_t fRefCnt;
153 uint32_t fFontID;
154
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000155 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000156 SkFaceRec(SkStream* strm, uint32_t fontID);
157 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000158 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000159 }
160};
161
162extern "C" {
163 static unsigned long sk_stream_read(FT_Stream stream,
164 unsigned long offset,
165 unsigned char* buffer,
166 unsigned long count ) {
167 SkStream* str = (SkStream*)stream->descriptor.pointer;
168
169 if (count) {
170 if (!str->rewind()) {
171 return 0;
172 } else {
173 unsigned long ret;
174 if (offset) {
175 ret = str->read(NULL, offset);
176 if (ret != offset) {
177 return 0;
178 }
179 }
180 ret = str->read(buffer, count);
181 if (ret != count) {
182 return 0;
183 }
184 count = ret;
185 }
186 }
187 return count;
188 }
189
190 static void sk_stream_close( FT_Stream stream) {}
191}
192
193SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
194 : fSkStream(strm), fFontID(fontID) {
195// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
196
reed@android.com4516f472009-06-29 16:25:36 +0000197 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000198 fFTStream.size = fSkStream->getLength();
199 fFTStream.descriptor.pointer = fSkStream;
200 fFTStream.read = sk_stream_read;
201 fFTStream.close = sk_stream_close;
202}
203
reed@android.com62900b42009-02-11 15:07:19 +0000204// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000205static SkFaceRec* ref_ft_face(uint32_t fontID) {
206 SkFaceRec* rec = gFaceRecHead;
207 while (rec) {
208 if (rec->fFontID == fontID) {
209 SkASSERT(rec->fFace);
210 rec->fRefCnt += 1;
211 return rec;
212 }
213 rec = rec->fNext;
214 }
215
216 SkStream* strm = SkFontHost::OpenStream(fontID);
217 if (NULL == strm) {
218 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000219 return 0;
220 }
221
222 // this passes ownership of strm to the rec
223 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
224
225 FT_Open_Args args;
226 memset(&args, 0, sizeof(args));
227 const void* memoryBase = strm->getMemoryBase();
228
229 if (NULL != memoryBase) {
230//printf("mmap(%s)\n", keyString.c_str());
231 args.flags = FT_OPEN_MEMORY;
232 args.memory_base = (const FT_Byte*)memoryBase;
233 args.memory_size = strm->getLength();
234 } else {
235//printf("fopen(%s)\n", keyString.c_str());
236 args.flags = FT_OPEN_STREAM;
237 args.stream = &rec->fFTStream;
238 }
239
agl@chromium.org61a678a2010-08-06 18:08:18 +0000240 int face_index;
241 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
242 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
243 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000244
245 if (err) { // bad filename, try the default font
246 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
247 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000248 return 0;
249 } else {
250 SkASSERT(rec->fFace);
251 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
252 rec->fNext = gFaceRecHead;
253 gFaceRecHead = rec;
254 rec->fRefCnt = 1;
255 return rec;
256 }
257}
258
259static void unref_ft_face(FT_Face face) {
260 SkFaceRec* rec = gFaceRecHead;
261 SkFaceRec* prev = NULL;
262 while (rec) {
263 SkFaceRec* next = rec->fNext;
264 if (rec->fFace == face) {
265 if (--rec->fRefCnt == 0) {
266 if (prev) {
267 prev->fNext = next;
268 } else {
269 gFaceRecHead = next;
270 }
271 FT_Done_Face(face);
272 SkDELETE(rec);
273 }
274 return;
275 }
276 prev = rec;
277 rec = next;
278 }
279 SkASSERT("shouldn't get here, face not in list");
280}
281
282///////////////////////////////////////////////////////////////////////////
283
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000284// Work around for old versions of freetype.
285static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
286 FT_Int32 loadFlags, FT_Fixed* advances) {
287#ifdef FT_ADVANCES_H
288 return FT_Get_Advances(face, start, count, loadFlags, advances);
289#else
290 if (!face || start >= face->num_glyphs ||
291 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
292 return 6; // "Invalid argument."
293 }
294 if (count == 0)
295 return 0;
296
297 for (int i = 0; i < count; i++) {
298 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
299 if (err)
300 return err;
301 advances[i] = face->glyph->advance.x;
302 }
303
304 return 0;
305#endif
306}
307
308static bool canEmbed(FT_Face face) {
309#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
310 FT_UShort fsType = FT_Get_FSType_Flags(face);
311 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
312 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
313#else
314 // No embedding is 0x2 and bitmap embedding only is 0x200.
315 TT_OS2* os2_table;
316 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
317 return (os2_table->fsType & 0x202) == 0;
318 }
319 return false; // We tried, fail safe.
320#endif
321}
322
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000323static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
324 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
325 if (!glyph_id)
326 return false;
327 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
328 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
329 return true;
330}
331
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000332static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000333 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000334 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
335 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000336 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000337 SkASSERT(data);
338 *data = advance;
339 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000340}
341
342// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000343SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000344 uint32_t fontID,
345 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo) {
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000346#if defined(SK_BUILD_FOR_MAC) || defined(ANDROID)
reed@google.com8a5d6922011-03-14 15:08:03 +0000347 return NULL;
348#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000349 SkAutoMutexAcquire ac(gFTMutex);
350 FT_Library libInit = NULL;
351 if (gFTCount == 0) {
352 if (!InitFreetype())
353 sk_throw();
354 libInit = gFTLibrary;
355 }
356 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
357 SkFaceRec* rec = ref_ft_face(fontID);
358 if (NULL == rec)
359 return NULL;
360 FT_Face face = rec->fFace;
361
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000362 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
363 info->fFontName.set(FT_Get_Postscript_Name(face));
364 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
365 info->fLastGlyphID = face->num_glyphs - 1;
366 info->fEmSize = 1000;
367
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000368 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000369 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000370 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000371 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000372 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000373 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000374 cid = true;
375 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000376 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000377 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000378 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000379 cid = true;
380 TT_Header* ttHeader;
381 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
382 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000383 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000384 }
385 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000386
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000387 info->fStyle = 0;
388 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000389 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000390 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000391 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000392 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
393 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000394 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
395
396 PS_FontInfoRec ps_info;
397 TT_Postscript* tt_info;
398 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
399 info->fItalicAngle = ps_info.italic_angle;
400 } else if ((tt_info =
401 (TT_Postscript*)FT_Get_Sfnt_Table(face,
402 ft_sfnt_post)) != NULL) {
403 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
404 } else {
405 info->fItalicAngle = 0;
406 }
407
408 info->fAscent = face->ascender;
409 info->fDescent = face->descender;
410
411 // Figure out a good guess for StemV - Min width of i, I, !, 1.
412 // This probably isn't very good with an italic font.
413 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000414 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000415 char stem_chars[] = {'i', 'I', '!', '1'};
416 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
417 FT_BBox bbox;
418 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
419 int16_t width = bbox.xMax - bbox.xMin;
420 if (width > 0 && width < min_width) {
421 min_width = width;
422 info->fStemV = min_width;
423 }
424 }
425 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000426
427 TT_PCLT* pclt_info;
428 TT_OS2* os2_table;
429 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
430 info->fCapHeight = pclt_info->CapHeight;
431 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
432 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000433 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000434 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000435 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000436 } else if ((os2_table =
437 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
438 info->fCapHeight = os2_table->sCapHeight;
439 } else {
440 // Figure out a good guess for CapHeight: average the height of M and X.
441 FT_BBox m_bbox, x_bbox;
442 bool got_m, got_x;
443 got_m = GetLetterCBox(face, 'M', &m_bbox);
444 got_x = GetLetterCBox(face, 'X', &x_bbox);
445 if (got_m && got_x) {
446 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
447 x_bbox.yMin) / 2;
448 } else if (got_m && !got_x) {
449 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
450 } else if (!got_m && got_x) {
451 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
452 }
453 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000455 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
456 face->bbox.xMax, face->bbox.yMin);
457
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000458 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
459 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
460 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
461 }
462
463 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000464 if (FT_IS_FIXED_WIDTH(face)) {
465 appendRange(&info->fGlyphWidths, 0);
466 int16_t advance = face->max_advance_width;
467 info->fGlyphWidths->fAdvance.append(1, &advance);
468 finishRange(info->fGlyphWidths.get(), 0,
469 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000470 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000471 appendRange(&info->fGlyphWidths, 0);
472 // So as to not blow out the stack, get advances in batches.
473 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
474 FT_Fixed advances[128];
475 int advanceCount = 128;
476 if (gID + advanceCount > face->num_glyphs)
477 advanceCount = face->num_glyphs - gID + 1;
478 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
479 advances);
480 for (int i = 0; i < advanceCount; i++) {
481 int16_t advance = advances[gID + i];
482 info->fGlyphWidths->fAdvance.append(1, &advance);
483 }
484 }
485 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
486 SkAdvancedTypefaceMetrics::WidthRange::kRange);
487 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000488 info->fGlyphWidths.reset(
489 getAdvanceData(face, face->num_glyphs, &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000490 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000491 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000492
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000493 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
494 FT_HAS_VERTICAL(face)) {
495 SkASSERT(false); // Not implemented yet.
496 }
497
498 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
499 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
500 // Postscript fonts may contain more than 255 glyphs, so we end up
501 // using multiple font descriptions with a glyph ordering. Record
502 // the name of each glyph.
503 info->fGlyphNames.reset(
504 new SkAutoTArray<SkString>(face->num_glyphs));
505 for (int gID = 0; gID < face->num_glyphs; gID++) {
506 char glyphName[128]; // PS limit for names is 127 bytes.
507 FT_Get_Glyph_Name(face, gID, glyphName, 128);
508 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000509 }
510 }
511
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000512 if (!canEmbed(face))
513 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
514
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000515 unref_ft_face(face);
516 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000517#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000518}
reed@google.com618ef5e2011-01-26 22:10:41 +0000519///////////////////////////////////////////////////////////////////////////
520
521void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
522 if (!gLCDSupportValid) {
523 InitFreetype();
524 FT_Done_FreeType(gFTLibrary);
525 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000526
reed@google.com8abde0a2011-03-14 17:45:33 +0000527 if (!gLCDSupport && (rec->isLCD() || SkMask::kLCD16_Format == rec->fMaskFormat)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000528 // If the runtime Freetype library doesn't support LCD mode, we disable
529 // it here.
530 rec->fMaskFormat = SkMask::kA8_Format;
531 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000532
reed@google.com618ef5e2011-01-26 22:10:41 +0000533 SkPaint::Hinting h = rec->getHinting();
534 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
535 // collapse full->normal hinting if we're not doing LCD
536 h = SkPaint::kNormal_Hinting;
537 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
538 SkPaint::kNo_Hinting != h) {
539 // to do subpixel, we must have at most slight hinting
540 h = SkPaint::kSlight_Hinting;
541 }
542 rec->setHinting(h);
543}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000544
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000545#ifdef ANDROID
546uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
547 SkAutoMutexAcquire ac(gFTMutex);
548 SkFaceRec *rec = ref_ft_face(fontID);
549 uint16_t unitsPerEm = 0;
550
551 if (rec != NULL && rec->fFace != NULL) {
552 unitsPerEm = rec->fFace->units_per_EM;
553 unref_ft_face(rec->fFace);
554 }
555
556 return (uint32_t)unitsPerEm;
557}
558#endif
559
reed@android.com8a1c16f2008-12-17 15:59:43 +0000560SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000561 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000562 SkAutoMutexAcquire ac(gFTMutex);
563
reed@android.com8a1c16f2008-12-17 15:59:43 +0000564 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000565 if (!InitFreetype()) {
566 sk_throw();
567 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000568 }
569 ++gFTCount;
570
571 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000572 fFTSize = NULL;
573 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000574 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000575 if (NULL == fFaceRec) {
576 return;
577 }
578 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000579
580 // compute our factors from the record
581
582 SkMatrix m;
583
584 fRec.getSingleMatrix(&m);
585
586#ifdef DUMP_STRIKE_CREATION
587 SkString keyString;
588 SkFontHost::GetDescriptorKeyString(desc, &keyString);
589 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
590 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
591 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
592 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000593 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000594#endif
595
596 // now compute our scale factors
597 SkScalar sx = m.getScaleX();
598 SkScalar sy = m.getScaleY();
599
600 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
601 // sort of give up on hinting
602 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
603 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
604 sx = sy = SkScalarAve(sx, sy);
605
606 SkScalar inv = SkScalarInvert(sx);
607
608 // flip the skew elements to go from our Y-down system to FreeType's
609 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
610 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
611 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
612 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
613 } else {
614 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
615 fMatrix22.xy = fMatrix22.yx = 0;
616 }
617
618 fScaleX = SkScalarToFixed(sx);
619 fScaleY = SkScalarToFixed(sy);
620
621 // compute the flags we send to Load_Glyph
622 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000623 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000624
agl@chromium.org70a303f2010-05-10 14:15:50 +0000625 if (SkMask::kBW_Format == fRec.fMaskFormat) {
626 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
627 loadFlags = FT_LOAD_TARGET_MONO;
628 if (fRec.getHinting() == SkPaint::kNo_Hinting)
629 loadFlags = FT_LOAD_NO_HINTING;
630 } else {
631 switch (fRec.getHinting()) {
632 case SkPaint::kNo_Hinting:
633 loadFlags = FT_LOAD_NO_HINTING;
634 break;
635 case SkPaint::kSlight_Hinting:
636 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
637 break;
638 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000639 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
640 loadFlags = FT_LOAD_FORCE_AUTOHINT;
641 else
642 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000643 break;
644 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000645 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
646 loadFlags = FT_LOAD_FORCE_AUTOHINT;
647 break;
648 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000649 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comea2333d2011-03-14 16:44:56 +0000650 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat ||
651 SkMask::kLCD16_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000652 loadFlags = FT_LOAD_TARGET_LCD;
reed@google.comea2333d2011-03-14 16:44:56 +0000653 } else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000654 loadFlags = FT_LOAD_TARGET_LCD_V;
reed@google.comea2333d2011-03-14 16:44:56 +0000655 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000656 break;
657 default:
658 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
659 break;
660 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000661 }
662
agl@chromium.org99e1b902010-01-05 01:19:44 +0000663 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000664 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000665
reed@google.com96a9f7912011-05-06 11:49:30 +0000666 // Always using FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH to get correct
667 // advances, as fontconfig and cairo do.
668 // See http://code.google.com/p/skia/issues/detail?id=222.
669 loadFlags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
670
reed@android.come4d0bc02009-07-24 19:53:20 +0000671 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000672 }
673
674 // now create the FT_Size
675
676 {
677 FT_Error err;
678
679 err = FT_New_Size(fFace, &fFTSize);
680 if (err != 0) {
681 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
682 fFaceRec->fFontID, fScaleX, fScaleY, err));
683 fFace = NULL;
684 return;
685 }
686
687 err = FT_Activate_Size(fFTSize);
688 if (err != 0) {
689 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
690 fFaceRec->fFontID, fScaleX, fScaleY, err));
691 fFTSize = NULL;
692 }
693
694 err = FT_Set_Char_Size( fFace,
695 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
696 72, 72);
697 if (err != 0) {
698 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
699 fFaceRec->fFontID, fScaleX, fScaleY, err));
700 fFace = NULL;
701 return;
702 }
703
704 FT_Set_Transform( fFace, &fMatrix22, NULL);
705 }
706}
707
708SkScalerContext_FreeType::~SkScalerContext_FreeType() {
709 if (fFTSize != NULL) {
710 FT_Done_Size(fFTSize);
711 }
712
713 SkAutoMutexAcquire ac(gFTMutex);
714
715 if (fFace != NULL) {
716 unref_ft_face(fFace);
717 }
718 if (--gFTCount == 0) {
719// SkDEBUGF(("FT_Done_FreeType\n"));
720 FT_Done_FreeType(gFTLibrary);
721 SkDEBUGCODE(gFTLibrary = NULL;)
722 }
723}
724
725/* We call this before each use of the fFace, since we may be sharing
726 this face with other context (at different sizes).
727*/
728FT_Error SkScalerContext_FreeType::setupSize() {
729 /* In the off-chance that a font has been removed, we want to error out
730 right away, so call resolve just to be sure.
731
732 TODO: perhaps we can skip this, by walking the global font cache and
733 killing all of the contexts when we know that a given fontID is going
734 away...
735 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000736 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000737 return (FT_Error)-1;
738 }
739
740 FT_Error err = FT_Activate_Size(fFTSize);
741
742 if (err != 0) {
743 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
744 fFaceRec->fFontID, fScaleX, fScaleY, err));
745 fFTSize = NULL;
746 } else {
747 // seems we need to reset this every time (not sure why, but without it
748 // I get random italics from some other fFTSize)
749 FT_Set_Transform( fFace, &fMatrix22, NULL);
750 }
751 return err;
752}
753
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000754void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
755 FT_Pos strength;
756 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
757 / 24;
758 FT_Outline_Embolden(outline, strength);
759}
760
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000761unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000762 return fFace->num_glyphs;
763}
764
765uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
766 return SkToU16(FT_Get_Char_Index( fFace, uni ));
767}
768
reed@android.com9d3a9852010-01-08 14:07:42 +0000769SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
770 // iterate through each cmap entry, looking for matching glyph indices
771 FT_UInt glyphIndex;
772 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
773
774 while (glyphIndex != 0) {
775 if (glyphIndex == glyph) {
776 return charCode;
777 }
778 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
779 }
780
781 return 0;
782}
783
reed@android.com8a1c16f2008-12-17 15:59:43 +0000784static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
785 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000786 case SkMask::kHorizontalLCD_Format:
787 case SkMask::kVerticalLCD_Format:
788 SkASSERT(!"An LCD format should never be passed here");
789 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790 case SkMask::kBW_Format:
791 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000792 case SkMask::kA8_Format:
793 default:
794 return FT_PIXEL_MODE_GRAY;
795 }
796}
797
reed@android.com8a1c16f2008-12-17 15:59:43 +0000798void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
799#ifdef FT_ADVANCES_H
800 /* unhinted and light hinted text have linearly scaled advances
801 * which are very cheap to compute with some font formats...
802 */
803 {
804 SkAutoMutexAcquire ac(gFTMutex);
805
806 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000807 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000808 return;
809 }
810
811 FT_Error error;
812 FT_Fixed advance;
813
814 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
815 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
816 &advance );
817 if (0 == error) {
818 glyph->fRsbDelta = 0;
819 glyph->fLsbDelta = 0;
820 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
821 glyph->fAdvanceY = 0;
822 return;
823 }
824 }
825#endif /* FT_ADVANCES_H */
826 /* otherwise, we need to load/hint the glyph, which is slower */
827 this->generateMetrics(glyph);
828 return;
829}
830
831void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
832 SkAutoMutexAcquire ac(gFTMutex);
833
834 glyph->fRsbDelta = 0;
835 glyph->fLsbDelta = 0;
836
837 FT_Error err;
838
839 if (this->setupSize()) {
840 goto ERROR;
841 }
842
843 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
844 if (err != 0) {
845 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
846 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
847 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000848 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000849 return;
850 }
851
852 switch ( fFace->glyph->format ) {
853 case FT_GLYPH_FORMAT_OUTLINE:
854 FT_BBox bbox;
855
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000856 if (fRec.fFlags & kEmbolden_Flag) {
857 emboldenOutline(&fFace->glyph->outline);
858 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000859 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
860
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000861 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000862 int dx = glyph->getSubXFixed() >> 10;
863 int dy = glyph->getSubYFixed() >> 10;
864 // negate dy since freetype-y-goes-up and skia-y-goes-down
865 bbox.xMin += dx;
866 bbox.yMin -= dy;
867 bbox.xMax += dx;
868 bbox.yMax -= dy;
869 }
870
871 bbox.xMin &= ~63;
872 bbox.yMin &= ~63;
873 bbox.xMax = (bbox.xMax + 63) & ~63;
874 bbox.yMax = (bbox.yMax + 63) & ~63;
875
876 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
877 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
878 glyph->fTop = -SkToS16(bbox.yMax >> 6);
879 glyph->fLeft = SkToS16(bbox.xMin >> 6);
880 break;
881
882 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000883 if (fRec.fFlags & kEmbolden_Flag) {
884 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
885 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
886 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000887 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
888 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
889 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
890 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
891 break;
892
893 default:
894 SkASSERT(!"unknown glyph format");
895 goto ERROR;
896 }
897
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000898 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000899 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
900 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
901 if (fRec.fFlags & kDevKernText_Flag) {
902 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
903 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
904 }
905 } else {
906 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
907 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
908 }
909
910#ifdef ENABLE_GLYPH_SPEW
911 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
912 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
913#endif
914}
915
reed@android.comf5493692009-07-22 19:21:01 +0000916#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000917namespace skia_freetype_support {
918// extern functions from SkFontHost_FreeType_Subpixel
919extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
920extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
921}
922
923using namespace skia_freetype_support;
924#endif
925
reed@google.comea2333d2011-03-14 16:44:56 +0000926static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap) {
reed@google.com260db922011-03-14 18:09:32 +0000927 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
reed@google.comea2333d2011-03-14 16:44:56 +0000928 SkASSERT(glyph.fHeight == bitmap.rows);
929
reed@google.com260db922011-03-14 18:09:32 +0000930 const uint8_t* src = bitmap.buffer + 3;
reed@google.comea2333d2011-03-14 16:44:56 +0000931 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
932 size_t dstRB = glyph.rowBytes();
933 int width = glyph.fWidth;
934
935 for (int y = 0; y < glyph.fHeight; y++) {
936 const uint8_t* triple = src;
937 for (int x = 0; x < width; x++) {
938 dst[x] = SkPackRGB16(triple[0] >> 3, triple[1] >> 2, triple[2] >> 3);
939 triple += 3;
940 }
941 src += bitmap.pitch;
942 dst = (uint16_t*)((char*)dst + dstRB);
943 }
944}
945
reed@android.com8a1c16f2008-12-17 15:59:43 +0000946void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
947 SkAutoMutexAcquire ac(gFTMutex);
948
949 FT_Error err;
950
951 if (this->setupSize()) {
952 goto ERROR;
953 }
954
955 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
956 if (err != 0) {
957 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
958 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
959 ERROR:
960 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
961 return;
962 }
963
agl@chromium.org309485b2009-07-21 17:41:32 +0000964 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
965 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
966
reed@android.com8a1c16f2008-12-17 15:59:43 +0000967 switch ( fFace->glyph->format ) {
968 case FT_GLYPH_FORMAT_OUTLINE: {
969 FT_Outline* outline = &fFace->glyph->outline;
970 FT_BBox bbox;
971 FT_Bitmap target;
972
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000973 if (fRec.fFlags & kEmbolden_Flag) {
974 emboldenOutline(outline);
975 }
976
reed@android.com8a1c16f2008-12-17 15:59:43 +0000977 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000978 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000979 dx = glyph.getSubXFixed() >> 10;
980 dy = glyph.getSubYFixed() >> 10;
981 // negate dy since freetype-y-goes-up and skia-y-goes-down
982 dy = -dy;
983 }
984 FT_Outline_Get_CBox(outline, &bbox);
985 /*
986 what we really want to do for subpixel is
987 offset(dx, dy)
988 compute_bounds
989 offset(bbox & !63)
990 but that is two calls to offset, so we do the following, which
991 achieves the same thing with only one offset call.
992 */
993 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
994 dy - ((bbox.yMin + dy) & ~63));
995
reed@android.comf5493692009-07-22 19:21:01 +0000996#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000997 if (lcdRenderMode) {
998 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
999 // we have to call FT_Render_Glyph and memcpy the image out.
1000 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
1001 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
1002 FT_Render_Glyph(fFace->glyph, mode);
1003
1004 if (isVertical)
1005 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
1006 else
1007 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
1008
1009 break;
1010 }
1011#endif
1012
reed@google.comea2333d2011-03-14 16:44:56 +00001013 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1014 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
1015 copyFT2LCD16(glyph, fFace->glyph->bitmap);
1016 } else {
1017 target.width = glyph.fWidth;
1018 target.rows = glyph.fHeight;
1019 target.pitch = glyph.rowBytes();
1020 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1021 target.pixel_mode = compute_pixel_mode(
1022 (SkMask::Format)fRec.fMaskFormat);
1023 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001024
reed@google.comea2333d2011-03-14 16:44:56 +00001025 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1026 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1027 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001028 } break;
1029
1030 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001031 if (fRec.fFlags & kEmbolden_Flag) {
1032 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1033 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1034 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1036 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1037 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1038 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1039
1040 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1041 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001042
agl@chromium.org558434a2009-08-11 17:22:38 +00001043 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1044 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1045 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001046 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1047 unsigned dstRowBytes = glyph.rowBytes();
1048 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1049 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1050
1051 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1052 memcpy(dst, src, minRowBytes);
1053 memset(dst + minRowBytes, 0, extraRowBytes);
1054 src += srcRowBytes;
1055 dst += dstRowBytes;
1056 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001057 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001058 (glyph.fMaskFormat == SkMask::kA8_Format ||
1059 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1060 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001061 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1062 uint8_t byte = 0;
1063 int bits = 0;
1064 const uint8_t* src_row = src;
1065 uint8_t* dst_row = dst;
1066
1067 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1068 if (!bits) {
1069 byte = *src_row++;
1070 bits = 8;
1071 }
1072
1073 *dst_row++ = byte & 0x80 ? 0xff : 0;
1074 bits--;
1075 byte <<= 1;
1076 }
1077
1078 src += fFace->glyph->bitmap.pitch;
1079 dst += glyph.rowBytes();
1080 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001081 } else {
1082 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001083 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001084
1085 if (lcdRenderMode)
1086 glyph.expandA8ToLCD();
1087
reed@android.com8a1c16f2008-12-17 15:59:43 +00001088 } break;
1089
1090 default:
1091 SkASSERT(!"unknown glyph format");
1092 goto ERROR;
1093 }
1094}
1095
1096///////////////////////////////////////////////////////////////////////////////
1097
1098#define ft2sk(x) SkFixedToScalar((x) << 10)
1099
reed@android.com6f252972009-01-14 16:46:16 +00001100#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001101 #define CONST_PARAM const
1102#else // older freetype doesn't use const here
1103 #define CONST_PARAM
1104#endif
1105
1106static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1107 SkPath* path = (SkPath*)ctx;
1108 path->close(); // to close the previous contour (if any)
1109 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1110 return 0;
1111}
1112
1113static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1114 SkPath* path = (SkPath*)ctx;
1115 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1116 return 0;
1117}
1118
1119static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1120 void* ctx) {
1121 SkPath* path = (SkPath*)ctx;
1122 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1123 return 0;
1124}
1125
1126static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1127 CONST_PARAM FT_Vector* pt2, void* ctx) {
1128 SkPath* path = (SkPath*)ctx;
1129 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1130 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1131 return 0;
1132}
1133
1134void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1135 SkPath* path) {
1136 SkAutoMutexAcquire ac(gFTMutex);
1137
1138 SkASSERT(&glyph && path);
1139
1140 if (this->setupSize()) {
1141 path->reset();
1142 return;
1143 }
1144
1145 uint32_t flags = fLoadGlyphFlags;
1146 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1147 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1148
1149 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1150
1151 if (err != 0) {
1152 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1153 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1154 path->reset();
1155 return;
1156 }
1157
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001158 if (fRec.fFlags & kEmbolden_Flag) {
1159 emboldenOutline(&fFace->glyph->outline);
1160 }
1161
reed@android.com8a1c16f2008-12-17 15:59:43 +00001162 FT_Outline_Funcs funcs;
1163
1164 funcs.move_to = move_proc;
1165 funcs.line_to = line_proc;
1166 funcs.conic_to = quad_proc;
1167 funcs.cubic_to = cubic_proc;
1168 funcs.shift = 0;
1169 funcs.delta = 0;
1170
1171 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1172
1173 if (err != 0) {
1174 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1175 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1176 path->reset();
1177 return;
1178 }
1179
1180 path->close();
1181}
1182
1183void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1184 SkPaint::FontMetrics* my) {
1185 if (NULL == mx && NULL == my) {
1186 return;
1187 }
1188
1189 SkAutoMutexAcquire ac(gFTMutex);
1190
1191 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001192 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001194 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195 }
1196 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001197 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001198 }
1199 return;
1200 }
1201
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001202 FT_Face face = fFace;
1203 int upem = face->units_per_EM;
1204 if (upem <= 0) {
1205 goto ERROR;
1206 }
1207
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001208 SkPoint pts[6];
1209 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001210 SkFixed scaleY = fScaleY;
1211 SkFixed mxy = fMatrix22.xy;
1212 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001213 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1214 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001215
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001216 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001217 if (leading < 0) {
1218 leading = 0;
1219 }
1220
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001221 // Try to get the OS/2 table from the font. This contains the specific
1222 // average font width metrics which Windows uses.
1223 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1224
reed@android.com8a1c16f2008-12-17 15:59:43 +00001225 ys[0] = -face->bbox.yMax;
1226 ys[1] = -face->ascender;
1227 ys[2] = -face->descender;
1228 ys[3] = -face->bbox.yMin;
1229 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001230 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1231
1232 SkScalar x_height;
1233 if (os2 && os2->sxHeight) {
1234 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1235 } else {
1236 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1237 if (x_glyph) {
1238 FT_BBox bbox;
1239 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001240 if (fRec.fFlags & kEmbolden_Flag) {
1241 emboldenOutline(&fFace->glyph->outline);
1242 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001243 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1244 x_height = SkIntToScalar(bbox.yMax) / 64;
1245 } else {
1246 x_height = 0;
1247 }
1248 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001249
1250 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001251 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001252 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1253 SkFixed x = SkFixedMul(mxy, y);
1254 y = SkFixedMul(myy, y);
1255 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1256 }
1257
1258 if (mx) {
1259 mx->fTop = pts[0].fX;
1260 mx->fAscent = pts[1].fX;
1261 mx->fDescent = pts[2].fX;
1262 mx->fBottom = pts[3].fX;
1263 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001264 mx->fAvgCharWidth = pts[5].fX;
1265 mx->fXMin = xmin;
1266 mx->fXMax = xmax;
1267 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001268 }
1269 if (my) {
1270 my->fTop = pts[0].fY;
1271 my->fAscent = pts[1].fY;
1272 my->fDescent = pts[2].fY;
1273 my->fBottom = pts[3].fY;
1274 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001275 my->fAvgCharWidth = pts[5].fY;
1276 my->fXMin = xmin;
1277 my->fXMax = xmax;
1278 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001279 }
1280}
1281
1282////////////////////////////////////////////////////////////////////////
1283////////////////////////////////////////////////////////////////////////
1284
1285SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001286 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1287 if (!c->success()) {
1288 SkDELETE(c);
1289 c = NULL;
1290 }
1291 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001292}
1293
1294///////////////////////////////////////////////////////////////////////////////
1295
1296/* Export this so that other parts of our FonttHost port can make use of our
1297 ability to extract the name+style from a stream, using FreeType's api.
1298*/
reed@google.com5b31b0f2011-02-23 14:41:42 +00001299SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
1300 bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001301 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001302 if (FT_Init_FreeType(&library)) {
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001303 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001304 return SkTypeface::kNormal;
1305 }
1306
1307 FT_Open_Args args;
1308 memset(&args, 0, sizeof(args));
1309
1310 const void* memoryBase = stream->getMemoryBase();
1311 FT_StreamRec streamRec;
1312
1313 if (NULL != memoryBase) {
1314 args.flags = FT_OPEN_MEMORY;
1315 args.memory_base = (const FT_Byte*)memoryBase;
1316 args.memory_size = stream->getLength();
1317 } else {
1318 memset(&streamRec, 0, sizeof(streamRec));
1319 streamRec.size = stream->read(NULL, 0);
1320 streamRec.descriptor.pointer = stream;
1321 streamRec.read = sk_stream_read;
1322 streamRec.close = sk_stream_close;
1323
1324 args.flags = FT_OPEN_STREAM;
1325 args.stream = &streamRec;
1326 }
1327
1328 FT_Face face;
1329 if (FT_Open_Face(library, &args, 0, &face)) {
1330 FT_Done_FreeType(library);
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001331 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001332 return SkTypeface::kNormal;
1333 }
1334
1335 name->set(face->family_name);
1336 int style = SkTypeface::kNormal;
1337
1338 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1339 style |= SkTypeface::kBold;
1340 }
1341 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1342 style |= SkTypeface::kItalic;
1343 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001344 if (isFixedWidth) {
1345 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1346 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001347
1348 FT_Done_Face(face);
1349 FT_Done_FreeType(library);
1350 return (SkTypeface::Style)style;
1351}