blob: e058a362bb16bc1ee1bf39671a877fad57c10b19 [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(
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000347 uint32_t fontID,
348 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo) {
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000349#if defined(SK_BUILD_FOR_MAC) || defined(ANDROID)
reed@google.com8a5d6922011-03-14 15:08:03 +0000350 return NULL;
351#else
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000352 SkAutoMutexAcquire ac(gFTMutex);
353 FT_Library libInit = NULL;
354 if (gFTCount == 0) {
355 if (!InitFreetype())
356 sk_throw();
357 libInit = gFTLibrary;
358 }
359 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
360 SkFaceRec* rec = ref_ft_face(fontID);
361 if (NULL == rec)
362 return NULL;
363 FT_Face face = rec->fFace;
364
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000365 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
366 info->fFontName.set(FT_Get_Postscript_Name(face));
367 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
368 info->fLastGlyphID = face->num_glyphs - 1;
369 info->fEmSize = 1000;
370
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000371 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000372 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000373 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000374 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000375 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000376 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000377 cid = true;
378 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000379 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000380 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000381 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000382 cid = true;
383 TT_Header* ttHeader;
384 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
385 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000386 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000387 }
388 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000389
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000390 info->fStyle = 0;
391 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000392 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000393 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000394 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000395 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
396 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000397 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
398
399 PS_FontInfoRec ps_info;
400 TT_Postscript* tt_info;
401 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
402 info->fItalicAngle = ps_info.italic_angle;
403 } else if ((tt_info =
404 (TT_Postscript*)FT_Get_Sfnt_Table(face,
405 ft_sfnt_post)) != NULL) {
406 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
407 } else {
408 info->fItalicAngle = 0;
409 }
410
411 info->fAscent = face->ascender;
412 info->fDescent = face->descender;
413
414 // Figure out a good guess for StemV - Min width of i, I, !, 1.
415 // This probably isn't very good with an italic font.
416 int16_t min_width = SHRT_MAX;
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000417 info->fStemV = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000418 char stem_chars[] = {'i', 'I', '!', '1'};
419 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
420 FT_BBox bbox;
421 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
422 int16_t width = bbox.xMax - bbox.xMin;
423 if (width > 0 && width < min_width) {
424 min_width = width;
425 info->fStemV = min_width;
426 }
427 }
428 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000429
430 TT_PCLT* pclt_info;
431 TT_OS2* os2_table;
432 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
433 info->fCapHeight = pclt_info->CapHeight;
434 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
435 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000436 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000437 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000438 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000439 } else if ((os2_table =
440 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
441 info->fCapHeight = os2_table->sCapHeight;
442 } else {
443 // Figure out a good guess for CapHeight: average the height of M and X.
444 FT_BBox m_bbox, x_bbox;
445 bool got_m, got_x;
446 got_m = GetLetterCBox(face, 'M', &m_bbox);
447 got_x = GetLetterCBox(face, 'X', &x_bbox);
448 if (got_m && got_x) {
449 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
450 x_bbox.yMin) / 2;
451 } else if (got_m && !got_x) {
452 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
453 } else if (!got_m && got_x) {
454 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
455 }
456 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000457
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000458 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
459 face->bbox.xMax, face->bbox.yMin);
460
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000461 if (!canEmbed(face) || !FT_IS_SCALABLE(face) ||
462 info->fType == SkAdvancedTypefaceMetrics::kOther_Font) {
463 perGlyphInfo = SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo;
464 }
465
466 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000467 if (FT_IS_FIXED_WIDTH(face)) {
468 appendRange(&info->fGlyphWidths, 0);
469 int16_t advance = face->max_advance_width;
470 info->fGlyphWidths->fAdvance.append(1, &advance);
471 finishRange(info->fGlyphWidths.get(), 0,
472 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000473 } else if (!cid) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000474 appendRange(&info->fGlyphWidths, 0);
475 // So as to not blow out the stack, get advances in batches.
476 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
477 FT_Fixed advances[128];
478 int advanceCount = 128;
479 if (gID + advanceCount > face->num_glyphs)
480 advanceCount = face->num_glyphs - gID + 1;
481 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
482 advances);
483 for (int i = 0; i < advanceCount; i++) {
484 int16_t advance = advances[gID + i];
485 info->fGlyphWidths->fAdvance.append(1, &advance);
486 }
487 }
488 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
489 SkAdvancedTypefaceMetrics::WidthRange::kRange);
490 } else {
vandebo@chromium.org6f72d1e2011-02-14 23:19:59 +0000491 info->fGlyphWidths.reset(
492 getAdvanceData(face, face->num_glyphs, &getWidthAdvance));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000493 }
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000494 }
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000495
vandebo@chromium.org325cb9a2011-03-30 18:36:29 +0000496 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kVAdvance_PerGlyphInfo &&
497 FT_HAS_VERTICAL(face)) {
498 SkASSERT(false); // Not implemented yet.
499 }
500
501 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo &&
502 info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
503 // Postscript fonts may contain more than 255 glyphs, so we end up
504 // using multiple font descriptions with a glyph ordering. Record
505 // the name of each glyph.
506 info->fGlyphNames.reset(
507 new SkAutoTArray<SkString>(face->num_glyphs));
508 for (int gID = 0; gID < face->num_glyphs; gID++) {
509 char glyphName[128]; // PS limit for names is 127 bytes.
510 FT_Get_Glyph_Name(face, gID, glyphName, 128);
511 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000512 }
513 }
514
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000515 if (!canEmbed(face))
516 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
517
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000518 unref_ft_face(face);
519 return info;
reed@google.com8a5d6922011-03-14 15:08:03 +0000520#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521}
reed@google.com618ef5e2011-01-26 22:10:41 +0000522///////////////////////////////////////////////////////////////////////////
523
524void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
525 if (!gLCDSupportValid) {
526 InitFreetype();
527 FT_Done_FreeType(gFTLibrary);
528 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000529
reed@google.com8abde0a2011-03-14 17:45:33 +0000530 if (!gLCDSupport && (rec->isLCD() || SkMask::kLCD16_Format == rec->fMaskFormat)) {
reed@google.com618ef5e2011-01-26 22:10:41 +0000531 // If the runtime Freetype library doesn't support LCD mode, we disable
532 // it here.
533 rec->fMaskFormat = SkMask::kA8_Format;
534 }
reed@google.com5b31b0f2011-02-23 14:41:42 +0000535
reed@google.com618ef5e2011-01-26 22:10:41 +0000536 SkPaint::Hinting h = rec->getHinting();
537 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
538 // collapse full->normal hinting if we're not doing LCD
539 h = SkPaint::kNormal_Hinting;
540 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
541 SkPaint::kNo_Hinting != h) {
542 // to do subpixel, we must have at most slight hinting
543 h = SkPaint::kSlight_Hinting;
544 }
545 rec->setHinting(h);
546}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000547
djsollen@google.comcd9d69b2011-03-14 20:30:14 +0000548#ifdef ANDROID
549uint32_t SkFontHost::GetUnitsPerEm(SkFontID fontID) {
550 SkAutoMutexAcquire ac(gFTMutex);
551 SkFaceRec *rec = ref_ft_face(fontID);
552 uint16_t unitsPerEm = 0;
553
554 if (rec != NULL && rec->fFace != NULL) {
555 unitsPerEm = rec->fFace->units_per_EM;
556 unref_ft_face(rec->fFace);
557 }
558
559 return (uint32_t)unitsPerEm;
560}
561#endif
562
reed@android.com8a1c16f2008-12-17 15:59:43 +0000563SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000564 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000565 SkAutoMutexAcquire ac(gFTMutex);
566
reed@android.com8a1c16f2008-12-17 15:59:43 +0000567 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000568 if (!InitFreetype()) {
569 sk_throw();
570 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000571 }
572 ++gFTCount;
573
574 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000575 fFTSize = NULL;
576 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000577 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000578 if (NULL == fFaceRec) {
579 return;
580 }
581 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000582
583 // compute our factors from the record
584
585 SkMatrix m;
586
587 fRec.getSingleMatrix(&m);
588
589#ifdef DUMP_STRIKE_CREATION
590 SkString keyString;
591 SkFontHost::GetDescriptorKeyString(desc, &keyString);
592 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
593 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
594 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
595 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000596 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000597#endif
598
599 // now compute our scale factors
600 SkScalar sx = m.getScaleX();
601 SkScalar sy = m.getScaleY();
602
603 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
604 // sort of give up on hinting
605 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
606 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
607 sx = sy = SkScalarAve(sx, sy);
608
609 SkScalar inv = SkScalarInvert(sx);
610
611 // flip the skew elements to go from our Y-down system to FreeType's
612 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
613 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
614 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
615 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
616 } else {
617 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
618 fMatrix22.xy = fMatrix22.yx = 0;
619 }
620
621 fScaleX = SkScalarToFixed(sx);
622 fScaleY = SkScalarToFixed(sy);
623
624 // compute the flags we send to Load_Glyph
625 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000626 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000627
agl@chromium.org70a303f2010-05-10 14:15:50 +0000628 if (SkMask::kBW_Format == fRec.fMaskFormat) {
629 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
630 loadFlags = FT_LOAD_TARGET_MONO;
631 if (fRec.getHinting() == SkPaint::kNo_Hinting)
632 loadFlags = FT_LOAD_NO_HINTING;
633 } else {
634 switch (fRec.getHinting()) {
635 case SkPaint::kNo_Hinting:
636 loadFlags = FT_LOAD_NO_HINTING;
637 break;
638 case SkPaint::kSlight_Hinting:
639 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
640 break;
641 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000642 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
643 loadFlags = FT_LOAD_FORCE_AUTOHINT;
644 else
645 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000646 break;
647 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000648 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
649 loadFlags = FT_LOAD_FORCE_AUTOHINT;
650 break;
651 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000652 loadFlags = FT_LOAD_TARGET_NORMAL;
reed@google.comea2333d2011-03-14 16:44:56 +0000653 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat ||
654 SkMask::kLCD16_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000655 loadFlags = FT_LOAD_TARGET_LCD;
reed@google.comea2333d2011-03-14 16:44:56 +0000656 } else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat) {
agl@chromium.org70a303f2010-05-10 14:15:50 +0000657 loadFlags = FT_LOAD_TARGET_LCD_V;
reed@google.comea2333d2011-03-14 16:44:56 +0000658 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000659 break;
660 default:
661 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
662 break;
663 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000664 }
665
agl@chromium.org99e1b902010-01-05 01:19:44 +0000666 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000667 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000668
reed@android.come4d0bc02009-07-24 19:53:20 +0000669 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000670 }
671
672 // now create the FT_Size
673
674 {
675 FT_Error err;
676
677 err = FT_New_Size(fFace, &fFTSize);
678 if (err != 0) {
679 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
680 fFaceRec->fFontID, fScaleX, fScaleY, err));
681 fFace = NULL;
682 return;
683 }
684
685 err = FT_Activate_Size(fFTSize);
686 if (err != 0) {
687 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
688 fFaceRec->fFontID, fScaleX, fScaleY, err));
689 fFTSize = NULL;
690 }
691
692 err = FT_Set_Char_Size( fFace,
693 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
694 72, 72);
695 if (err != 0) {
696 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
697 fFaceRec->fFontID, fScaleX, fScaleY, err));
698 fFace = NULL;
699 return;
700 }
701
702 FT_Set_Transform( fFace, &fMatrix22, NULL);
703 }
704}
705
706SkScalerContext_FreeType::~SkScalerContext_FreeType() {
707 if (fFTSize != NULL) {
708 FT_Done_Size(fFTSize);
709 }
710
711 SkAutoMutexAcquire ac(gFTMutex);
712
713 if (fFace != NULL) {
714 unref_ft_face(fFace);
715 }
716 if (--gFTCount == 0) {
717// SkDEBUGF(("FT_Done_FreeType\n"));
718 FT_Done_FreeType(gFTLibrary);
719 SkDEBUGCODE(gFTLibrary = NULL;)
720 }
721}
722
723/* We call this before each use of the fFace, since we may be sharing
724 this face with other context (at different sizes).
725*/
726FT_Error SkScalerContext_FreeType::setupSize() {
727 /* In the off-chance that a font has been removed, we want to error out
728 right away, so call resolve just to be sure.
729
730 TODO: perhaps we can skip this, by walking the global font cache and
731 killing all of the contexts when we know that a given fontID is going
732 away...
733 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000734 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000735 return (FT_Error)-1;
736 }
737
738 FT_Error err = FT_Activate_Size(fFTSize);
739
740 if (err != 0) {
741 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
742 fFaceRec->fFontID, fScaleX, fScaleY, err));
743 fFTSize = NULL;
744 } else {
745 // seems we need to reset this every time (not sure why, but without it
746 // I get random italics from some other fFTSize)
747 FT_Set_Transform( fFace, &fMatrix22, NULL);
748 }
749 return err;
750}
751
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000752void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
753 FT_Pos strength;
754 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
755 / 24;
756 FT_Outline_Embolden(outline, strength);
757}
758
ctguil@chromium.org0bc7bf52011-03-04 19:04:57 +0000759unsigned SkScalerContext_FreeType::generateGlyphCount() {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000760 return fFace->num_glyphs;
761}
762
763uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
764 return SkToU16(FT_Get_Char_Index( fFace, uni ));
765}
766
reed@android.com9d3a9852010-01-08 14:07:42 +0000767SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
768 // iterate through each cmap entry, looking for matching glyph indices
769 FT_UInt glyphIndex;
770 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
771
772 while (glyphIndex != 0) {
773 if (glyphIndex == glyph) {
774 return charCode;
775 }
776 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
777 }
778
779 return 0;
780}
781
reed@android.com8a1c16f2008-12-17 15:59:43 +0000782static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
783 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000784 case SkMask::kHorizontalLCD_Format:
785 case SkMask::kVerticalLCD_Format:
786 SkASSERT(!"An LCD format should never be passed here");
787 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000788 case SkMask::kBW_Format:
789 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790 case SkMask::kA8_Format:
791 default:
792 return FT_PIXEL_MODE_GRAY;
793 }
794}
795
reed@android.com8a1c16f2008-12-17 15:59:43 +0000796void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
797#ifdef FT_ADVANCES_H
798 /* unhinted and light hinted text have linearly scaled advances
799 * which are very cheap to compute with some font formats...
800 */
801 {
802 SkAutoMutexAcquire ac(gFTMutex);
803
804 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000805 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000806 return;
807 }
808
809 FT_Error error;
810 FT_Fixed advance;
811
812 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
813 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
814 &advance );
815 if (0 == error) {
816 glyph->fRsbDelta = 0;
817 glyph->fLsbDelta = 0;
818 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
819 glyph->fAdvanceY = 0;
820 return;
821 }
822 }
823#endif /* FT_ADVANCES_H */
824 /* otherwise, we need to load/hint the glyph, which is slower */
825 this->generateMetrics(glyph);
826 return;
827}
828
829void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
830 SkAutoMutexAcquire ac(gFTMutex);
831
832 glyph->fRsbDelta = 0;
833 glyph->fLsbDelta = 0;
834
835 FT_Error err;
836
837 if (this->setupSize()) {
838 goto ERROR;
839 }
840
841 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
842 if (err != 0) {
843 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
844 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
845 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000846 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847 return;
848 }
849
850 switch ( fFace->glyph->format ) {
851 case FT_GLYPH_FORMAT_OUTLINE:
852 FT_BBox bbox;
853
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000854 if (fRec.fFlags & kEmbolden_Flag) {
855 emboldenOutline(&fFace->glyph->outline);
856 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000857 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
858
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000859 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000860 int dx = glyph->getSubXFixed() >> 10;
861 int dy = glyph->getSubYFixed() >> 10;
862 // negate dy since freetype-y-goes-up and skia-y-goes-down
863 bbox.xMin += dx;
864 bbox.yMin -= dy;
865 bbox.xMax += dx;
866 bbox.yMax -= dy;
867 }
868
869 bbox.xMin &= ~63;
870 bbox.yMin &= ~63;
871 bbox.xMax = (bbox.xMax + 63) & ~63;
872 bbox.yMax = (bbox.yMax + 63) & ~63;
873
874 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
875 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
876 glyph->fTop = -SkToS16(bbox.yMax >> 6);
877 glyph->fLeft = SkToS16(bbox.xMin >> 6);
878 break;
879
880 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000881 if (fRec.fFlags & kEmbolden_Flag) {
882 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
883 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
884 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000885 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
886 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
887 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
888 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
889 break;
890
891 default:
892 SkASSERT(!"unknown glyph format");
893 goto ERROR;
894 }
895
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000896 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000897 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
898 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
899 if (fRec.fFlags & kDevKernText_Flag) {
900 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
901 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
902 }
903 } else {
904 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
905 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
906 }
907
908#ifdef ENABLE_GLYPH_SPEW
909 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
910 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
911#endif
912}
913
reed@android.comf5493692009-07-22 19:21:01 +0000914#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000915namespace skia_freetype_support {
916// extern functions from SkFontHost_FreeType_Subpixel
917extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
918extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
919}
920
921using namespace skia_freetype_support;
922#endif
923
reed@google.comea2333d2011-03-14 16:44:56 +0000924static void copyFT2LCD16(const SkGlyph& glyph, const FT_Bitmap& bitmap) {
reed@google.com260db922011-03-14 18:09:32 +0000925 SkASSERT(glyph.fWidth * 3 == bitmap.width - 6);
reed@google.comea2333d2011-03-14 16:44:56 +0000926 SkASSERT(glyph.fHeight == bitmap.rows);
927
reed@google.com260db922011-03-14 18:09:32 +0000928 const uint8_t* src = bitmap.buffer + 3;
reed@google.comea2333d2011-03-14 16:44:56 +0000929 uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage);
930 size_t dstRB = glyph.rowBytes();
931 int width = glyph.fWidth;
932
933 for (int y = 0; y < glyph.fHeight; y++) {
934 const uint8_t* triple = src;
935 for (int x = 0; x < width; x++) {
936 dst[x] = SkPackRGB16(triple[0] >> 3, triple[1] >> 2, triple[2] >> 3);
937 triple += 3;
938 }
939 src += bitmap.pitch;
940 dst = (uint16_t*)((char*)dst + dstRB);
941 }
942}
943
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
945 SkAutoMutexAcquire ac(gFTMutex);
946
947 FT_Error err;
948
949 if (this->setupSize()) {
950 goto ERROR;
951 }
952
953 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
954 if (err != 0) {
955 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
956 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
957 ERROR:
958 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
959 return;
960 }
961
agl@chromium.org309485b2009-07-21 17:41:32 +0000962 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
963 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
964
reed@android.com8a1c16f2008-12-17 15:59:43 +0000965 switch ( fFace->glyph->format ) {
966 case FT_GLYPH_FORMAT_OUTLINE: {
967 FT_Outline* outline = &fFace->glyph->outline;
968 FT_BBox bbox;
969 FT_Bitmap target;
970
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000971 if (fRec.fFlags & kEmbolden_Flag) {
972 emboldenOutline(outline);
973 }
974
reed@android.com8a1c16f2008-12-17 15:59:43 +0000975 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000976 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000977 dx = glyph.getSubXFixed() >> 10;
978 dy = glyph.getSubYFixed() >> 10;
979 // negate dy since freetype-y-goes-up and skia-y-goes-down
980 dy = -dy;
981 }
982 FT_Outline_Get_CBox(outline, &bbox);
983 /*
984 what we really want to do for subpixel is
985 offset(dx, dy)
986 compute_bounds
987 offset(bbox & !63)
988 but that is two calls to offset, so we do the following, which
989 achieves the same thing with only one offset call.
990 */
991 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
992 dy - ((bbox.yMin + dy) & ~63));
993
reed@android.comf5493692009-07-22 19:21:01 +0000994#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000995 if (lcdRenderMode) {
996 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
997 // we have to call FT_Render_Glyph and memcpy the image out.
998 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
999 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
1000 FT_Render_Glyph(fFace->glyph, mode);
1001
1002 if (isVertical)
1003 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
1004 else
1005 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
1006
1007 break;
1008 }
1009#endif
1010
reed@google.comea2333d2011-03-14 16:44:56 +00001011 if (SkMask::kLCD16_Format == glyph.fMaskFormat) {
1012 FT_Render_Glyph(fFace->glyph, FT_RENDER_MODE_LCD);
1013 copyFT2LCD16(glyph, fFace->glyph->bitmap);
1014 } else {
1015 target.width = glyph.fWidth;
1016 target.rows = glyph.fHeight;
1017 target.pitch = glyph.rowBytes();
1018 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1019 target.pixel_mode = compute_pixel_mode(
1020 (SkMask::Format)fRec.fMaskFormat);
1021 target.num_grays = 256;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001022
reed@google.comea2333d2011-03-14 16:44:56 +00001023 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1024 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1025 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001026 } break;
1027
1028 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001029 if (fRec.fFlags & kEmbolden_Flag) {
1030 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1031 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1032 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001033 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1034 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1035 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1036 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1037
1038 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1039 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001040
agl@chromium.org558434a2009-08-11 17:22:38 +00001041 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1042 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1043 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001044 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1045 unsigned dstRowBytes = glyph.rowBytes();
1046 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1047 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1048
1049 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1050 memcpy(dst, src, minRowBytes);
1051 memset(dst + minRowBytes, 0, extraRowBytes);
1052 src += srcRowBytes;
1053 dst += dstRowBytes;
1054 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001055 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001056 (glyph.fMaskFormat == SkMask::kA8_Format ||
1057 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1058 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001059 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1060 uint8_t byte = 0;
1061 int bits = 0;
1062 const uint8_t* src_row = src;
1063 uint8_t* dst_row = dst;
1064
1065 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1066 if (!bits) {
1067 byte = *src_row++;
1068 bits = 8;
1069 }
1070
1071 *dst_row++ = byte & 0x80 ? 0xff : 0;
1072 bits--;
1073 byte <<= 1;
1074 }
1075
1076 src += fFace->glyph->bitmap.pitch;
1077 dst += glyph.rowBytes();
1078 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001079 } else {
1080 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001081 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001082
1083 if (lcdRenderMode)
1084 glyph.expandA8ToLCD();
1085
reed@android.com8a1c16f2008-12-17 15:59:43 +00001086 } break;
1087
1088 default:
1089 SkASSERT(!"unknown glyph format");
1090 goto ERROR;
1091 }
1092}
1093
1094///////////////////////////////////////////////////////////////////////////////
1095
1096#define ft2sk(x) SkFixedToScalar((x) << 10)
1097
reed@android.com6f252972009-01-14 16:46:16 +00001098#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001099 #define CONST_PARAM const
1100#else // older freetype doesn't use const here
1101 #define CONST_PARAM
1102#endif
1103
1104static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1105 SkPath* path = (SkPath*)ctx;
1106 path->close(); // to close the previous contour (if any)
1107 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1108 return 0;
1109}
1110
1111static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1112 SkPath* path = (SkPath*)ctx;
1113 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1114 return 0;
1115}
1116
1117static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1118 void* ctx) {
1119 SkPath* path = (SkPath*)ctx;
1120 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1121 return 0;
1122}
1123
1124static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1125 CONST_PARAM FT_Vector* pt2, void* ctx) {
1126 SkPath* path = (SkPath*)ctx;
1127 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1128 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1129 return 0;
1130}
1131
1132void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1133 SkPath* path) {
1134 SkAutoMutexAcquire ac(gFTMutex);
1135
1136 SkASSERT(&glyph && path);
1137
1138 if (this->setupSize()) {
1139 path->reset();
1140 return;
1141 }
1142
1143 uint32_t flags = fLoadGlyphFlags;
1144 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1145 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1146
1147 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1148
1149 if (err != 0) {
1150 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1151 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1152 path->reset();
1153 return;
1154 }
1155
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001156 if (fRec.fFlags & kEmbolden_Flag) {
1157 emboldenOutline(&fFace->glyph->outline);
1158 }
1159
reed@android.com8a1c16f2008-12-17 15:59:43 +00001160 FT_Outline_Funcs funcs;
1161
1162 funcs.move_to = move_proc;
1163 funcs.line_to = line_proc;
1164 funcs.conic_to = quad_proc;
1165 funcs.cubic_to = cubic_proc;
1166 funcs.shift = 0;
1167 funcs.delta = 0;
1168
1169 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1170
1171 if (err != 0) {
1172 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1173 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1174 path->reset();
1175 return;
1176 }
1177
1178 path->close();
1179}
1180
1181void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1182 SkPaint::FontMetrics* my) {
1183 if (NULL == mx && NULL == my) {
1184 return;
1185 }
1186
1187 SkAutoMutexAcquire ac(gFTMutex);
1188
1189 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001190 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001191 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001192 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001193 }
1194 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001195 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001196 }
1197 return;
1198 }
1199
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001200 FT_Face face = fFace;
1201 int upem = face->units_per_EM;
1202 if (upem <= 0) {
1203 goto ERROR;
1204 }
1205
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001206 SkPoint pts[6];
1207 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001208 SkFixed scaleY = fScaleY;
1209 SkFixed mxy = fMatrix22.xy;
1210 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001211 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1212 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001213
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001214 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001215 if (leading < 0) {
1216 leading = 0;
1217 }
1218
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001219 // Try to get the OS/2 table from the font. This contains the specific
1220 // average font width metrics which Windows uses.
1221 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1222
reed@android.com8a1c16f2008-12-17 15:59:43 +00001223 ys[0] = -face->bbox.yMax;
1224 ys[1] = -face->ascender;
1225 ys[2] = -face->descender;
1226 ys[3] = -face->bbox.yMin;
1227 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001228 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1229
1230 SkScalar x_height;
1231 if (os2 && os2->sxHeight) {
1232 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1233 } else {
1234 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1235 if (x_glyph) {
1236 FT_BBox bbox;
1237 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001238 if (fRec.fFlags & kEmbolden_Flag) {
1239 emboldenOutline(&fFace->glyph->outline);
1240 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001241 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1242 x_height = SkIntToScalar(bbox.yMax) / 64;
1243 } else {
1244 x_height = 0;
1245 }
1246 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001247
1248 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001249 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001250 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1251 SkFixed x = SkFixedMul(mxy, y);
1252 y = SkFixedMul(myy, y);
1253 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1254 }
1255
1256 if (mx) {
1257 mx->fTop = pts[0].fX;
1258 mx->fAscent = pts[1].fX;
1259 mx->fDescent = pts[2].fX;
1260 mx->fBottom = pts[3].fX;
1261 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001262 mx->fAvgCharWidth = pts[5].fX;
1263 mx->fXMin = xmin;
1264 mx->fXMax = xmax;
1265 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001266 }
1267 if (my) {
1268 my->fTop = pts[0].fY;
1269 my->fAscent = pts[1].fY;
1270 my->fDescent = pts[2].fY;
1271 my->fBottom = pts[3].fY;
1272 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001273 my->fAvgCharWidth = pts[5].fY;
1274 my->fXMin = xmin;
1275 my->fXMax = xmax;
1276 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001277 }
1278}
1279
1280////////////////////////////////////////////////////////////////////////
1281////////////////////////////////////////////////////////////////////////
1282
1283SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001284 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1285 if (!c->success()) {
1286 SkDELETE(c);
1287 c = NULL;
1288 }
1289 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001290}
1291
1292///////////////////////////////////////////////////////////////////////////////
1293
1294/* Export this so that other parts of our FonttHost port can make use of our
1295 ability to extract the name+style from a stream, using FreeType's api.
1296*/
reed@google.com5b31b0f2011-02-23 14:41:42 +00001297SkTypeface::Style find_name_and_attributes(SkStream* stream, SkString* name,
1298 bool* isFixedWidth) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001299 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001300 if (FT_Init_FreeType(&library)) {
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001301 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001302 return SkTypeface::kNormal;
1303 }
1304
1305 FT_Open_Args args;
1306 memset(&args, 0, sizeof(args));
1307
1308 const void* memoryBase = stream->getMemoryBase();
1309 FT_StreamRec streamRec;
1310
1311 if (NULL != memoryBase) {
1312 args.flags = FT_OPEN_MEMORY;
1313 args.memory_base = (const FT_Byte*)memoryBase;
1314 args.memory_size = stream->getLength();
1315 } else {
1316 memset(&streamRec, 0, sizeof(streamRec));
1317 streamRec.size = stream->read(NULL, 0);
1318 streamRec.descriptor.pointer = stream;
1319 streamRec.read = sk_stream_read;
1320 streamRec.close = sk_stream_close;
1321
1322 args.flags = FT_OPEN_STREAM;
1323 args.stream = &streamRec;
1324 }
1325
1326 FT_Face face;
1327 if (FT_Open_Face(library, &args, 0, &face)) {
1328 FT_Done_FreeType(library);
djsollen@google.com7b34ea62011-02-24 16:28:51 +00001329 name->reset();
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330 return SkTypeface::kNormal;
1331 }
1332
1333 name->set(face->family_name);
1334 int style = SkTypeface::kNormal;
1335
1336 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1337 style |= SkTypeface::kBold;
1338 }
1339 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1340 style |= SkTypeface::kItalic;
1341 }
reed@google.com5b31b0f2011-02-23 14:41:42 +00001342 if (isFixedWidth) {
1343 *isFixedWidth = FT_IS_FIXED_WIDTH(face);
1344 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001345
1346 FT_Done_Face(face);
1347 FT_Done_FreeType(library);
1348 return (SkTypeface::Style)style;
1349}