blob: 1c0b269fa75f06e19587c334f1490b5a4e6136d5 [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@google.comea2333d2011-03-14 16:44:56 +000043#if defined(SK_SUPPORT_LCDTEXT) || true
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);
reed@google.comea2333d2011-03-14 16:44:56 +000098 if (err) {
agl@chromium.org309485b2009-07-21 17:41:32 +000099 return false;
reed@google.comea2333d2011-03-14 16:44:56 +0000100 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000101
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;
reed@android.com61608aa2009-07-31 14:52:54 +0000106 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000107
108 return true;
109}
110
reed@android.com8a1c16f2008-12-17 15:59:43 +0000111class SkScalerContext_FreeType : public SkScalerContext {
112public:
113 SkScalerContext_FreeType(const SkDescriptor* desc);
114 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000115
reed@android.com62900b42009-02-11 15:07:19 +0000116 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000117 return fFaceRec != NULL &&
118 fFTSize != NULL &&
119 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000120 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000121
122protected:
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000123 virtual unsigned generateGlyphCount();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000124 virtual uint16_t generateCharToGlyph(SkUnichar uni);
125 virtual void generateAdvance(SkGlyph* glyph);
126 virtual void generateMetrics(SkGlyph* glyph);
127 virtual void generateImage(const SkGlyph& glyph);
128 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
129 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
130 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000131 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000132
133private:
134 SkFaceRec* fFaceRec;
135 FT_Face fFace; // reference to shared face in gFaceRecHead
136 FT_Size fFTSize; // our own copy
137 SkFixed fScaleX, fScaleY;
138 FT_Matrix fMatrix22;
139 uint32_t fLoadGlyphFlags;
140
141 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000142 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000143};
144
145///////////////////////////////////////////////////////////////////////////
146///////////////////////////////////////////////////////////////////////////
147
148#include "SkStream.h"
149
150struct SkFaceRec {
151 SkFaceRec* fNext;
152 FT_Face fFace;
153 FT_StreamRec fFTStream;
154 SkStream* fSkStream;
155 uint32_t fRefCnt;
156 uint32_t fFontID;
157
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000158 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000159 SkFaceRec(SkStream* strm, uint32_t fontID);
160 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000161 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000162 }
163};
164
165extern "C" {
166 static unsigned long sk_stream_read(FT_Stream stream,
167 unsigned long offset,
168 unsigned char* buffer,
169 unsigned long count ) {
170 SkStream* str = (SkStream*)stream->descriptor.pointer;
171
172 if (count) {
173 if (!str->rewind()) {
174 return 0;
175 } else {
176 unsigned long ret;
177 if (offset) {
178 ret = str->read(NULL, offset);
179 if (ret != offset) {
180 return 0;
181 }
182 }
183 ret = str->read(buffer, count);
184 if (ret != count) {
185 return 0;
186 }
187 count = ret;
188 }
189 }
190 return count;
191 }
192
193 static void sk_stream_close( FT_Stream stream) {}
194}
195
196SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
197 : fSkStream(strm), fFontID(fontID) {
198// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
199
reed@android.com4516f472009-06-29 16:25:36 +0000200 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000201 fFTStream.size = fSkStream->getLength();
202 fFTStream.descriptor.pointer = fSkStream;
203 fFTStream.read = sk_stream_read;
204 fFTStream.close = sk_stream_close;
205}
206
reed@android.com62900b42009-02-11 15:07:19 +0000207// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000208static SkFaceRec* ref_ft_face(uint32_t fontID) {
209 SkFaceRec* rec = gFaceRecHead;
210 while (rec) {
211 if (rec->fFontID == fontID) {
212 SkASSERT(rec->fFace);
213 rec->fRefCnt += 1;
214 return rec;
215 }
216 rec = rec->fNext;
217 }
218
219 SkStream* strm = SkFontHost::OpenStream(fontID);
220 if (NULL == strm) {
221 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000222 return 0;
223 }
224
225 // this passes ownership of strm to the rec
226 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
227
228 FT_Open_Args args;
229 memset(&args, 0, sizeof(args));
230 const void* memoryBase = strm->getMemoryBase();
231
232 if (NULL != memoryBase) {
233//printf("mmap(%s)\n", keyString.c_str());
234 args.flags = FT_OPEN_MEMORY;
235 args.memory_base = (const FT_Byte*)memoryBase;
236 args.memory_size = strm->getLength();
237 } else {
238//printf("fopen(%s)\n", keyString.c_str());
239 args.flags = FT_OPEN_STREAM;
240 args.stream = &rec->fFTStream;
241 }
242
agl@chromium.org61a678a2010-08-06 18:08:18 +0000243 int face_index;
244 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
245 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
246 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000247
248 if (err) { // bad filename, try the default font
249 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
250 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000251 return 0;
252 } else {
253 SkASSERT(rec->fFace);
254 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
255 rec->fNext = gFaceRecHead;
256 gFaceRecHead = rec;
257 rec->fRefCnt = 1;
258 return rec;
259 }
260}
261
262static void unref_ft_face(FT_Face face) {
263 SkFaceRec* rec = gFaceRecHead;
264 SkFaceRec* prev = NULL;
265 while (rec) {
266 SkFaceRec* next = rec->fNext;
267 if (rec->fFace == face) {
268 if (--rec->fRefCnt == 0) {
269 if (prev) {
270 prev->fNext = next;
271 } else {
272 gFaceRecHead = next;
273 }
274 FT_Done_Face(face);
275 SkDELETE(rec);
276 }
277 return;
278 }
279 prev = rec;
280 rec = next;
281 }
282 SkASSERT("shouldn't get here, face not in list");
283}
284
285///////////////////////////////////////////////////////////////////////////
286
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000287// Work around for old versions of freetype.
288static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
289 FT_Int32 loadFlags, FT_Fixed* advances) {
290#ifdef FT_ADVANCES_H
291 return FT_Get_Advances(face, start, count, loadFlags, advances);
292#else
293 if (!face || start >= face->num_glyphs ||
294 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
295 return 6; // "Invalid argument."
296 }
297 if (count == 0)
298 return 0;
299
300 for (int i = 0; i < count; i++) {
301 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
302 if (err)
303 return err;
304 advances[i] = face->glyph->advance.x;
305 }
306
307 return 0;
308#endif
309}
310
311static bool canEmbed(FT_Face face) {
312#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
313 FT_UShort fsType = FT_Get_FSType_Flags(face);
314 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
315 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
316#else
317 // No embedding is 0x2 and bitmap embedding only is 0x200.
318 TT_OS2* os2_table;
319 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
320 return (os2_table->fsType & 0x202) == 0;
321 }
322 return false; // We tried, fail safe.
323#endif
324}
325
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000326static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
327 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
328 if (!glyph_id)
329 return false;
330 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
331 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
332 return true;
333}
334
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000335static bool getWidthAdvance(FT_Face face, int gId, int16_t* data) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000336 FT_Fixed advance = 0;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000337 if (getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance)) {
338 return false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000339 }
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000340 SkASSERT(data);
341 *data = advance;
342 return true;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000343}
344
345// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000346SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
347 uint32_t fontID, bool perGlyphInfo) {
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000348#if defined(SK_BUILD_FOR_MAC) || defined(ANDROID)
reed@google.com8a5d6922011-03-14 15:08:03 +0000349 return NULL;
350#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000351 SkAutoMutexAcquire ac(gFTMutex);
352 FT_Library libInit = NULL;
353 if (gFTCount == 0) {
354 if (!InitFreetype())
355 sk_throw();
356 libInit = gFTLibrary;
357 }
358 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
359 SkFaceRec* rec = ref_ft_face(fontID);
360 if (NULL == rec)
361 return NULL;
362 FT_Face face = rec->fFace;
363
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000364 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
365 info->fFontName.set(FT_Get_Postscript_Name(face));
366 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
367 info->fLastGlyphID = face->num_glyphs - 1;
368 info->fEmSize = 1000;
369
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000370 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000371 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000372 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000373 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000374 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000375 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000376 cid = true;
377 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000378 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000379 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000380 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000381 cid = true;
382 TT_Header* ttHeader;
383 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
384 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000385 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000386 }
387 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000388
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000389 SkASSERT(!FT_HAS_VERTICAL(face));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000390#ifdef FT_IS_CID_KEYED
391 SkASSERT(FT_IS_CID_KEYED(face) ==
392 (info->fType == SkAdvancedTypefaceMetrics::kType1CID_Font));
393#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000394
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000395 info->fStyle = 0;
396 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000397 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000398 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000399 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000400 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
401 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000402 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
403
404 PS_FontInfoRec ps_info;
405 TT_Postscript* tt_info;
406 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
407 info->fItalicAngle = ps_info.italic_angle;
408 } else if ((tt_info =
409 (TT_Postscript*)FT_Get_Sfnt_Table(face,
410 ft_sfnt_post)) != NULL) {
411 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
412 } else {
413 info->fItalicAngle = 0;
414 }
415
416 info->fAscent = face->ascender;
417 info->fDescent = face->descender;
418
419 // Figure out a good guess for StemV - Min width of i, I, !, 1.
420 // This probably isn't very good with an italic font.
421 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000422 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000423 char stem_chars[] = {'i', 'I', '!', '1'};
424 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
425 FT_BBox bbox;
426 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
427 int16_t width = bbox.xMax - bbox.xMin;
428 if (width > 0 && width < min_width) {
429 min_width = width;
430 info->fStemV = min_width;
431 }
432 }
433 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000434
435 TT_PCLT* pclt_info;
436 TT_OS2* os2_table;
437 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
438 info->fCapHeight = pclt_info->CapHeight;
439 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
440 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000441 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000442 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000443 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000444 } else if ((os2_table =
445 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
446 info->fCapHeight = os2_table->sCapHeight;
447 } else {
448 // Figure out a good guess for CapHeight: average the height of M and X.
449 FT_BBox m_bbox, x_bbox;
450 bool got_m, got_x;
451 got_m = GetLetterCBox(face, 'M', &m_bbox);
452 got_x = GetLetterCBox(face, 'X', &x_bbox);
453 if (got_m && got_x) {
454 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
455 x_bbox.yMin) / 2;
456 } else if (got_m && !got_x) {
457 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
458 } else if (!got_m && got_x) {
459 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
460 }
461 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000462
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000463 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
464 face->bbox.xMax, face->bbox.yMin);
465
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000466 if (perGlyphInfo && canEmbed(face) && FT_IS_SCALABLE(face) &&
467 info->fType != SkAdvancedTypefaceMetrics::kOther_Font) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000468 if (FT_IS_FIXED_WIDTH(face)) {
469 appendRange(&info->fGlyphWidths, 0);
470 int16_t advance = face->max_advance_width;
471 info->fGlyphWidths->fAdvance.append(1, &advance);
472 finishRange(info->fGlyphWidths.get(), 0,
473 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000474 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000475 appendRange(&info->fGlyphWidths, 0);
476 // So as to not blow out the stack, get advances in batches.
477 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
478 FT_Fixed advances[128];
479 int advanceCount = 128;
480 if (gID + advanceCount > face->num_glyphs)
481 advanceCount = face->num_glyphs - gID + 1;
482 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
483 advances);
484 for (int i = 0; i < advanceCount; i++) {
485 int16_t advance = advances[gID + i];
486 info->fGlyphWidths->fAdvance.append(1, &advance);
487 }
488 }
489 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
490 SkAdvancedTypefaceMetrics::WidthRange::kRange);
491 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000492 info->fGlyphWidths.reset(
493 getAdvanceData(face, face->num_glyphs, &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000494 }
495
496 if (info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
497 // Postscript fonts may contain more than 255 glyphs, so we end up
498 // using multiple font descriptions with a glyph ordering. Record
499 // the name of each glyph.
500 info->fGlyphNames.reset(
501 new SkAutoTArray<SkString>(face->num_glyphs));
502 for (int gID = 0; gID < face->num_glyphs; gID++) {
503 char glyphName[128]; // PS limit for names is 127 bytes.
504 FT_Get_Glyph_Name(face, gID, glyphName, 128);
505 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000506 }
507 }
508 }
509
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000510 if (!canEmbed(face))
511 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
512
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000513 unref_ft_face(face);
514 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000515#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000516}
reed@google.com618ef5e2011-01-26 22:10:41 +0000517///////////////////////////////////////////////////////////////////////////
518
519void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
520 if (!gLCDSupportValid) {
521 InitFreetype();
522 FT_Done_FreeType(gFTLibrary);
523 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000524
reed@google.com8abde0a2011-03-14 17:45:33 +0000525 if (!gLCDSupport && (rec->isLCD() || SkMask::kLCD16_Format == rec->fMaskFormat)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000526 // If the runtime Freetype library doesn't support LCD mode, we disable
527 // it here.
528 rec->fMaskFormat = SkMask::kA8_Format;
529 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000530
reed@google.com618ef5e2011-01-26 22:10:41 +0000531 SkPaint::Hinting h = rec->getHinting();
532 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
533 // collapse full->normal hinting if we're not doing LCD
534 h = SkPaint::kNormal_Hinting;
535 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
536 SkPaint::kNo_Hinting != h) {
537 // to do subpixel, we must have at most slight hinting
538 h = SkPaint::kSlight_Hinting;
539 }
540 rec->setHinting(h);
541}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000542
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000543#ifdef ANDROID
544uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
545 SkAutoMutexAcquire ac(gFTMutex);
546 SkFaceRec *rec = ref_ft_face(fontID);
547 uint16_t unitsPerEm = 0;
548
549 if (rec != NULL && rec->fFace != NULL) {
550 unitsPerEm = rec->fFace->units_per_EM;
551 unref_ft_face(rec->fFace);
552 }
553
554 return (uint32_t)unitsPerEm;
555}
556#endif
557
reed@android.com8a1c16f2008-12-17 15:59:43 +0000558SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000559 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000560 SkAutoMutexAcquire ac(gFTMutex);
561
reed@android.com8a1c16f2008-12-17 15:59:43 +0000562 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000563 if (!InitFreetype()) {
564 sk_throw();
565 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000566 }
567 ++gFTCount;
568
569 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000570 fFTSize = NULL;
571 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000572 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000573 if (NULL == fFaceRec) {
574 return;
575 }
576 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000577
578 // compute our factors from the record
579
580 SkMatrix m;
581
582 fRec.getSingleMatrix(&m);
583
584#ifdef DUMP_STRIKE_CREATION
585 SkString keyString;
586 SkFontHost::GetDescriptorKeyString(desc, &keyString);
587 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
588 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
589 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
590 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000591 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000592#endif
593
594 // now compute our scale factors
595 SkScalar sx = m.getScaleX();
596 SkScalar sy = m.getScaleY();
597
598 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
599 // sort of give up on hinting
600 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
601 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
602 sx = sy = SkScalarAve(sx, sy);
603
604 SkScalar inv = SkScalarInvert(sx);
605
606 // flip the skew elements to go from our Y-down system to FreeType's
607 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
608 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
609 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
610 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
611 } else {
612 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
613 fMatrix22.xy = fMatrix22.yx = 0;
614 }
615
616 fScaleX = SkScalarToFixed(sx);
617 fScaleY = SkScalarToFixed(sy);
618
619 // compute the flags we send to Load_Glyph
620 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000621 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000622
agl@chromium.org70a303f2010-05-10 14:15:50 +0000623 if (SkMask::kBW_Format == fRec.fMaskFormat) {
624 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
625 loadFlags = FT_LOAD_TARGET_MONO;
626 if (fRec.getHinting() == SkPaint::kNo_Hinting)
627 loadFlags = FT_LOAD_NO_HINTING;
628 } else {
629 switch (fRec.getHinting()) {
630 case SkPaint::kNo_Hinting:
631 loadFlags = FT_LOAD_NO_HINTING;
632 break;
633 case SkPaint::kSlight_Hinting:
634 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
635 break;
636 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000637 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
638 loadFlags = FT_LOAD_FORCE_AUTOHINT;
639 else
640 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000641 break;
642 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000643 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
644 loadFlags = FT_LOAD_FORCE_AUTOHINT;
645 break;
646 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000647 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comea2333d2011-03-14 16:44:56 +0000648 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat ||
649 SkMask::kLCD16_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000650 loadFlags = FT_LOAD_TARGET_LCD;
reed@google.comea2333d2011-03-14 16:44:56 +0000651 } else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000652 loadFlags = FT_LOAD_TARGET_LCD_V;
reed@google.comea2333d2011-03-14 16:44:56 +0000653 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000654 break;
655 default:
656 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
657 break;
658 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000659 }
660
agl@chromium.org99e1b902010-01-05 01:19:44 +0000661 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000662 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000663
reed@android.come4d0bc02009-07-24 19:53:20 +0000664 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000665 }
666
667 // now create the FT_Size
668
669 {
670 FT_Error err;
671
672 err = FT_New_Size(fFace, &fFTSize);
673 if (err != 0) {
674 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
675 fFaceRec->fFontID, fScaleX, fScaleY, err));
676 fFace = NULL;
677 return;
678 }
679
680 err = FT_Activate_Size(fFTSize);
681 if (err != 0) {
682 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
683 fFaceRec->fFontID, fScaleX, fScaleY, err));
684 fFTSize = NULL;
685 }
686
687 err = FT_Set_Char_Size( fFace,
688 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
689 72, 72);
690 if (err != 0) {
691 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
692 fFaceRec->fFontID, fScaleX, fScaleY, err));
693 fFace = NULL;
694 return;
695 }
696
697 FT_Set_Transform( fFace, &fMatrix22, NULL);
698 }
699}
700
701SkScalerContext_FreeType::~SkScalerContext_FreeType() {
702 if (fFTSize != NULL) {
703 FT_Done_Size(fFTSize);
704 }
705
706 SkAutoMutexAcquire ac(gFTMutex);
707
708 if (fFace != NULL) {
709 unref_ft_face(fFace);
710 }
711 if (--gFTCount == 0) {
712// SkDEBUGF(("FT_Done_FreeType\n"));
713 FT_Done_FreeType(gFTLibrary);
714 SkDEBUGCODE(gFTLibrary = NULL;)
715 }
716}
717
718/* We call this before each use of the fFace, since we may be sharing
719 this face with other context (at different sizes).
720*/
721FT_Error SkScalerContext_FreeType::setupSize() {
722 /* In the off-chance that a font has been removed, we want to error out
723 right away, so call resolve just to be sure.
724
725 TODO: perhaps we can skip this, by walking the global font cache and
726 killing all of the contexts when we know that a given fontID is going
727 away...
728 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000729 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000730 return (FT_Error)-1;
731 }
732
733 FT_Error err = FT_Activate_Size(fFTSize);
734
735 if (err != 0) {
736 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
737 fFaceRec->fFontID, fScaleX, fScaleY, err));
738 fFTSize = NULL;
739 } else {
740 // seems we need to reset this every time (not sure why, but without it
741 // I get random italics from some other fFTSize)
742 FT_Set_Transform( fFace, &fMatrix22, NULL);
743 }
744 return err;
745}
746
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000747void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
748 FT_Pos strength;
749 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
750 / 24;
751 FT_Outline_Embolden(outline, strength);
752}
753
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000754unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000755 return fFace->num_glyphs;
756}
757
758uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
759 return SkToU16(FT_Get_Char_Index( fFace, uni ));
760}
761
reed@android.com9d3a9852010-01-08 14:07:42 +0000762SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
763 // iterate through each cmap entry, looking for matching glyph indices
764 FT_UInt glyphIndex;
765 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
766
767 while (glyphIndex != 0) {
768 if (glyphIndex == glyph) {
769 return charCode;
770 }
771 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
772 }
773
774 return 0;
775}
776
reed@android.com8a1c16f2008-12-17 15:59:43 +0000777static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
778 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000779 case SkMask::kHorizontalLCD_Format:
780 case SkMask::kVerticalLCD_Format:
781 SkASSERT(!"An LCD format should never be passed here");
782 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000783 case SkMask::kBW_Format:
784 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000785 case SkMask::kA8_Format:
786 default:
787 return FT_PIXEL_MODE_GRAY;
788 }
789}
790
reed@android.com8a1c16f2008-12-17 15:59:43 +0000791void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
792#ifdef FT_ADVANCES_H
793 /* unhinted and light hinted text have linearly scaled advances
794 * which are very cheap to compute with some font formats...
795 */
796 {
797 SkAutoMutexAcquire ac(gFTMutex);
798
799 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000800 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000801 return;
802 }
803
804 FT_Error error;
805 FT_Fixed advance;
806
807 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
808 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
809 &advance );
810 if (0 == error) {
811 glyph->fRsbDelta = 0;
812 glyph->fLsbDelta = 0;
813 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
814 glyph->fAdvanceY = 0;
815 return;
816 }
817 }
818#endif /* FT_ADVANCES_H */
819 /* otherwise, we need to load/hint the glyph, which is slower */
820 this->generateMetrics(glyph);
821 return;
822}
823
824void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
825 SkAutoMutexAcquire ac(gFTMutex);
826
827 glyph->fRsbDelta = 0;
828 glyph->fLsbDelta = 0;
829
830 FT_Error err;
831
832 if (this->setupSize()) {
833 goto ERROR;
834 }
835
836 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
837 if (err != 0) {
838 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
839 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
840 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000841 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000842 return;
843 }
844
845 switch ( fFace->glyph->format ) {
846 case FT_GLYPH_FORMAT_OUTLINE:
847 FT_BBox bbox;
848
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000849 if (fRec.fFlags & kEmbolden_Flag) {
850 emboldenOutline(&fFace->glyph->outline);
851 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000852 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
853
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000854 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000855 int dx = glyph->getSubXFixed() >> 10;
856 int dy = glyph->getSubYFixed() >> 10;
857 // negate dy since freetype-y-goes-up and skia-y-goes-down
858 bbox.xMin += dx;
859 bbox.yMin -= dy;
860 bbox.xMax += dx;
861 bbox.yMax -= dy;
862 }
863
864 bbox.xMin &= ~63;
865 bbox.yMin &= ~63;
866 bbox.xMax = (bbox.xMax + 63) & ~63;
867 bbox.yMax = (bbox.yMax + 63) & ~63;
868
869 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
870 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
871 glyph->fTop = -SkToS16(bbox.yMax >> 6);
872 glyph->fLeft = SkToS16(bbox.xMin >> 6);
873 break;
874
875 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000876 if (fRec.fFlags & kEmbolden_Flag) {
877 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
878 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
879 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000880 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
881 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
882 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
883 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
884 break;
885
886 default:
887 SkASSERT(!"unknown glyph format");
888 goto ERROR;
889 }
890
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000891 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000892 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
893 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
894 if (fRec.fFlags & kDevKernText_Flag) {
895 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
896 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
897 }
898 } else {
899 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
900 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
901 }
902
903#ifdef ENABLE_GLYPH_SPEW
904 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
905 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
906#endif
907}
908
reed@android.comf5493692009-07-22 19:21:01 +0000909#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000910namespace skia_freetype_support {
911// extern functions from SkFontHost_FreeType_Subpixel
912extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
913extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
914}
915
916using namespace skia_freetype_support;
917#endif
918
reed@google.comea2333d2011-03-14 16:44:56 +0000919static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap) {
reed@google.com260db922011-03-14 18:09:32 +0000920 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
reed@google.comea2333d2011-03-14 16:44:56 +0000921 SkASSERT(glyph.fHeight == bitmap.rows);
922
reed@google.com260db922011-03-14 18:09:32 +0000923 const uint8_t* src = bitmap.buffer + 3;
reed@google.comea2333d2011-03-14 16:44:56 +0000924 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
925 size_t dstRB = glyph.rowBytes();
926 int width = glyph.fWidth;
927
928 for (int y = 0; y < glyph.fHeight; y++) {
929 const uint8_t* triple = src;
930 for (int x = 0; x < width; x++) {
931 dst[x] = SkPackRGB16(triple[0] >> 3, triple[1] >> 2, triple[2] >> 3);
932 triple += 3;
933 }
934 src += bitmap.pitch;
935 dst = (uint16_t*)((char*)dst + dstRB);
936 }
937}
938
reed@android.com8a1c16f2008-12-17 15:59:43 +0000939void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
940 SkAutoMutexAcquire ac(gFTMutex);
941
942 FT_Error err;
943
944 if (this->setupSize()) {
945 goto ERROR;
946 }
947
948 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
949 if (err != 0) {
950 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
951 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
952 ERROR:
953 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
954 return;
955 }
956
agl@chromium.org309485b2009-07-21 17:41:32 +0000957 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
958 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
959
reed@android.com8a1c16f2008-12-17 15:59:43 +0000960 switch ( fFace->glyph->format ) {
961 case FT_GLYPH_FORMAT_OUTLINE: {
962 FT_Outline* outline = &fFace->glyph->outline;
963 FT_BBox bbox;
964 FT_Bitmap target;
965
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000966 if (fRec.fFlags & kEmbolden_Flag) {
967 emboldenOutline(outline);
968 }
969
reed@android.com8a1c16f2008-12-17 15:59:43 +0000970 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000971 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000972 dx = glyph.getSubXFixed() >> 10;
973 dy = glyph.getSubYFixed() >> 10;
974 // negate dy since freetype-y-goes-up and skia-y-goes-down
975 dy = -dy;
976 }
977 FT_Outline_Get_CBox(outline, &bbox);
978 /*
979 what we really want to do for subpixel is
980 offset(dx, dy)
981 compute_bounds
982 offset(bbox & !63)
983 but that is two calls to offset, so we do the following, which
984 achieves the same thing with only one offset call.
985 */
986 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
987 dy - ((bbox.yMin + dy) & ~63));
988
reed@android.comf5493692009-07-22 19:21:01 +0000989#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000990 if (lcdRenderMode) {
991 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
992 // we have to call FT_Render_Glyph and memcpy the image out.
993 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
994 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
995 FT_Render_Glyph(fFace->glyph, mode);
996
997 if (isVertical)
998 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
999 else
1000 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
1001
1002 break;
1003 }
1004#endif
1005
reed@google.comea2333d2011-03-14 16:44:56 +00001006 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1007 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
1008 copyFT2LCD16(glyph, fFace->glyph->bitmap);
1009 } else {
1010 target.width = glyph.fWidth;
1011 target.rows = glyph.fHeight;
1012 target.pitch = glyph.rowBytes();
1013 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1014 target.pixel_mode = compute_pixel_mode(
1015 (SkMask::Format)fRec.fMaskFormat);
1016 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001017
reed@google.comea2333d2011-03-14 16:44:56 +00001018 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1019 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1020 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001021 } break;
1022
1023 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001024 if (fRec.fFlags & kEmbolden_Flag) {
1025 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1026 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1027 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001028 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1029 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1030 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1031 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1032
1033 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1034 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001035
agl@chromium.org558434a2009-08-11 17:22:38 +00001036 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1037 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1038 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001039 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1040 unsigned dstRowBytes = glyph.rowBytes();
1041 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1042 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1043
1044 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1045 memcpy(dst, src, minRowBytes);
1046 memset(dst + minRowBytes, 0, extraRowBytes);
1047 src += srcRowBytes;
1048 dst += dstRowBytes;
1049 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001050 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001051 (glyph.fMaskFormat == SkMask::kA8_Format ||
1052 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1053 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001054 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1055 uint8_t byte = 0;
1056 int bits = 0;
1057 const uint8_t* src_row = src;
1058 uint8_t* dst_row = dst;
1059
1060 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1061 if (!bits) {
1062 byte = *src_row++;
1063 bits = 8;
1064 }
1065
1066 *dst_row++ = byte & 0x80 ? 0xff : 0;
1067 bits--;
1068 byte <<= 1;
1069 }
1070
1071 src += fFace->glyph->bitmap.pitch;
1072 dst += glyph.rowBytes();
1073 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001074 } else {
1075 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001076 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001077
1078 if (lcdRenderMode)
1079 glyph.expandA8ToLCD();
1080
reed@android.com8a1c16f2008-12-17 15:59:43 +00001081 } break;
1082
1083 default:
1084 SkASSERT(!"unknown glyph format");
1085 goto ERROR;
1086 }
1087}
1088
1089///////////////////////////////////////////////////////////////////////////////
1090
1091#define ft2sk(x) SkFixedToScalar((x) << 10)
1092
reed@android.com6f252972009-01-14 16:46:16 +00001093#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001094 #define CONST_PARAM const
1095#else // older freetype doesn't use const here
1096 #define CONST_PARAM
1097#endif
1098
1099static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1100 SkPath* path = (SkPath*)ctx;
1101 path->close(); // to close the previous contour (if any)
1102 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1103 return 0;
1104}
1105
1106static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1107 SkPath* path = (SkPath*)ctx;
1108 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1109 return 0;
1110}
1111
1112static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1113 void* ctx) {
1114 SkPath* path = (SkPath*)ctx;
1115 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1116 return 0;
1117}
1118
1119static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1120 CONST_PARAM FT_Vector* pt2, void* ctx) {
1121 SkPath* path = (SkPath*)ctx;
1122 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1123 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1124 return 0;
1125}
1126
1127void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1128 SkPath* path) {
1129 SkAutoMutexAcquire ac(gFTMutex);
1130
1131 SkASSERT(&glyph && path);
1132
1133 if (this->setupSize()) {
1134 path->reset();
1135 return;
1136 }
1137
1138 uint32_t flags = fLoadGlyphFlags;
1139 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1140 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1141
1142 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1143
1144 if (err != 0) {
1145 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1146 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1147 path->reset();
1148 return;
1149 }
1150
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001151 if (fRec.fFlags & kEmbolden_Flag) {
1152 emboldenOutline(&fFace->glyph->outline);
1153 }
1154
reed@android.com8a1c16f2008-12-17 15:59:43 +00001155 FT_Outline_Funcs funcs;
1156
1157 funcs.move_to = move_proc;
1158 funcs.line_to = line_proc;
1159 funcs.conic_to = quad_proc;
1160 funcs.cubic_to = cubic_proc;
1161 funcs.shift = 0;
1162 funcs.delta = 0;
1163
1164 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1165
1166 if (err != 0) {
1167 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1168 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1169 path->reset();
1170 return;
1171 }
1172
1173 path->close();
1174}
1175
1176void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1177 SkPaint::FontMetrics* my) {
1178 if (NULL == mx && NULL == my) {
1179 return;
1180 }
1181
1182 SkAutoMutexAcquire ac(gFTMutex);
1183
1184 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001185 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001186 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001187 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188 }
1189 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001190 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001191 }
1192 return;
1193 }
1194
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001195 FT_Face face = fFace;
1196 int upem = face->units_per_EM;
1197 if (upem <= 0) {
1198 goto ERROR;
1199 }
1200
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001201 SkPoint pts[6];
1202 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001203 SkFixed scaleY = fScaleY;
1204 SkFixed mxy = fMatrix22.xy;
1205 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001206 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1207 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001208
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001209 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001210 if (leading < 0) {
1211 leading = 0;
1212 }
1213
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001214 // Try to get the OS/2 table from the font. This contains the specific
1215 // average font width metrics which Windows uses.
1216 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1217
reed@android.com8a1c16f2008-12-17 15:59:43 +00001218 ys[0] = -face->bbox.yMax;
1219 ys[1] = -face->ascender;
1220 ys[2] = -face->descender;
1221 ys[3] = -face->bbox.yMin;
1222 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001223 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1224
1225 SkScalar x_height;
1226 if (os2 && os2->sxHeight) {
1227 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1228 } else {
1229 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1230 if (x_glyph) {
1231 FT_BBox bbox;
1232 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001233 if (fRec.fFlags & kEmbolden_Flag) {
1234 emboldenOutline(&fFace->glyph->outline);
1235 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001236 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1237 x_height = SkIntToScalar(bbox.yMax) / 64;
1238 } else {
1239 x_height = 0;
1240 }
1241 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001242
1243 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001244 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001245 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1246 SkFixed x = SkFixedMul(mxy, y);
1247 y = SkFixedMul(myy, y);
1248 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1249 }
1250
1251 if (mx) {
1252 mx->fTop = pts[0].fX;
1253 mx->fAscent = pts[1].fX;
1254 mx->fDescent = pts[2].fX;
1255 mx->fBottom = pts[3].fX;
1256 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001257 mx->fAvgCharWidth = pts[5].fX;
1258 mx->fXMin = xmin;
1259 mx->fXMax = xmax;
1260 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001261 }
1262 if (my) {
1263 my->fTop = pts[0].fY;
1264 my->fAscent = pts[1].fY;
1265 my->fDescent = pts[2].fY;
1266 my->fBottom = pts[3].fY;
1267 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001268 my->fAvgCharWidth = pts[5].fY;
1269 my->fXMin = xmin;
1270 my->fXMax = xmax;
1271 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001272 }
1273}
1274
1275////////////////////////////////////////////////////////////////////////
1276////////////////////////////////////////////////////////////////////////
1277
1278SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001279 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1280 if (!c->success()) {
1281 SkDELETE(c);
1282 c = NULL;
1283 }
1284 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001285}
1286
1287///////////////////////////////////////////////////////////////////////////////
1288
1289/* Export this so that other parts of our FonttHost port can make use of our
1290 ability to extract the name+style from a stream, using FreeType's api.
1291*/
reed@google.com5b31b0f2011-02-23 14:41:42 +00001292SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
1293 bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001294 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001295 if (FT_Init_FreeType(&library)) {
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001296 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001297 return SkTypeface::kNormal;
1298 }
1299
1300 FT_Open_Args args;
1301 memset(&args, 0, sizeof(args));
1302
1303 const void* memoryBase = stream->getMemoryBase();
1304 FT_StreamRec streamRec;
1305
1306 if (NULL != memoryBase) {
1307 args.flags = FT_OPEN_MEMORY;
1308 args.memory_base = (const FT_Byte*)memoryBase;
1309 args.memory_size = stream->getLength();
1310 } else {
1311 memset(&streamRec, 0, sizeof(streamRec));
1312 streamRec.size = stream->read(NULL, 0);
1313 streamRec.descriptor.pointer = stream;
1314 streamRec.read = sk_stream_read;
1315 streamRec.close = sk_stream_close;
1316
1317 args.flags = FT_OPEN_STREAM;
1318 args.stream = &streamRec;
1319 }
1320
1321 FT_Face face;
1322 if (FT_Open_Face(library, &args, 0, &face)) {
1323 FT_Done_FreeType(library);
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001324 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001325 return SkTypeface::kNormal;
1326 }
1327
1328 name->set(face->family_name);
1329 int style = SkTypeface::kNormal;
1330
1331 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1332 style |= SkTypeface::kBold;
1333 }
1334 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1335 style |= SkTypeface::kItalic;
1336 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001337 if (isFixedWidth) {
1338 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1339 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001340
1341 FT_Done_Face(face);
1342 FT_Done_FreeType(library);
1343 return (SkTypeface::Style)style;
1344}