blob: 54977348cdc8a2ca0ff62048b698493028ef52b2 [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) {
reed@google.com8a5d6922011-03-14 15:08:03 +0000348#if defined(SK_BUILD_FOR_MAC)
349 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
reed@android.com8a1c16f2008-12-17 15:59:43 +0000543SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000544 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000545 SkAutoMutexAcquire ac(gFTMutex);
546
reed@android.com8a1c16f2008-12-17 15:59:43 +0000547 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000548 if (!InitFreetype()) {
549 sk_throw();
550 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000551 }
552 ++gFTCount;
553
554 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000555 fFTSize = NULL;
556 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000557 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000558 if (NULL == fFaceRec) {
559 return;
560 }
561 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000562
563 // compute our factors from the record
564
565 SkMatrix m;
566
567 fRec.getSingleMatrix(&m);
568
569#ifdef DUMP_STRIKE_CREATION
570 SkString keyString;
571 SkFontHost::GetDescriptorKeyString(desc, &keyString);
572 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
573 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
574 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
575 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000576 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000577#endif
578
579 // now compute our scale factors
580 SkScalar sx = m.getScaleX();
581 SkScalar sy = m.getScaleY();
582
583 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
584 // sort of give up on hinting
585 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
586 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
587 sx = sy = SkScalarAve(sx, sy);
588
589 SkScalar inv = SkScalarInvert(sx);
590
591 // flip the skew elements to go from our Y-down system to FreeType's
592 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
593 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
594 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
595 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
596 } else {
597 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
598 fMatrix22.xy = fMatrix22.yx = 0;
599 }
600
601 fScaleX = SkScalarToFixed(sx);
602 fScaleY = SkScalarToFixed(sy);
603
604 // compute the flags we send to Load_Glyph
605 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000606 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000607
agl@chromium.org70a303f2010-05-10 14:15:50 +0000608 if (SkMask::kBW_Format == fRec.fMaskFormat) {
609 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
610 loadFlags = FT_LOAD_TARGET_MONO;
611 if (fRec.getHinting() == SkPaint::kNo_Hinting)
612 loadFlags = FT_LOAD_NO_HINTING;
613 } else {
614 switch (fRec.getHinting()) {
615 case SkPaint::kNo_Hinting:
616 loadFlags = FT_LOAD_NO_HINTING;
617 break;
618 case SkPaint::kSlight_Hinting:
619 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
620 break;
621 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000622 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
623 loadFlags = FT_LOAD_FORCE_AUTOHINT;
624 else
625 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000626 break;
627 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000628 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
629 loadFlags = FT_LOAD_FORCE_AUTOHINT;
630 break;
631 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000632 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comea2333d2011-03-14 16:44:56 +0000633 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat ||
634 SkMask::kLCD16_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000635 loadFlags = FT_LOAD_TARGET_LCD;
reed@google.comea2333d2011-03-14 16:44:56 +0000636 } else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000637 loadFlags = FT_LOAD_TARGET_LCD_V;
reed@google.comea2333d2011-03-14 16:44:56 +0000638 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000639 break;
640 default:
641 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
642 break;
643 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000644 }
645
agl@chromium.org99e1b902010-01-05 01:19:44 +0000646 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000647 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000648
reed@android.come4d0bc02009-07-24 19:53:20 +0000649 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000650 }
651
652 // now create the FT_Size
653
654 {
655 FT_Error err;
656
657 err = FT_New_Size(fFace, &fFTSize);
658 if (err != 0) {
659 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
660 fFaceRec->fFontID, fScaleX, fScaleY, err));
661 fFace = NULL;
662 return;
663 }
664
665 err = FT_Activate_Size(fFTSize);
666 if (err != 0) {
667 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
668 fFaceRec->fFontID, fScaleX, fScaleY, err));
669 fFTSize = NULL;
670 }
671
672 err = FT_Set_Char_Size( fFace,
673 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
674 72, 72);
675 if (err != 0) {
676 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
677 fFaceRec->fFontID, fScaleX, fScaleY, err));
678 fFace = NULL;
679 return;
680 }
681
682 FT_Set_Transform( fFace, &fMatrix22, NULL);
683 }
684}
685
686SkScalerContext_FreeType::~SkScalerContext_FreeType() {
687 if (fFTSize != NULL) {
688 FT_Done_Size(fFTSize);
689 }
690
691 SkAutoMutexAcquire ac(gFTMutex);
692
693 if (fFace != NULL) {
694 unref_ft_face(fFace);
695 }
696 if (--gFTCount == 0) {
697// SkDEBUGF(("FT_Done_FreeType\n"));
698 FT_Done_FreeType(gFTLibrary);
699 SkDEBUGCODE(gFTLibrary = NULL;)
700 }
701}
702
703/* We call this before each use of the fFace, since we may be sharing
704 this face with other context (at different sizes).
705*/
706FT_Error SkScalerContext_FreeType::setupSize() {
707 /* In the off-chance that a font has been removed, we want to error out
708 right away, so call resolve just to be sure.
709
710 TODO: perhaps we can skip this, by walking the global font cache and
711 killing all of the contexts when we know that a given fontID is going
712 away...
713 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000714 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000715 return (FT_Error)-1;
716 }
717
718 FT_Error err = FT_Activate_Size(fFTSize);
719
720 if (err != 0) {
721 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
722 fFaceRec->fFontID, fScaleX, fScaleY, err));
723 fFTSize = NULL;
724 } else {
725 // seems we need to reset this every time (not sure why, but without it
726 // I get random italics from some other fFTSize)
727 FT_Set_Transform( fFace, &fMatrix22, NULL);
728 }
729 return err;
730}
731
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000732void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
733 FT_Pos strength;
734 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
735 / 24;
736 FT_Outline_Embolden(outline, strength);
737}
738
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000739unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000740 return fFace->num_glyphs;
741}
742
743uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
744 return SkToU16(FT_Get_Char_Index( fFace, uni ));
745}
746
reed@android.com9d3a9852010-01-08 14:07:42 +0000747SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
748 // iterate through each cmap entry, looking for matching glyph indices
749 FT_UInt glyphIndex;
750 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
751
752 while (glyphIndex != 0) {
753 if (glyphIndex == glyph) {
754 return charCode;
755 }
756 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
757 }
758
759 return 0;
760}
761
reed@android.com8a1c16f2008-12-17 15:59:43 +0000762static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
763 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000764 case SkMask::kHorizontalLCD_Format:
765 case SkMask::kVerticalLCD_Format:
766 SkASSERT(!"An LCD format should never be passed here");
767 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000768 case SkMask::kBW_Format:
769 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000770 case SkMask::kA8_Format:
771 default:
772 return FT_PIXEL_MODE_GRAY;
773 }
774}
775
reed@android.com8a1c16f2008-12-17 15:59:43 +0000776void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
777#ifdef FT_ADVANCES_H
778 /* unhinted and light hinted text have linearly scaled advances
779 * which are very cheap to compute with some font formats...
780 */
781 {
782 SkAutoMutexAcquire ac(gFTMutex);
783
784 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000785 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000786 return;
787 }
788
789 FT_Error error;
790 FT_Fixed advance;
791
792 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
793 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
794 &advance );
795 if (0 == error) {
796 glyph->fRsbDelta = 0;
797 glyph->fLsbDelta = 0;
798 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
799 glyph->fAdvanceY = 0;
800 return;
801 }
802 }
803#endif /* FT_ADVANCES_H */
804 /* otherwise, we need to load/hint the glyph, which is slower */
805 this->generateMetrics(glyph);
806 return;
807}
808
809void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
810 SkAutoMutexAcquire ac(gFTMutex);
811
812 glyph->fRsbDelta = 0;
813 glyph->fLsbDelta = 0;
814
815 FT_Error err;
816
817 if (this->setupSize()) {
818 goto ERROR;
819 }
820
821 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
822 if (err != 0) {
823 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
824 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
825 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000826 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000827 return;
828 }
829
830 switch ( fFace->glyph->format ) {
831 case FT_GLYPH_FORMAT_OUTLINE:
832 FT_BBox bbox;
833
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000834 if (fRec.fFlags & kEmbolden_Flag) {
835 emboldenOutline(&fFace->glyph->outline);
836 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
838
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000839 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000840 int dx = glyph->getSubXFixed() >> 10;
841 int dy = glyph->getSubYFixed() >> 10;
842 // negate dy since freetype-y-goes-up and skia-y-goes-down
843 bbox.xMin += dx;
844 bbox.yMin -= dy;
845 bbox.xMax += dx;
846 bbox.yMax -= dy;
847 }
848
849 bbox.xMin &= ~63;
850 bbox.yMin &= ~63;
851 bbox.xMax = (bbox.xMax + 63) & ~63;
852 bbox.yMax = (bbox.yMax + 63) & ~63;
853
854 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
855 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
856 glyph->fTop = -SkToS16(bbox.yMax >> 6);
857 glyph->fLeft = SkToS16(bbox.xMin >> 6);
858 break;
859
860 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000861 if (fRec.fFlags & kEmbolden_Flag) {
862 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
863 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
864 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000865 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
866 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
867 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
868 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
869 break;
870
871 default:
872 SkASSERT(!"unknown glyph format");
873 goto ERROR;
874 }
875
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000876 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000877 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
878 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
879 if (fRec.fFlags & kDevKernText_Flag) {
880 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
881 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
882 }
883 } else {
884 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
885 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
886 }
887
888#ifdef ENABLE_GLYPH_SPEW
889 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
890 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
891#endif
892}
893
reed@android.comf5493692009-07-22 19:21:01 +0000894#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000895namespace skia_freetype_support {
896// extern functions from SkFontHost_FreeType_Subpixel
897extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
898extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
899}
900
901using namespace skia_freetype_support;
902#endif
903
reed@google.comea2333d2011-03-14 16:44:56 +0000904static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap) {
reed@google.com260db922011-03-14 18:09:32 +0000905 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
reed@google.comea2333d2011-03-14 16:44:56 +0000906 SkASSERT(glyph.fHeight == bitmap.rows);
907
reed@google.com260db922011-03-14 18:09:32 +0000908 const uint8_t* src = bitmap.buffer + 3;
reed@google.comea2333d2011-03-14 16:44:56 +0000909 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
910 size_t dstRB = glyph.rowBytes();
911 int width = glyph.fWidth;
912
913 for (int y = 0; y < glyph.fHeight; y++) {
914 const uint8_t* triple = src;
915 for (int x = 0; x < width; x++) {
916 dst[x] = SkPackRGB16(triple[0] >> 3, triple[1] >> 2, triple[2] >> 3);
917 triple += 3;
918 }
919 src += bitmap.pitch;
920 dst = (uint16_t*)((char*)dst + dstRB);
921 }
922}
923
reed@android.com8a1c16f2008-12-17 15:59:43 +0000924void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
925 SkAutoMutexAcquire ac(gFTMutex);
926
927 FT_Error err;
928
929 if (this->setupSize()) {
930 goto ERROR;
931 }
932
933 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
934 if (err != 0) {
935 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
936 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
937 ERROR:
938 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
939 return;
940 }
941
agl@chromium.org309485b2009-07-21 17:41:32 +0000942 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
943 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
944
reed@android.com8a1c16f2008-12-17 15:59:43 +0000945 switch ( fFace->glyph->format ) {
946 case FT_GLYPH_FORMAT_OUTLINE: {
947 FT_Outline* outline = &fFace->glyph->outline;
948 FT_BBox bbox;
949 FT_Bitmap target;
950
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000951 if (fRec.fFlags & kEmbolden_Flag) {
952 emboldenOutline(outline);
953 }
954
reed@android.com8a1c16f2008-12-17 15:59:43 +0000955 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000956 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000957 dx = glyph.getSubXFixed() >> 10;
958 dy = glyph.getSubYFixed() >> 10;
959 // negate dy since freetype-y-goes-up and skia-y-goes-down
960 dy = -dy;
961 }
962 FT_Outline_Get_CBox(outline, &bbox);
963 /*
964 what we really want to do for subpixel is
965 offset(dx, dy)
966 compute_bounds
967 offset(bbox & !63)
968 but that is two calls to offset, so we do the following, which
969 achieves the same thing with only one offset call.
970 */
971 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
972 dy - ((bbox.yMin + dy) & ~63));
973
reed@android.comf5493692009-07-22 19:21:01 +0000974#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000975 if (lcdRenderMode) {
976 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
977 // we have to call FT_Render_Glyph and memcpy the image out.
978 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
979 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
980 FT_Render_Glyph(fFace->glyph, mode);
981
982 if (isVertical)
983 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
984 else
985 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
986
987 break;
988 }
989#endif
990
reed@google.comea2333d2011-03-14 16:44:56 +0000991 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
992 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
993 copyFT2LCD16(glyph, fFace->glyph->bitmap);
994 } else {
995 target.width = glyph.fWidth;
996 target.rows = glyph.fHeight;
997 target.pitch = glyph.rowBytes();
998 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
999 target.pixel_mode = compute_pixel_mode(
1000 (SkMask::Format)fRec.fMaskFormat);
1001 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001002
reed@google.comea2333d2011-03-14 16:44:56 +00001003 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1004 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1005 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001006 } break;
1007
1008 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001009 if (fRec.fFlags & kEmbolden_Flag) {
1010 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1011 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1012 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001013 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1014 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1015 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1016 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1017
1018 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1019 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001020
agl@chromium.org558434a2009-08-11 17:22:38 +00001021 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1022 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1023 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001024 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1025 unsigned dstRowBytes = glyph.rowBytes();
1026 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1027 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1028
1029 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1030 memcpy(dst, src, minRowBytes);
1031 memset(dst + minRowBytes, 0, extraRowBytes);
1032 src += srcRowBytes;
1033 dst += dstRowBytes;
1034 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001035 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001036 (glyph.fMaskFormat == SkMask::kA8_Format ||
1037 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1038 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001039 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1040 uint8_t byte = 0;
1041 int bits = 0;
1042 const uint8_t* src_row = src;
1043 uint8_t* dst_row = dst;
1044
1045 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1046 if (!bits) {
1047 byte = *src_row++;
1048 bits = 8;
1049 }
1050
1051 *dst_row++ = byte & 0x80 ? 0xff : 0;
1052 bits--;
1053 byte <<= 1;
1054 }
1055
1056 src += fFace->glyph->bitmap.pitch;
1057 dst += glyph.rowBytes();
1058 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001059 } else {
1060 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001061 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001062
1063 if (lcdRenderMode)
1064 glyph.expandA8ToLCD();
1065
reed@android.com8a1c16f2008-12-17 15:59:43 +00001066 } break;
1067
1068 default:
1069 SkASSERT(!"unknown glyph format");
1070 goto ERROR;
1071 }
1072}
1073
1074///////////////////////////////////////////////////////////////////////////////
1075
1076#define ft2sk(x) SkFixedToScalar((x) << 10)
1077
reed@android.com6f252972009-01-14 16:46:16 +00001078#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001079 #define CONST_PARAM const
1080#else // older freetype doesn't use const here
1081 #define CONST_PARAM
1082#endif
1083
1084static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1085 SkPath* path = (SkPath*)ctx;
1086 path->close(); // to close the previous contour (if any)
1087 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1088 return 0;
1089}
1090
1091static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1092 SkPath* path = (SkPath*)ctx;
1093 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1094 return 0;
1095}
1096
1097static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1098 void* ctx) {
1099 SkPath* path = (SkPath*)ctx;
1100 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1101 return 0;
1102}
1103
1104static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1105 CONST_PARAM FT_Vector* pt2, void* ctx) {
1106 SkPath* path = (SkPath*)ctx;
1107 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1108 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1109 return 0;
1110}
1111
1112void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1113 SkPath* path) {
1114 SkAutoMutexAcquire ac(gFTMutex);
1115
1116 SkASSERT(&glyph && path);
1117
1118 if (this->setupSize()) {
1119 path->reset();
1120 return;
1121 }
1122
1123 uint32_t flags = fLoadGlyphFlags;
1124 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1125 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1126
1127 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1128
1129 if (err != 0) {
1130 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1131 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1132 path->reset();
1133 return;
1134 }
1135
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001136 if (fRec.fFlags & kEmbolden_Flag) {
1137 emboldenOutline(&fFace->glyph->outline);
1138 }
1139
reed@android.com8a1c16f2008-12-17 15:59:43 +00001140 FT_Outline_Funcs funcs;
1141
1142 funcs.move_to = move_proc;
1143 funcs.line_to = line_proc;
1144 funcs.conic_to = quad_proc;
1145 funcs.cubic_to = cubic_proc;
1146 funcs.shift = 0;
1147 funcs.delta = 0;
1148
1149 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1150
1151 if (err != 0) {
1152 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1153 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1154 path->reset();
1155 return;
1156 }
1157
1158 path->close();
1159}
1160
1161void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1162 SkPaint::FontMetrics* my) {
1163 if (NULL == mx && NULL == my) {
1164 return;
1165 }
1166
1167 SkAutoMutexAcquire ac(gFTMutex);
1168
1169 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001170 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001171 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001172 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001173 }
1174 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001175 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001176 }
1177 return;
1178 }
1179
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001180 FT_Face face = fFace;
1181 int upem = face->units_per_EM;
1182 if (upem <= 0) {
1183 goto ERROR;
1184 }
1185
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001186 SkPoint pts[6];
1187 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001188 SkFixed scaleY = fScaleY;
1189 SkFixed mxy = fMatrix22.xy;
1190 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001191 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1192 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001194 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001195 if (leading < 0) {
1196 leading = 0;
1197 }
1198
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001199 // Try to get the OS/2 table from the font. This contains the specific
1200 // average font width metrics which Windows uses.
1201 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1202
reed@android.com8a1c16f2008-12-17 15:59:43 +00001203 ys[0] = -face->bbox.yMax;
1204 ys[1] = -face->ascender;
1205 ys[2] = -face->descender;
1206 ys[3] = -face->bbox.yMin;
1207 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001208 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1209
1210 SkScalar x_height;
1211 if (os2 && os2->sxHeight) {
1212 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1213 } else {
1214 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1215 if (x_glyph) {
1216 FT_BBox bbox;
1217 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001218 if (fRec.fFlags & kEmbolden_Flag) {
1219 emboldenOutline(&fFace->glyph->outline);
1220 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001221 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1222 x_height = SkIntToScalar(bbox.yMax) / 64;
1223 } else {
1224 x_height = 0;
1225 }
1226 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001227
1228 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001229 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001230 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1231 SkFixed x = SkFixedMul(mxy, y);
1232 y = SkFixedMul(myy, y);
1233 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1234 }
1235
1236 if (mx) {
1237 mx->fTop = pts[0].fX;
1238 mx->fAscent = pts[1].fX;
1239 mx->fDescent = pts[2].fX;
1240 mx->fBottom = pts[3].fX;
1241 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001242 mx->fAvgCharWidth = pts[5].fX;
1243 mx->fXMin = xmin;
1244 mx->fXMax = xmax;
1245 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001246 }
1247 if (my) {
1248 my->fTop = pts[0].fY;
1249 my->fAscent = pts[1].fY;
1250 my->fDescent = pts[2].fY;
1251 my->fBottom = pts[3].fY;
1252 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001253 my->fAvgCharWidth = pts[5].fY;
1254 my->fXMin = xmin;
1255 my->fXMax = xmax;
1256 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001257 }
1258}
1259
1260////////////////////////////////////////////////////////////////////////
1261////////////////////////////////////////////////////////////////////////
1262
1263SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001264 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1265 if (!c->success()) {
1266 SkDELETE(c);
1267 c = NULL;
1268 }
1269 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001270}
1271
1272///////////////////////////////////////////////////////////////////////////////
1273
1274/* Export this so that other parts of our FonttHost port can make use of our
1275 ability to extract the name+style from a stream, using FreeType's api.
1276*/
reed@google.com5b31b0f2011-02-23 14:41:42 +00001277SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
1278 bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001279 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001280 if (FT_Init_FreeType(&library)) {
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001281 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001282 return SkTypeface::kNormal;
1283 }
1284
1285 FT_Open_Args args;
1286 memset(&args, 0, sizeof(args));
1287
1288 const void* memoryBase = stream->getMemoryBase();
1289 FT_StreamRec streamRec;
1290
1291 if (NULL != memoryBase) {
1292 args.flags = FT_OPEN_MEMORY;
1293 args.memory_base = (const FT_Byte*)memoryBase;
1294 args.memory_size = stream->getLength();
1295 } else {
1296 memset(&streamRec, 0, sizeof(streamRec));
1297 streamRec.size = stream->read(NULL, 0);
1298 streamRec.descriptor.pointer = stream;
1299 streamRec.read = sk_stream_read;
1300 streamRec.close = sk_stream_close;
1301
1302 args.flags = FT_OPEN_STREAM;
1303 args.stream = &streamRec;
1304 }
1305
1306 FT_Face face;
1307 if (FT_Open_Face(library, &args, 0, &face)) {
1308 FT_Done_FreeType(library);
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001309 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001310 return SkTypeface::kNormal;
1311 }
1312
1313 name->set(face->family_name);
1314 int style = SkTypeface::kNormal;
1315
1316 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1317 style |= SkTypeface::kBold;
1318 }
1319 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1320 style |= SkTypeface::kItalic;
1321 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001322 if (isFixedWidth) {
1323 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1324 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001325
1326 FT_Done_Face(face);
1327 FT_Done_FreeType(library);
1328 return (SkTypeface::Style)style;
1329}