blob: d5a48a6b4b22829bac4a4d702c1c5691195c5573 [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
agl@chromium.org309485b2009-07-21 17:41:32 +000018#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000019#include "SkScalerContext.h"
20#include "SkBitmap.h"
21#include "SkCanvas.h"
22#include "SkDescriptor.h"
23#include "SkFDot6.h"
24#include "SkFontHost.h"
25#include "SkMask.h"
26#include "SkStream.h"
27#include "SkString.h"
28#include "SkThread.h"
29#include "SkTemplates.h"
30
31#include <ft2build.h>
32#include FT_FREETYPE_H
33#include FT_OUTLINE_H
34#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000035#include FT_TRUETYPE_TABLES_H
agl@chromium.org309485b2009-07-21 17:41:32 +000036
reed@android.comf5493692009-07-22 19:21:01 +000037#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000038#include FT_LCD_FILTER_H
39#endif
40
reed@android.com8a1c16f2008-12-17 15:59:43 +000041#ifdef FT_ADVANCES_H
42#include FT_ADVANCES_H
43#endif
44
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000045#if 0
46// Also include the files by name for build tools which require this.
47#include <freetype/freetype.h>
48#include <freetype/ftoutln.h>
49#include <freetype/ftsizes.h>
50#include <freetype/tttables.h>
51#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000052#include <freetype/ftlcdfil.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000053#endif
54
reed@android.com8a1c16f2008-12-17 15:59:43 +000055//#define ENABLE_GLYPH_SPEW // for tracing calls
56//#define DUMP_STRIKE_CREATION
57
58#ifdef SK_DEBUG
59 #define SkASSERT_CONTINUE(pred) \
60 do { \
61 if (!(pred)) \
62 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
63 } while (false)
64#else
65 #define SkASSERT_CONTINUE(pred)
66#endif
67
68//////////////////////////////////////////////////////////////////////////
69
70struct SkFaceRec;
71
72static SkMutex gFTMutex;
73static int gFTCount;
74static FT_Library gFTLibrary;
75static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000076static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
77static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000078
79/////////////////////////////////////////////////////////////////////////
80
agl@chromium.org309485b2009-07-21 17:41:32 +000081static bool
82InitFreetype() {
83 FT_Error err = FT_Init_FreeType(&gFTLibrary);
84 if (err)
85 return false;
86
reed@android.comf5493692009-07-22 19:21:01 +000087#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000088 // Setup LCD filtering. This reduces colour fringes for LCD rendered
89 // glyphs.
90 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +000091 gLCDSupport = err == 0;
agl@chromium.org309485b2009-07-21 17:41:32 +000092#endif
reed@android.com61608aa2009-07-31 14:52:54 +000093 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +000094
95 return true;
96}
97
reed@android.com8a1c16f2008-12-17 15:59:43 +000098class SkScalerContext_FreeType : public SkScalerContext {
99public:
100 SkScalerContext_FreeType(const SkDescriptor* desc);
101 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000102
reed@android.com62900b42009-02-11 15:07:19 +0000103 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000104 return fFaceRec != NULL &&
105 fFTSize != NULL &&
106 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000107 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000108
109protected:
110 virtual unsigned generateGlyphCount() const;
111 virtual uint16_t generateCharToGlyph(SkUnichar uni);
112 virtual void generateAdvance(SkGlyph* glyph);
113 virtual void generateMetrics(SkGlyph* glyph);
114 virtual void generateImage(const SkGlyph& glyph);
115 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
116 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
117 SkPaint::FontMetrics* my);
118
119private:
120 SkFaceRec* fFaceRec;
121 FT_Face fFace; // reference to shared face in gFaceRecHead
122 FT_Size fFTSize; // our own copy
123 SkFixed fScaleX, fScaleY;
124 FT_Matrix fMatrix22;
125 uint32_t fLoadGlyphFlags;
126
127 FT_Error setupSize();
128};
129
130///////////////////////////////////////////////////////////////////////////
131///////////////////////////////////////////////////////////////////////////
132
133#include "SkStream.h"
134
135struct SkFaceRec {
136 SkFaceRec* fNext;
137 FT_Face fFace;
138 FT_StreamRec fFTStream;
139 SkStream* fSkStream;
140 uint32_t fRefCnt;
141 uint32_t fFontID;
142
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000143 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000144 SkFaceRec(SkStream* strm, uint32_t fontID);
145 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000146 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000147 }
148};
149
150extern "C" {
151 static unsigned long sk_stream_read(FT_Stream stream,
152 unsigned long offset,
153 unsigned char* buffer,
154 unsigned long count ) {
155 SkStream* str = (SkStream*)stream->descriptor.pointer;
156
157 if (count) {
158 if (!str->rewind()) {
159 return 0;
160 } else {
161 unsigned long ret;
162 if (offset) {
163 ret = str->read(NULL, offset);
164 if (ret != offset) {
165 return 0;
166 }
167 }
168 ret = str->read(buffer, count);
169 if (ret != count) {
170 return 0;
171 }
172 count = ret;
173 }
174 }
175 return count;
176 }
177
178 static void sk_stream_close( FT_Stream stream) {}
179}
180
181SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
182 : fSkStream(strm), fFontID(fontID) {
183// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
184
reed@android.com4516f472009-06-29 16:25:36 +0000185 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000186 fFTStream.size = fSkStream->getLength();
187 fFTStream.descriptor.pointer = fSkStream;
188 fFTStream.read = sk_stream_read;
189 fFTStream.close = sk_stream_close;
190}
191
reed@android.com62900b42009-02-11 15:07:19 +0000192// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000193static SkFaceRec* ref_ft_face(uint32_t fontID) {
194 SkFaceRec* rec = gFaceRecHead;
195 while (rec) {
196 if (rec->fFontID == fontID) {
197 SkASSERT(rec->fFace);
198 rec->fRefCnt += 1;
199 return rec;
200 }
201 rec = rec->fNext;
202 }
203
204 SkStream* strm = SkFontHost::OpenStream(fontID);
205 if (NULL == strm) {
206 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000207 return 0;
208 }
209
210 // this passes ownership of strm to the rec
211 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
212
213 FT_Open_Args args;
214 memset(&args, 0, sizeof(args));
215 const void* memoryBase = strm->getMemoryBase();
216
217 if (NULL != memoryBase) {
218//printf("mmap(%s)\n", keyString.c_str());
219 args.flags = FT_OPEN_MEMORY;
220 args.memory_base = (const FT_Byte*)memoryBase;
221 args.memory_size = strm->getLength();
222 } else {
223//printf("fopen(%s)\n", keyString.c_str());
224 args.flags = FT_OPEN_STREAM;
225 args.stream = &rec->fFTStream;
226 }
227
228 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
229
230 if (err) { // bad filename, try the default font
231 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
232 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000233 return 0;
234 } else {
235 SkASSERT(rec->fFace);
236 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
237 rec->fNext = gFaceRecHead;
238 gFaceRecHead = rec;
239 rec->fRefCnt = 1;
240 return rec;
241 }
242}
243
244static void unref_ft_face(FT_Face face) {
245 SkFaceRec* rec = gFaceRecHead;
246 SkFaceRec* prev = NULL;
247 while (rec) {
248 SkFaceRec* next = rec->fNext;
249 if (rec->fFace == face) {
250 if (--rec->fRefCnt == 0) {
251 if (prev) {
252 prev->fNext = next;
253 } else {
254 gFaceRecHead = next;
255 }
256 FT_Done_Face(face);
257 SkDELETE(rec);
258 }
259 return;
260 }
261 prev = rec;
262 rec = next;
263 }
264 SkASSERT("shouldn't get here, face not in list");
265}
266
267///////////////////////////////////////////////////////////////////////////
268
reed@android.com36a4c2a2009-07-22 19:52:11 +0000269void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000270 if (!gLCDSupportValid) {
271 InitFreetype();
272 FT_Done_FreeType(gFTLibrary);
273 }
274
275 if (!gLCDSupport && rec->isLCD()) {
276 // If the runtime Freetype library doesn't support LCD mode, we disable
277 // it here.
278 rec->fMaskFormat = SkMask::kA8_Format;
279 }
280
reed@android.com36a4c2a2009-07-22 19:52:11 +0000281 SkPaint::Hinting h = rec->getHinting();
282 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
reed@android.come4d0bc02009-07-24 19:53:20 +0000283 // collapse full->normaling hinting if we're not doing LCD
284 h = SkPaint::kNormal_Hinting;
285 } else if (rec->fSubpixelPositioning && SkPaint::kNo_Hinting != h) {
286 // to do subpixel, we must have at most slight hinting
287 h = SkPaint::kSlight_Hinting;
reed@android.com36a4c2a2009-07-22 19:52:11 +0000288 }
reed@android.come4d0bc02009-07-24 19:53:20 +0000289 rec->setHinting(h);
reed@android.com36a4c2a2009-07-22 19:52:11 +0000290}
291
reed@android.com8a1c16f2008-12-17 15:59:43 +0000292SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000293 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000294 SkAutoMutexAcquire ac(gFTMutex);
295
reed@android.com8a1c16f2008-12-17 15:59:43 +0000296 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000297 if (!InitFreetype()) {
298 sk_throw();
299 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000300 }
301 ++gFTCount;
302
303 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000304 fFTSize = NULL;
305 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000306 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000307 if (NULL == fFaceRec) {
308 return;
309 }
310 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000311
312 // compute our factors from the record
313
314 SkMatrix m;
315
316 fRec.getSingleMatrix(&m);
317
318#ifdef DUMP_STRIKE_CREATION
319 SkString keyString;
320 SkFontHost::GetDescriptorKeyString(desc, &keyString);
321 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
322 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
323 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
324 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000325 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000326#endif
327
328 // now compute our scale factors
329 SkScalar sx = m.getScaleX();
330 SkScalar sy = m.getScaleY();
331
332 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
333 // sort of give up on hinting
334 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
335 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
336 sx = sy = SkScalarAve(sx, sy);
337
338 SkScalar inv = SkScalarInvert(sx);
339
340 // flip the skew elements to go from our Y-down system to FreeType's
341 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
342 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
343 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
344 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
345 } else {
346 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
347 fMatrix22.xy = fMatrix22.yx = 0;
348 }
349
350 fScaleX = SkScalarToFixed(sx);
351 fScaleY = SkScalarToFixed(sy);
352
353 // compute the flags we send to Load_Glyph
354 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000355 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000356
agl@chromium.org309485b2009-07-21 17:41:32 +0000357 switch (fRec.getHinting()) {
358 case SkPaint::kNo_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000359 loadFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000360 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000361 case SkPaint::kSlight_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000362 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000363 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000364 case SkPaint::kNormal_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000365 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000366 break;
367 case SkPaint::kFull_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000368 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000369 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000370 loadFlags = FT_LOAD_TARGET_LCD;
agl@chromium.org309485b2009-07-21 17:41:32 +0000371 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000372 loadFlags = FT_LOAD_TARGET_LCD_V;
373 break;
374 default:
375 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000376 break;
377 }
378
agl@chromium.org99e1b902010-01-05 01:19:44 +0000379 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000380 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000381
reed@android.come4d0bc02009-07-24 19:53:20 +0000382 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000383 }
384
385 // now create the FT_Size
386
387 {
388 FT_Error err;
389
390 err = FT_New_Size(fFace, &fFTSize);
391 if (err != 0) {
392 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
393 fFaceRec->fFontID, fScaleX, fScaleY, err));
394 fFace = NULL;
395 return;
396 }
397
398 err = FT_Activate_Size(fFTSize);
399 if (err != 0) {
400 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
401 fFaceRec->fFontID, fScaleX, fScaleY, err));
402 fFTSize = NULL;
403 }
404
405 err = FT_Set_Char_Size( fFace,
406 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
407 72, 72);
408 if (err != 0) {
409 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
410 fFaceRec->fFontID, fScaleX, fScaleY, err));
411 fFace = NULL;
412 return;
413 }
414
415 FT_Set_Transform( fFace, &fMatrix22, NULL);
416 }
417}
418
419SkScalerContext_FreeType::~SkScalerContext_FreeType() {
420 if (fFTSize != NULL) {
421 FT_Done_Size(fFTSize);
422 }
423
424 SkAutoMutexAcquire ac(gFTMutex);
425
426 if (fFace != NULL) {
427 unref_ft_face(fFace);
428 }
429 if (--gFTCount == 0) {
430// SkDEBUGF(("FT_Done_FreeType\n"));
431 FT_Done_FreeType(gFTLibrary);
432 SkDEBUGCODE(gFTLibrary = NULL;)
433 }
434}
435
436/* We call this before each use of the fFace, since we may be sharing
437 this face with other context (at different sizes).
438*/
439FT_Error SkScalerContext_FreeType::setupSize() {
440 /* In the off-chance that a font has been removed, we want to error out
441 right away, so call resolve just to be sure.
442
443 TODO: perhaps we can skip this, by walking the global font cache and
444 killing all of the contexts when we know that a given fontID is going
445 away...
446 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000447 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000448 return (FT_Error)-1;
449 }
450
451 FT_Error err = FT_Activate_Size(fFTSize);
452
453 if (err != 0) {
454 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
455 fFaceRec->fFontID, fScaleX, fScaleY, err));
456 fFTSize = NULL;
457 } else {
458 // seems we need to reset this every time (not sure why, but without it
459 // I get random italics from some other fFTSize)
460 FT_Set_Transform( fFace, &fMatrix22, NULL);
461 }
462 return err;
463}
464
465unsigned SkScalerContext_FreeType::generateGlyphCount() const {
466 return fFace->num_glyphs;
467}
468
469uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
470 return SkToU16(FT_Get_Char_Index( fFace, uni ));
471}
472
473static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
474 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000475 case SkMask::kHorizontalLCD_Format:
476 case SkMask::kVerticalLCD_Format:
477 SkASSERT(!"An LCD format should never be passed here");
478 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000479 case SkMask::kBW_Format:
480 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000481 case SkMask::kA8_Format:
482 default:
483 return FT_PIXEL_MODE_GRAY;
484 }
485}
486
reed@android.com8a1c16f2008-12-17 15:59:43 +0000487void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
488#ifdef FT_ADVANCES_H
489 /* unhinted and light hinted text have linearly scaled advances
490 * which are very cheap to compute with some font formats...
491 */
492 {
493 SkAutoMutexAcquire ac(gFTMutex);
494
495 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000496 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000497 return;
498 }
499
500 FT_Error error;
501 FT_Fixed advance;
502
503 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
504 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
505 &advance );
506 if (0 == error) {
507 glyph->fRsbDelta = 0;
508 glyph->fLsbDelta = 0;
509 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
510 glyph->fAdvanceY = 0;
511 return;
512 }
513 }
514#endif /* FT_ADVANCES_H */
515 /* otherwise, we need to load/hint the glyph, which is slower */
516 this->generateMetrics(glyph);
517 return;
518}
519
520void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
521 SkAutoMutexAcquire ac(gFTMutex);
522
523 glyph->fRsbDelta = 0;
524 glyph->fLsbDelta = 0;
525
526 FT_Error err;
527
528 if (this->setupSize()) {
529 goto ERROR;
530 }
531
532 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
533 if (err != 0) {
534 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
535 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
536 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000537 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000538 return;
539 }
540
541 switch ( fFace->glyph->format ) {
542 case FT_GLYPH_FORMAT_OUTLINE:
543 FT_BBox bbox;
544
545 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
546
agl@chromium.org309485b2009-07-21 17:41:32 +0000547 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000548 int dx = glyph->getSubXFixed() >> 10;
549 int dy = glyph->getSubYFixed() >> 10;
550 // negate dy since freetype-y-goes-up and skia-y-goes-down
551 bbox.xMin += dx;
552 bbox.yMin -= dy;
553 bbox.xMax += dx;
554 bbox.yMax -= dy;
555 }
556
557 bbox.xMin &= ~63;
558 bbox.yMin &= ~63;
559 bbox.xMax = (bbox.xMax + 63) & ~63;
560 bbox.yMax = (bbox.yMax + 63) & ~63;
561
562 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
563 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
564 glyph->fTop = -SkToS16(bbox.yMax >> 6);
565 glyph->fLeft = SkToS16(bbox.xMin >> 6);
566 break;
567
568 case FT_GLYPH_FORMAT_BITMAP:
569 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
570 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
571 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
572 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
573 break;
574
575 default:
576 SkASSERT(!"unknown glyph format");
577 goto ERROR;
578 }
579
agl@chromium.org309485b2009-07-21 17:41:32 +0000580 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000581 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
582 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
583 if (fRec.fFlags & kDevKernText_Flag) {
584 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
585 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
586 }
587 } else {
588 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
589 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
590 }
591
592#ifdef ENABLE_GLYPH_SPEW
593 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
594 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
595#endif
596}
597
reed@android.comf5493692009-07-22 19:21:01 +0000598#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000599namespace skia_freetype_support {
600// extern functions from SkFontHost_FreeType_Subpixel
601extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
602extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
603}
604
605using namespace skia_freetype_support;
606#endif
607
reed@android.com8a1c16f2008-12-17 15:59:43 +0000608void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
609 SkAutoMutexAcquire ac(gFTMutex);
610
611 FT_Error err;
612
613 if (this->setupSize()) {
614 goto ERROR;
615 }
616
617 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
618 if (err != 0) {
619 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
620 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
621 ERROR:
622 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
623 return;
624 }
625
agl@chromium.org309485b2009-07-21 17:41:32 +0000626 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
627 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
628
reed@android.com8a1c16f2008-12-17 15:59:43 +0000629 switch ( fFace->glyph->format ) {
630 case FT_GLYPH_FORMAT_OUTLINE: {
631 FT_Outline* outline = &fFace->glyph->outline;
632 FT_BBox bbox;
633 FT_Bitmap target;
634
635 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000636 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000637 dx = glyph.getSubXFixed() >> 10;
638 dy = glyph.getSubYFixed() >> 10;
639 // negate dy since freetype-y-goes-up and skia-y-goes-down
640 dy = -dy;
641 }
642 FT_Outline_Get_CBox(outline, &bbox);
643 /*
644 what we really want to do for subpixel is
645 offset(dx, dy)
646 compute_bounds
647 offset(bbox & !63)
648 but that is two calls to offset, so we do the following, which
649 achieves the same thing with only one offset call.
650 */
651 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
652 dy - ((bbox.yMin + dy) & ~63));
653
reed@android.comf5493692009-07-22 19:21:01 +0000654#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000655 if (lcdRenderMode) {
656 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
657 // we have to call FT_Render_Glyph and memcpy the image out.
658 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
659 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
660 FT_Render_Glyph(fFace->glyph, mode);
661
662 if (isVertical)
663 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
664 else
665 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
666
667 break;
668 }
669#endif
670
reed@android.com8a1c16f2008-12-17 15:59:43 +0000671 target.width = glyph.fWidth;
672 target.rows = glyph.fHeight;
673 target.pitch = glyph.rowBytes();
674 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
675 target.pixel_mode = compute_pixel_mode(
676 (SkMask::Format)fRec.fMaskFormat);
677 target.num_grays = 256;
678
679 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
680 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
681 } break;
682
683 case FT_GLYPH_FORMAT_BITMAP: {
684 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
685 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
686 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
687 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
688
689 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
690 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000691
agl@chromium.org558434a2009-08-11 17:22:38 +0000692 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
693 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
694 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000695 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
696 unsigned dstRowBytes = glyph.rowBytes();
697 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
698 unsigned extraRowBytes = dstRowBytes - minRowBytes;
699
700 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
701 memcpy(dst, src, minRowBytes);
702 memset(dst + minRowBytes, 0, extraRowBytes);
703 src += srcRowBytes;
704 dst += dstRowBytes;
705 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000706 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +0000707 (glyph.fMaskFormat == SkMask::kA8_Format ||
708 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
709 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000710 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
711 uint8_t byte = 0;
712 int bits = 0;
713 const uint8_t* src_row = src;
714 uint8_t* dst_row = dst;
715
716 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
717 if (!bits) {
718 byte = *src_row++;
719 bits = 8;
720 }
721
722 *dst_row++ = byte & 0x80 ? 0xff : 0;
723 bits--;
724 byte <<= 1;
725 }
726
727 src += fFace->glyph->bitmap.pitch;
728 dst += glyph.rowBytes();
729 }
agl@chromium.org558434a2009-08-11 17:22:38 +0000730 } else {
731 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +0000732 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000733
734 if (lcdRenderMode)
735 glyph.expandA8ToLCD();
736
reed@android.com8a1c16f2008-12-17 15:59:43 +0000737 } break;
738
739 default:
740 SkASSERT(!"unknown glyph format");
741 goto ERROR;
742 }
743}
744
745///////////////////////////////////////////////////////////////////////////////
746
747#define ft2sk(x) SkFixedToScalar((x) << 10)
748
reed@android.com6f252972009-01-14 16:46:16 +0000749#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000750 #define CONST_PARAM const
751#else // older freetype doesn't use const here
752 #define CONST_PARAM
753#endif
754
755static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
756 SkPath* path = (SkPath*)ctx;
757 path->close(); // to close the previous contour (if any)
758 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
759 return 0;
760}
761
762static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
763 SkPath* path = (SkPath*)ctx;
764 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
765 return 0;
766}
767
768static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
769 void* ctx) {
770 SkPath* path = (SkPath*)ctx;
771 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
772 return 0;
773}
774
775static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
776 CONST_PARAM FT_Vector* pt2, void* ctx) {
777 SkPath* path = (SkPath*)ctx;
778 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
779 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
780 return 0;
781}
782
783void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
784 SkPath* path) {
785 SkAutoMutexAcquire ac(gFTMutex);
786
787 SkASSERT(&glyph && path);
788
789 if (this->setupSize()) {
790 path->reset();
791 return;
792 }
793
794 uint32_t flags = fLoadGlyphFlags;
795 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
796 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
797
798 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
799
800 if (err != 0) {
801 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
802 glyph.getGlyphID(fBaseGlyphCount), flags, err));
803 path->reset();
804 return;
805 }
806
807 FT_Outline_Funcs funcs;
808
809 funcs.move_to = move_proc;
810 funcs.line_to = line_proc;
811 funcs.conic_to = quad_proc;
812 funcs.cubic_to = cubic_proc;
813 funcs.shift = 0;
814 funcs.delta = 0;
815
816 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
817
818 if (err != 0) {
819 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
820 glyph.getGlyphID(fBaseGlyphCount), flags, err));
821 path->reset();
822 return;
823 }
824
825 path->close();
826}
827
828void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
829 SkPaint::FontMetrics* my) {
830 if (NULL == mx && NULL == my) {
831 return;
832 }
833
834 SkAutoMutexAcquire ac(gFTMutex);
835
836 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000837 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000838 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000839 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000840 }
841 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000842 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000843 }
844 return;
845 }
846
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000847 FT_Face face = fFace;
848 int upem = face->units_per_EM;
849 if (upem <= 0) {
850 goto ERROR;
851 }
852
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000853 SkPoint pts[6];
854 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000855 SkFixed scaleY = fScaleY;
856 SkFixed mxy = fMatrix22.xy;
857 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000858 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
859 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000860
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000861 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000862 if (leading < 0) {
863 leading = 0;
864 }
865
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000866 // Try to get the OS/2 table from the font. This contains the specific
867 // average font width metrics which Windows uses.
868 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
869
reed@android.com8a1c16f2008-12-17 15:59:43 +0000870 ys[0] = -face->bbox.yMax;
871 ys[1] = -face->ascender;
872 ys[2] = -face->descender;
873 ys[3] = -face->bbox.yMin;
874 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000875 ys[5] = os2 ? os2->xAvgCharWidth : 0;
876
877 SkScalar x_height;
878 if (os2 && os2->sxHeight) {
879 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
880 } else {
881 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
882 if (x_glyph) {
883 FT_BBox bbox;
884 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
885 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
886 x_height = SkIntToScalar(bbox.yMax) / 64;
887 } else {
888 x_height = 0;
889 }
890 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000891
892 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000893 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000894 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
895 SkFixed x = SkFixedMul(mxy, y);
896 y = SkFixedMul(myy, y);
897 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
898 }
899
900 if (mx) {
901 mx->fTop = pts[0].fX;
902 mx->fAscent = pts[1].fX;
903 mx->fDescent = pts[2].fX;
904 mx->fBottom = pts[3].fX;
905 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000906 mx->fAvgCharWidth = pts[5].fX;
907 mx->fXMin = xmin;
908 mx->fXMax = xmax;
909 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000910 }
911 if (my) {
912 my->fTop = pts[0].fY;
913 my->fAscent = pts[1].fY;
914 my->fDescent = pts[2].fY;
915 my->fBottom = pts[3].fY;
916 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000917 my->fAvgCharWidth = pts[5].fY;
918 my->fXMin = xmin;
919 my->fXMax = xmax;
920 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000921 }
922}
923
924////////////////////////////////////////////////////////////////////////
925////////////////////////////////////////////////////////////////////////
926
927SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000928 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
929 if (!c->success()) {
930 SkDELETE(c);
931 c = NULL;
932 }
933 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000934}
935
936///////////////////////////////////////////////////////////////////////////////
937
938/* Export this so that other parts of our FonttHost port can make use of our
939 ability to extract the name+style from a stream, using FreeType's api.
940*/
941SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
942 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +0000943 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944 name->set(NULL);
945 return SkTypeface::kNormal;
946 }
947
948 FT_Open_Args args;
949 memset(&args, 0, sizeof(args));
950
951 const void* memoryBase = stream->getMemoryBase();
952 FT_StreamRec streamRec;
953
954 if (NULL != memoryBase) {
955 args.flags = FT_OPEN_MEMORY;
956 args.memory_base = (const FT_Byte*)memoryBase;
957 args.memory_size = stream->getLength();
958 } else {
959 memset(&streamRec, 0, sizeof(streamRec));
960 streamRec.size = stream->read(NULL, 0);
961 streamRec.descriptor.pointer = stream;
962 streamRec.read = sk_stream_read;
963 streamRec.close = sk_stream_close;
964
965 args.flags = FT_OPEN_STREAM;
966 args.stream = &streamRec;
967 }
968
969 FT_Face face;
970 if (FT_Open_Face(library, &args, 0, &face)) {
971 FT_Done_FreeType(library);
972 name->set(NULL);
973 return SkTypeface::kNormal;
974 }
975
976 name->set(face->family_name);
977 int style = SkTypeface::kNormal;
978
979 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
980 style |= SkTypeface::kBold;
981 }
982 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
983 style |= SkTypeface::kItalic;
984 }
985
986 FT_Done_Face(face);
987 FT_Done_FreeType(library);
988 return (SkTypeface::Style)style;
989}