blob: 7f1e37726027039efa84a5ea33aed55f855d52ab [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
reed@android.comf5493692009-07-22 19:21:01 +000043#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000044#include FT_LCD_FILTER_H
45#endif
46
reed@android.com8a1c16f2008-12-17 15:59:43 +000047#ifdef FT_ADVANCES_H
48#include FT_ADVANCES_H
49#endif
50
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000051#if 0
52// Also include the files by name for build tools which require this.
53#include <freetype/freetype.h>
54#include <freetype/ftoutln.h>
55#include <freetype/ftsizes.h>
56#include <freetype/tttables.h>
57#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000058#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000059#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000060#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000061#endif
62
reed@android.com8a1c16f2008-12-17 15:59:43 +000063//#define ENABLE_GLYPH_SPEW // for tracing calls
64//#define DUMP_STRIKE_CREATION
65
66#ifdef SK_DEBUG
67 #define SkASSERT_CONTINUE(pred) \
68 do { \
69 if (!(pred)) \
70 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
71 } while (false)
72#else
73 #define SkASSERT_CONTINUE(pred)
74#endif
75
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +000076using namespace skia_advanced_typeface_metrics_utils;
77
reed@android.com8a1c16f2008-12-17 15:59:43 +000078//////////////////////////////////////////////////////////////////////////
79
80struct SkFaceRec;
81
82static SkMutex gFTMutex;
83static int gFTCount;
84static FT_Library gFTLibrary;
85static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000086static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
87static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000088
89/////////////////////////////////////////////////////////////////////////
90
agl@chromium.orge76073b2010-06-04 20:31:17 +000091// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
92// This value was chosen by eyeballing the result in Firefox and trying to match it.
93static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
94
agl@chromium.org309485b2009-07-21 17:41:32 +000095static bool
96InitFreetype() {
97 FT_Error err = FT_Init_FreeType(&gFTLibrary);
98 if (err)
99 return false;
100
reed@android.comf5493692009-07-22 19:21:01 +0000101#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000102 // Setup LCD filtering. This reduces colour fringes for LCD rendered
103 // glyphs.
104 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000105 gLCDSupport = err == 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000106#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000107 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000108
109 return true;
110}
111
reed@android.com8a1c16f2008-12-17 15:59:43 +0000112class SkScalerContext_FreeType : public SkScalerContext {
113public:
114 SkScalerContext_FreeType(const SkDescriptor* desc);
115 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000116
reed@android.com62900b42009-02-11 15:07:19 +0000117 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000118 return fFaceRec != NULL &&
119 fFTSize != NULL &&
120 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000121 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000122
123protected:
124 virtual unsigned generateGlyphCount() const;
125 virtual uint16_t generateCharToGlyph(SkUnichar uni);
126 virtual void generateAdvance(SkGlyph* glyph);
127 virtual void generateMetrics(SkGlyph* glyph);
128 virtual void generateImage(const SkGlyph& glyph);
129 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
130 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
131 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000132 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000133
134private:
135 SkFaceRec* fFaceRec;
136 FT_Face fFace; // reference to shared face in gFaceRecHead
137 FT_Size fFTSize; // our own copy
138 SkFixed fScaleX, fScaleY;
139 FT_Matrix fMatrix22;
140 uint32_t fLoadGlyphFlags;
141
142 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000143 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144};
145
146///////////////////////////////////////////////////////////////////////////
147///////////////////////////////////////////////////////////////////////////
148
149#include "SkStream.h"
150
151struct SkFaceRec {
152 SkFaceRec* fNext;
153 FT_Face fFace;
154 FT_StreamRec fFTStream;
155 SkStream* fSkStream;
156 uint32_t fRefCnt;
157 uint32_t fFontID;
158
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000159 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000160 SkFaceRec(SkStream* strm, uint32_t fontID);
161 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000162 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000163 }
164};
165
166extern "C" {
167 static unsigned long sk_stream_read(FT_Stream stream,
168 unsigned long offset,
169 unsigned char* buffer,
170 unsigned long count ) {
171 SkStream* str = (SkStream*)stream->descriptor.pointer;
172
173 if (count) {
174 if (!str->rewind()) {
175 return 0;
176 } else {
177 unsigned long ret;
178 if (offset) {
179 ret = str->read(NULL, offset);
180 if (ret != offset) {
181 return 0;
182 }
183 }
184 ret = str->read(buffer, count);
185 if (ret != count) {
186 return 0;
187 }
188 count = ret;
189 }
190 }
191 return count;
192 }
193
194 static void sk_stream_close( FT_Stream stream) {}
195}
196
197SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
198 : fSkStream(strm), fFontID(fontID) {
199// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
200
reed@android.com4516f472009-06-29 16:25:36 +0000201 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000202 fFTStream.size = fSkStream->getLength();
203 fFTStream.descriptor.pointer = fSkStream;
204 fFTStream.read = sk_stream_read;
205 fFTStream.close = sk_stream_close;
206}
207
reed@android.com62900b42009-02-11 15:07:19 +0000208// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000209static SkFaceRec* ref_ft_face(uint32_t fontID) {
210 SkFaceRec* rec = gFaceRecHead;
211 while (rec) {
212 if (rec->fFontID == fontID) {
213 SkASSERT(rec->fFace);
214 rec->fRefCnt += 1;
215 return rec;
216 }
217 rec = rec->fNext;
218 }
219
220 SkStream* strm = SkFontHost::OpenStream(fontID);
221 if (NULL == strm) {
222 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000223 return 0;
224 }
225
226 // this passes ownership of strm to the rec
227 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
228
229 FT_Open_Args args;
230 memset(&args, 0, sizeof(args));
231 const void* memoryBase = strm->getMemoryBase();
232
233 if (NULL != memoryBase) {
234//printf("mmap(%s)\n", keyString.c_str());
235 args.flags = FT_OPEN_MEMORY;
236 args.memory_base = (const FT_Byte*)memoryBase;
237 args.memory_size = strm->getLength();
238 } else {
239//printf("fopen(%s)\n", keyString.c_str());
240 args.flags = FT_OPEN_STREAM;
241 args.stream = &rec->fFTStream;
242 }
243
agl@chromium.org61a678a2010-08-06 18:08:18 +0000244 int face_index;
245 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
246 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
247 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000248
249 if (err) { // bad filename, try the default font
250 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
251 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000252 return 0;
253 } else {
254 SkASSERT(rec->fFace);
255 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
256 rec->fNext = gFaceRecHead;
257 gFaceRecHead = rec;
258 rec->fRefCnt = 1;
259 return rec;
260 }
261}
262
263static void unref_ft_face(FT_Face face) {
264 SkFaceRec* rec = gFaceRecHead;
265 SkFaceRec* prev = NULL;
266 while (rec) {
267 SkFaceRec* next = rec->fNext;
268 if (rec->fFace == face) {
269 if (--rec->fRefCnt == 0) {
270 if (prev) {
271 prev->fNext = next;
272 } else {
273 gFaceRecHead = next;
274 }
275 FT_Done_Face(face);
276 SkDELETE(rec);
277 }
278 return;
279 }
280 prev = rec;
281 rec = next;
282 }
283 SkASSERT("shouldn't get here, face not in list");
284}
285
286///////////////////////////////////////////////////////////////////////////
287
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000288// Work around for old versions of freetype.
289static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
290 FT_Int32 loadFlags, FT_Fixed* advances) {
291#ifdef FT_ADVANCES_H
292 return FT_Get_Advances(face, start, count, loadFlags, advances);
293#else
294 if (!face || start >= face->num_glyphs ||
295 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
296 return 6; // "Invalid argument."
297 }
298 if (count == 0)
299 return 0;
300
301 for (int i = 0; i < count; i++) {
302 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
303 if (err)
304 return err;
305 advances[i] = face->glyph->advance.x;
306 }
307
308 return 0;
309#endif
310}
311
312static bool canEmbed(FT_Face face) {
313#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
314 FT_UShort fsType = FT_Get_FSType_Flags(face);
315 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
316 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
317#else
318 // No embedding is 0x2 and bitmap embedding only is 0x200.
319 TT_OS2* os2_table;
320 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
321 return (os2_table->fsType & 0x202) == 0;
322 }
323 return false; // We tried, fail safe.
324#endif
325}
326
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000327static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
328 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
329 if (!glyph_id)
330 return false;
331 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
332 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
333 return true;
334}
335
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000336static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000337 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000338 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
339 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000340 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000341 SkASSERT(data);
342 *data = advance;
343 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000344}
345
346// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000347SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
348 uint32_t fontID, bool perGlyphInfo) {
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 SkASSERT(!FT_HAS_VERTICAL(face));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000388#ifdef FT_IS_CID_KEYED
389 SkASSERT(FT_IS_CID_KEYED(face) ==
390 (info->fType == SkAdvancedTypefaceMetrics::kType1CID_Font));
391#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000392
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000393 info->fStyle = 0;
394 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000395 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000396 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000397 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000398 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
399 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000400 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
401
402 PS_FontInfoRec ps_info;
403 TT_Postscript* tt_info;
404 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
405 info->fItalicAngle = ps_info.italic_angle;
406 } else if ((tt_info =
407 (TT_Postscript*)FT_Get_Sfnt_Table(face,
408 ft_sfnt_post)) != NULL) {
409 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
410 } else {
411 info->fItalicAngle = 0;
412 }
413
414 info->fAscent = face->ascender;
415 info->fDescent = face->descender;
416
417 // Figure out a good guess for StemV - Min width of i, I, !, 1.
418 // This probably isn't very good with an italic font.
419 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000420 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000421 char stem_chars[] = {'i', 'I', '!', '1'};
422 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
423 FT_BBox bbox;
424 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
425 int16_t width = bbox.xMax - bbox.xMin;
426 if (width > 0 && width < min_width) {
427 min_width = width;
428 info->fStemV = min_width;
429 }
430 }
431 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000432
433 TT_PCLT* pclt_info;
434 TT_OS2* os2_table;
435 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
436 info->fCapHeight = pclt_info->CapHeight;
437 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
438 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000439 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000440 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000441 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000442 } else if ((os2_table =
443 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
444 info->fCapHeight = os2_table->sCapHeight;
445 } else {
446 // Figure out a good guess for CapHeight: average the height of M and X.
447 FT_BBox m_bbox, x_bbox;
448 bool got_m, got_x;
449 got_m = GetLetterCBox(face, 'M', &m_bbox);
450 got_x = GetLetterCBox(face, 'X', &x_bbox);
451 if (got_m && got_x) {
452 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
453 x_bbox.yMin) / 2;
454 } else if (got_m && !got_x) {
455 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
456 } else if (!got_m && got_x) {
457 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
458 }
459 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000460
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000461 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
462 face->bbox.xMax, face->bbox.yMin);
463
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000464 if (perGlyphInfo && canEmbed(face) && FT_IS_SCALABLE(face) &&
465 info->fType != SkAdvancedTypefaceMetrics::kOther_Font) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000466 if (FT_IS_FIXED_WIDTH(face)) {
467 appendRange(&info->fGlyphWidths, 0);
468 int16_t advance = face->max_advance_width;
469 info->fGlyphWidths->fAdvance.append(1, &advance);
470 finishRange(info->fGlyphWidths.get(), 0,
471 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000472 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000473 appendRange(&info->fGlyphWidths, 0);
474 // So as to not blow out the stack, get advances in batches.
475 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
476 FT_Fixed advances[128];
477 int advanceCount = 128;
478 if (gID + advanceCount > face->num_glyphs)
479 advanceCount = face->num_glyphs - gID + 1;
480 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
481 advances);
482 for (int i = 0; i < advanceCount; i++) {
483 int16_t advance = advances[gID + i];
484 info->fGlyphWidths->fAdvance.append(1, &advance);
485 }
486 }
487 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
488 SkAdvancedTypefaceMetrics::WidthRange::kRange);
489 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000490 info->fGlyphWidths.reset(
491 getAdvanceData(face, face->num_glyphs, &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000492 }
493
494 if (info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
495 // Postscript fonts may contain more than 255 glyphs, so we end up
496 // using multiple font descriptions with a glyph ordering. Record
497 // the name of each glyph.
498 info->fGlyphNames.reset(
499 new SkAutoTArray<SkString>(face->num_glyphs));
500 for (int gID = 0; gID < face->num_glyphs; gID++) {
501 char glyphName[128]; // PS limit for names is 127 bytes.
502 FT_Get_Glyph_Name(face, gID, glyphName, 128);
503 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000504 }
505 }
506 }
507
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000508 if (!canEmbed(face))
509 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
510
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000511 unref_ft_face(face);
512 return info;
513}
reed@google.com618ef5e2011-01-26 22:10:41 +0000514///////////////////////////////////////////////////////////////////////////
515
516void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
517 if (!gLCDSupportValid) {
518 InitFreetype();
519 FT_Done_FreeType(gFTLibrary);
520 }
521
522 if (!gLCDSupport && rec->isLCD()) {
523 // If the runtime Freetype library doesn't support LCD mode, we disable
524 // it here.
525 rec->fMaskFormat = SkMask::kA8_Format;
526 }
527
528 SkPaint::Hinting h = rec->getHinting();
529 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
530 // collapse full->normal hinting if we're not doing LCD
531 h = SkPaint::kNormal_Hinting;
532 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
533 SkPaint::kNo_Hinting != h) {
534 // to do subpixel, we must have at most slight hinting
535 h = SkPaint::kSlight_Hinting;
536 }
537 rec->setHinting(h);
538}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000539
reed@android.com8a1c16f2008-12-17 15:59:43 +0000540SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000541 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000542 SkAutoMutexAcquire ac(gFTMutex);
543
reed@android.com8a1c16f2008-12-17 15:59:43 +0000544 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000545 if (!InitFreetype()) {
546 sk_throw();
547 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000548 }
549 ++gFTCount;
550
551 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000552 fFTSize = NULL;
553 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000554 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000555 if (NULL == fFaceRec) {
556 return;
557 }
558 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000559
560 // compute our factors from the record
561
562 SkMatrix m;
563
564 fRec.getSingleMatrix(&m);
565
566#ifdef DUMP_STRIKE_CREATION
567 SkString keyString;
568 SkFontHost::GetDescriptorKeyString(desc, &keyString);
569 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
570 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
571 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
572 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000573 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000574#endif
575
576 // now compute our scale factors
577 SkScalar sx = m.getScaleX();
578 SkScalar sy = m.getScaleY();
579
580 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
581 // sort of give up on hinting
582 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
583 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
584 sx = sy = SkScalarAve(sx, sy);
585
586 SkScalar inv = SkScalarInvert(sx);
587
588 // flip the skew elements to go from our Y-down system to FreeType's
589 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
590 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
591 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
592 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
593 } else {
594 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
595 fMatrix22.xy = fMatrix22.yx = 0;
596 }
597
598 fScaleX = SkScalarToFixed(sx);
599 fScaleY = SkScalarToFixed(sy);
600
601 // compute the flags we send to Load_Glyph
602 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000603 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000604
agl@chromium.org70a303f2010-05-10 14:15:50 +0000605 if (SkMask::kBW_Format == fRec.fMaskFormat) {
606 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
607 loadFlags = FT_LOAD_TARGET_MONO;
608 if (fRec.getHinting() == SkPaint::kNo_Hinting)
609 loadFlags = FT_LOAD_NO_HINTING;
610 } else {
611 switch (fRec.getHinting()) {
612 case SkPaint::kNo_Hinting:
613 loadFlags = FT_LOAD_NO_HINTING;
614 break;
615 case SkPaint::kSlight_Hinting:
616 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
617 break;
618 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000619 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
620 loadFlags = FT_LOAD_FORCE_AUTOHINT;
621 else
622 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000623 break;
624 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000625 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
626 loadFlags = FT_LOAD_FORCE_AUTOHINT;
627 break;
628 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000629 loadFlags = FT_LOAD_TARGET_NORMAL;
630 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
631 loadFlags = FT_LOAD_TARGET_LCD;
632 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
633 loadFlags = FT_LOAD_TARGET_LCD_V;
634 break;
635 default:
636 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
637 break;
638 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000639 }
640
agl@chromium.org99e1b902010-01-05 01:19:44 +0000641 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000642 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000643
reed@android.come4d0bc02009-07-24 19:53:20 +0000644 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000645 }
646
647 // now create the FT_Size
648
649 {
650 FT_Error err;
651
652 err = FT_New_Size(fFace, &fFTSize);
653 if (err != 0) {
654 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
655 fFaceRec->fFontID, fScaleX, fScaleY, err));
656 fFace = NULL;
657 return;
658 }
659
660 err = FT_Activate_Size(fFTSize);
661 if (err != 0) {
662 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
663 fFaceRec->fFontID, fScaleX, fScaleY, err));
664 fFTSize = NULL;
665 }
666
667 err = FT_Set_Char_Size( fFace,
668 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
669 72, 72);
670 if (err != 0) {
671 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
672 fFaceRec->fFontID, fScaleX, fScaleY, err));
673 fFace = NULL;
674 return;
675 }
676
677 FT_Set_Transform( fFace, &fMatrix22, NULL);
678 }
679}
680
681SkScalerContext_FreeType::~SkScalerContext_FreeType() {
682 if (fFTSize != NULL) {
683 FT_Done_Size(fFTSize);
684 }
685
686 SkAutoMutexAcquire ac(gFTMutex);
687
688 if (fFace != NULL) {
689 unref_ft_face(fFace);
690 }
691 if (--gFTCount == 0) {
692// SkDEBUGF(("FT_Done_FreeType\n"));
693 FT_Done_FreeType(gFTLibrary);
694 SkDEBUGCODE(gFTLibrary = NULL;)
695 }
696}
697
698/* We call this before each use of the fFace, since we may be sharing
699 this face with other context (at different sizes).
700*/
701FT_Error SkScalerContext_FreeType::setupSize() {
702 /* In the off-chance that a font has been removed, we want to error out
703 right away, so call resolve just to be sure.
704
705 TODO: perhaps we can skip this, by walking the global font cache and
706 killing all of the contexts when we know that a given fontID is going
707 away...
708 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000709 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000710 return (FT_Error)-1;
711 }
712
713 FT_Error err = FT_Activate_Size(fFTSize);
714
715 if (err != 0) {
716 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
717 fFaceRec->fFontID, fScaleX, fScaleY, err));
718 fFTSize = NULL;
719 } else {
720 // seems we need to reset this every time (not sure why, but without it
721 // I get random italics from some other fFTSize)
722 FT_Set_Transform( fFace, &fMatrix22, NULL);
723 }
724 return err;
725}
726
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000727void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
728 FT_Pos strength;
729 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
730 / 24;
731 FT_Outline_Embolden(outline, strength);
732}
733
reed@android.com8a1c16f2008-12-17 15:59:43 +0000734unsigned SkScalerContext_FreeType::generateGlyphCount() const {
735 return fFace->num_glyphs;
736}
737
738uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
739 return SkToU16(FT_Get_Char_Index( fFace, uni ));
740}
741
reed@android.com9d3a9852010-01-08 14:07:42 +0000742SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
743 // iterate through each cmap entry, looking for matching glyph indices
744 FT_UInt glyphIndex;
745 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
746
747 while (glyphIndex != 0) {
748 if (glyphIndex == glyph) {
749 return charCode;
750 }
751 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
752 }
753
754 return 0;
755}
756
reed@android.com8a1c16f2008-12-17 15:59:43 +0000757static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
758 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000759 case SkMask::kHorizontalLCD_Format:
760 case SkMask::kVerticalLCD_Format:
761 SkASSERT(!"An LCD format should never be passed here");
762 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000763 case SkMask::kBW_Format:
764 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000765 case SkMask::kA8_Format:
766 default:
767 return FT_PIXEL_MODE_GRAY;
768 }
769}
770
reed@android.com8a1c16f2008-12-17 15:59:43 +0000771void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
772#ifdef FT_ADVANCES_H
773 /* unhinted and light hinted text have linearly scaled advances
774 * which are very cheap to compute with some font formats...
775 */
776 {
777 SkAutoMutexAcquire ac(gFTMutex);
778
779 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000780 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000781 return;
782 }
783
784 FT_Error error;
785 FT_Fixed advance;
786
787 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
788 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
789 &advance );
790 if (0 == error) {
791 glyph->fRsbDelta = 0;
792 glyph->fLsbDelta = 0;
793 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
794 glyph->fAdvanceY = 0;
795 return;
796 }
797 }
798#endif /* FT_ADVANCES_H */
799 /* otherwise, we need to load/hint the glyph, which is slower */
800 this->generateMetrics(glyph);
801 return;
802}
803
804void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
805 SkAutoMutexAcquire ac(gFTMutex);
806
807 glyph->fRsbDelta = 0;
808 glyph->fLsbDelta = 0;
809
810 FT_Error err;
811
812 if (this->setupSize()) {
813 goto ERROR;
814 }
815
816 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
817 if (err != 0) {
818 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
819 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
820 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000821 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000822 return;
823 }
824
825 switch ( fFace->glyph->format ) {
826 case FT_GLYPH_FORMAT_OUTLINE:
827 FT_BBox bbox;
828
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000829 if (fRec.fFlags & kEmbolden_Flag) {
830 emboldenOutline(&fFace->glyph->outline);
831 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000832 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
833
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000834 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000835 int dx = glyph->getSubXFixed() >> 10;
836 int dy = glyph->getSubYFixed() >> 10;
837 // negate dy since freetype-y-goes-up and skia-y-goes-down
838 bbox.xMin += dx;
839 bbox.yMin -= dy;
840 bbox.xMax += dx;
841 bbox.yMax -= dy;
842 }
843
844 bbox.xMin &= ~63;
845 bbox.yMin &= ~63;
846 bbox.xMax = (bbox.xMax + 63) & ~63;
847 bbox.yMax = (bbox.yMax + 63) & ~63;
848
849 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
850 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
851 glyph->fTop = -SkToS16(bbox.yMax >> 6);
852 glyph->fLeft = SkToS16(bbox.xMin >> 6);
853 break;
854
855 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000856 if (fRec.fFlags & kEmbolden_Flag) {
857 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
858 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
859 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000860 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
861 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
862 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
863 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
864 break;
865
866 default:
867 SkASSERT(!"unknown glyph format");
868 goto ERROR;
869 }
870
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000871 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000872 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
873 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
874 if (fRec.fFlags & kDevKernText_Flag) {
875 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
876 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
877 }
878 } else {
879 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
880 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
881 }
882
883#ifdef ENABLE_GLYPH_SPEW
884 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
885 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
886#endif
887}
888
reed@android.comf5493692009-07-22 19:21:01 +0000889#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000890namespace skia_freetype_support {
891// extern functions from SkFontHost_FreeType_Subpixel
892extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
893extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
894}
895
896using namespace skia_freetype_support;
897#endif
898
reed@android.com8a1c16f2008-12-17 15:59:43 +0000899void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
900 SkAutoMutexAcquire ac(gFTMutex);
901
902 FT_Error err;
903
904 if (this->setupSize()) {
905 goto ERROR;
906 }
907
908 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
909 if (err != 0) {
910 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
911 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
912 ERROR:
913 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
914 return;
915 }
916
agl@chromium.org309485b2009-07-21 17:41:32 +0000917 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
918 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
919
reed@android.com8a1c16f2008-12-17 15:59:43 +0000920 switch ( fFace->glyph->format ) {
921 case FT_GLYPH_FORMAT_OUTLINE: {
922 FT_Outline* outline = &fFace->glyph->outline;
923 FT_BBox bbox;
924 FT_Bitmap target;
925
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000926 if (fRec.fFlags & kEmbolden_Flag) {
927 emboldenOutline(outline);
928 }
929
reed@android.com8a1c16f2008-12-17 15:59:43 +0000930 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000931 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000932 dx = glyph.getSubXFixed() >> 10;
933 dy = glyph.getSubYFixed() >> 10;
934 // negate dy since freetype-y-goes-up and skia-y-goes-down
935 dy = -dy;
936 }
937 FT_Outline_Get_CBox(outline, &bbox);
938 /*
939 what we really want to do for subpixel is
940 offset(dx, dy)
941 compute_bounds
942 offset(bbox & !63)
943 but that is two calls to offset, so we do the following, which
944 achieves the same thing with only one offset call.
945 */
946 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
947 dy - ((bbox.yMin + dy) & ~63));
948
reed@android.comf5493692009-07-22 19:21:01 +0000949#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000950 if (lcdRenderMode) {
951 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
952 // we have to call FT_Render_Glyph and memcpy the image out.
953 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
954 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
955 FT_Render_Glyph(fFace->glyph, mode);
956
957 if (isVertical)
958 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
959 else
960 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
961
962 break;
963 }
964#endif
965
reed@android.com8a1c16f2008-12-17 15:59:43 +0000966 target.width = glyph.fWidth;
967 target.rows = glyph.fHeight;
968 target.pitch = glyph.rowBytes();
969 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
970 target.pixel_mode = compute_pixel_mode(
971 (SkMask::Format)fRec.fMaskFormat);
972 target.num_grays = 256;
973
974 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
975 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
976 } break;
977
978 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +0000979 if (fRec.fFlags & kEmbolden_Flag) {
980 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
981 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
982 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
984 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
985 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
986 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
987
988 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
989 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000990
agl@chromium.org558434a2009-08-11 17:22:38 +0000991 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
992 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
993 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000994 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
995 unsigned dstRowBytes = glyph.rowBytes();
996 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
997 unsigned extraRowBytes = dstRowBytes - minRowBytes;
998
999 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1000 memcpy(dst, src, minRowBytes);
1001 memset(dst + minRowBytes, 0, extraRowBytes);
1002 src += srcRowBytes;
1003 dst += dstRowBytes;
1004 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001005 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001006 (glyph.fMaskFormat == SkMask::kA8_Format ||
1007 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1008 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001009 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1010 uint8_t byte = 0;
1011 int bits = 0;
1012 const uint8_t* src_row = src;
1013 uint8_t* dst_row = dst;
1014
1015 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1016 if (!bits) {
1017 byte = *src_row++;
1018 bits = 8;
1019 }
1020
1021 *dst_row++ = byte & 0x80 ? 0xff : 0;
1022 bits--;
1023 byte <<= 1;
1024 }
1025
1026 src += fFace->glyph->bitmap.pitch;
1027 dst += glyph.rowBytes();
1028 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001029 } else {
1030 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001031 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001032
1033 if (lcdRenderMode)
1034 glyph.expandA8ToLCD();
1035
reed@android.com8a1c16f2008-12-17 15:59:43 +00001036 } break;
1037
1038 default:
1039 SkASSERT(!"unknown glyph format");
1040 goto ERROR;
1041 }
1042}
1043
1044///////////////////////////////////////////////////////////////////////////////
1045
1046#define ft2sk(x) SkFixedToScalar((x) << 10)
1047
reed@android.com6f252972009-01-14 16:46:16 +00001048#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001049 #define CONST_PARAM const
1050#else // older freetype doesn't use const here
1051 #define CONST_PARAM
1052#endif
1053
1054static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1055 SkPath* path = (SkPath*)ctx;
1056 path->close(); // to close the previous contour (if any)
1057 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1058 return 0;
1059}
1060
1061static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1062 SkPath* path = (SkPath*)ctx;
1063 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1064 return 0;
1065}
1066
1067static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1068 void* ctx) {
1069 SkPath* path = (SkPath*)ctx;
1070 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1071 return 0;
1072}
1073
1074static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1075 CONST_PARAM FT_Vector* pt2, void* ctx) {
1076 SkPath* path = (SkPath*)ctx;
1077 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1078 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1079 return 0;
1080}
1081
1082void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1083 SkPath* path) {
1084 SkAutoMutexAcquire ac(gFTMutex);
1085
1086 SkASSERT(&glyph && path);
1087
1088 if (this->setupSize()) {
1089 path->reset();
1090 return;
1091 }
1092
1093 uint32_t flags = fLoadGlyphFlags;
1094 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1095 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1096
1097 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1098
1099 if (err != 0) {
1100 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1101 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1102 path->reset();
1103 return;
1104 }
1105
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001106 if (fRec.fFlags & kEmbolden_Flag) {
1107 emboldenOutline(&fFace->glyph->outline);
1108 }
1109
reed@android.com8a1c16f2008-12-17 15:59:43 +00001110 FT_Outline_Funcs funcs;
1111
1112 funcs.move_to = move_proc;
1113 funcs.line_to = line_proc;
1114 funcs.conic_to = quad_proc;
1115 funcs.cubic_to = cubic_proc;
1116 funcs.shift = 0;
1117 funcs.delta = 0;
1118
1119 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1120
1121 if (err != 0) {
1122 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1123 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1124 path->reset();
1125 return;
1126 }
1127
1128 path->close();
1129}
1130
1131void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1132 SkPaint::FontMetrics* my) {
1133 if (NULL == mx && NULL == my) {
1134 return;
1135 }
1136
1137 SkAutoMutexAcquire ac(gFTMutex);
1138
1139 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001140 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001141 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001142 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001143 }
1144 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001145 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001146 }
1147 return;
1148 }
1149
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001150 FT_Face face = fFace;
1151 int upem = face->units_per_EM;
1152 if (upem <= 0) {
1153 goto ERROR;
1154 }
1155
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001156 SkPoint pts[6];
1157 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001158 SkFixed scaleY = fScaleY;
1159 SkFixed mxy = fMatrix22.xy;
1160 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001161 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1162 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001163
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001164 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001165 if (leading < 0) {
1166 leading = 0;
1167 }
1168
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001169 // Try to get the OS/2 table from the font. This contains the specific
1170 // average font width metrics which Windows uses.
1171 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1172
reed@android.com8a1c16f2008-12-17 15:59:43 +00001173 ys[0] = -face->bbox.yMax;
1174 ys[1] = -face->ascender;
1175 ys[2] = -face->descender;
1176 ys[3] = -face->bbox.yMin;
1177 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001178 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1179
1180 SkScalar x_height;
1181 if (os2 && os2->sxHeight) {
1182 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1183 } else {
1184 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1185 if (x_glyph) {
1186 FT_BBox bbox;
1187 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001188 if (fRec.fFlags & kEmbolden_Flag) {
1189 emboldenOutline(&fFace->glyph->outline);
1190 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001191 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1192 x_height = SkIntToScalar(bbox.yMax) / 64;
1193 } else {
1194 x_height = 0;
1195 }
1196 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001197
1198 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001199 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001200 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1201 SkFixed x = SkFixedMul(mxy, y);
1202 y = SkFixedMul(myy, y);
1203 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1204 }
1205
1206 if (mx) {
1207 mx->fTop = pts[0].fX;
1208 mx->fAscent = pts[1].fX;
1209 mx->fDescent = pts[2].fX;
1210 mx->fBottom = pts[3].fX;
1211 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001212 mx->fAvgCharWidth = pts[5].fX;
1213 mx->fXMin = xmin;
1214 mx->fXMax = xmax;
1215 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001216 }
1217 if (my) {
1218 my->fTop = pts[0].fY;
1219 my->fAscent = pts[1].fY;
1220 my->fDescent = pts[2].fY;
1221 my->fBottom = pts[3].fY;
1222 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001223 my->fAvgCharWidth = pts[5].fY;
1224 my->fXMin = xmin;
1225 my->fXMax = xmax;
1226 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001227 }
1228}
1229
1230////////////////////////////////////////////////////////////////////////
1231////////////////////////////////////////////////////////////////////////
1232
1233SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001234 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1235 if (!c->success()) {
1236 SkDELETE(c);
1237 c = NULL;
1238 }
1239 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001240}
1241
1242///////////////////////////////////////////////////////////////////////////////
1243
1244/* Export this so that other parts of our FonttHost port can make use of our
1245 ability to extract the name+style from a stream, using FreeType's api.
1246*/
1247SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
1248 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001249 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001250 name->set(NULL);
1251 return SkTypeface::kNormal;
1252 }
1253
1254 FT_Open_Args args;
1255 memset(&args, 0, sizeof(args));
1256
1257 const void* memoryBase = stream->getMemoryBase();
1258 FT_StreamRec streamRec;
1259
1260 if (NULL != memoryBase) {
1261 args.flags = FT_OPEN_MEMORY;
1262 args.memory_base = (const FT_Byte*)memoryBase;
1263 args.memory_size = stream->getLength();
1264 } else {
1265 memset(&streamRec, 0, sizeof(streamRec));
1266 streamRec.size = stream->read(NULL, 0);
1267 streamRec.descriptor.pointer = stream;
1268 streamRec.read = sk_stream_read;
1269 streamRec.close = sk_stream_close;
1270
1271 args.flags = FT_OPEN_STREAM;
1272 args.stream = &streamRec;
1273 }
1274
1275 FT_Face face;
1276 if (FT_Open_Face(library, &args, 0, &face)) {
1277 FT_Done_FreeType(library);
1278 name->set(NULL);
1279 return SkTypeface::kNormal;
1280 }
1281
1282 name->set(face->family_name);
1283 int style = SkTypeface::kNormal;
1284
1285 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1286 style |= SkTypeface::kBold;
1287 }
1288 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1289 style |= SkTypeface::kItalic;
1290 }
1291
1292 FT_Done_Face(face);
1293 FT_Done_FreeType(library);
1294 return (SkTypeface::Style)style;
1295}