blob: dbba1a28a4d0fb10b5eb5767e0a97c0cf80a6236 [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;
76
77/////////////////////////////////////////////////////////////////////////
78
agl@chromium.org309485b2009-07-21 17:41:32 +000079static bool
80InitFreetype() {
81 FT_Error err = FT_Init_FreeType(&gFTLibrary);
82 if (err)
83 return false;
84
reed@android.comf5493692009-07-22 19:21:01 +000085#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000086 // Setup LCD filtering. This reduces colour fringes for LCD rendered
87 // glyphs.
88 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
89#endif
90
91 return true;
92}
93
reed@android.com8a1c16f2008-12-17 15:59:43 +000094class SkScalerContext_FreeType : public SkScalerContext {
95public:
96 SkScalerContext_FreeType(const SkDescriptor* desc);
97 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000098
reed@android.com62900b42009-02-11 15:07:19 +000099 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000100 return fFaceRec != NULL &&
101 fFTSize != NULL &&
102 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000103 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000104
105protected:
106 virtual unsigned generateGlyphCount() const;
107 virtual uint16_t generateCharToGlyph(SkUnichar uni);
108 virtual void generateAdvance(SkGlyph* glyph);
109 virtual void generateMetrics(SkGlyph* glyph);
110 virtual void generateImage(const SkGlyph& glyph);
111 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
112 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
113 SkPaint::FontMetrics* my);
114
115private:
116 SkFaceRec* fFaceRec;
117 FT_Face fFace; // reference to shared face in gFaceRecHead
118 FT_Size fFTSize; // our own copy
119 SkFixed fScaleX, fScaleY;
120 FT_Matrix fMatrix22;
121 uint32_t fLoadGlyphFlags;
122
123 FT_Error setupSize();
124};
125
126///////////////////////////////////////////////////////////////////////////
127///////////////////////////////////////////////////////////////////////////
128
129#include "SkStream.h"
130
131struct SkFaceRec {
132 SkFaceRec* fNext;
133 FT_Face fFace;
134 FT_StreamRec fFTStream;
135 SkStream* fSkStream;
136 uint32_t fRefCnt;
137 uint32_t fFontID;
138
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000139 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000140 SkFaceRec(SkStream* strm, uint32_t fontID);
141 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000142 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000143 }
144};
145
146extern "C" {
147 static unsigned long sk_stream_read(FT_Stream stream,
148 unsigned long offset,
149 unsigned char* buffer,
150 unsigned long count ) {
151 SkStream* str = (SkStream*)stream->descriptor.pointer;
152
153 if (count) {
154 if (!str->rewind()) {
155 return 0;
156 } else {
157 unsigned long ret;
158 if (offset) {
159 ret = str->read(NULL, offset);
160 if (ret != offset) {
161 return 0;
162 }
163 }
164 ret = str->read(buffer, count);
165 if (ret != count) {
166 return 0;
167 }
168 count = ret;
169 }
170 }
171 return count;
172 }
173
174 static void sk_stream_close( FT_Stream stream) {}
175}
176
177SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
178 : fSkStream(strm), fFontID(fontID) {
179// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
180
reed@android.com4516f472009-06-29 16:25:36 +0000181 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000182 fFTStream.size = fSkStream->getLength();
183 fFTStream.descriptor.pointer = fSkStream;
184 fFTStream.read = sk_stream_read;
185 fFTStream.close = sk_stream_close;
186}
187
reed@android.com62900b42009-02-11 15:07:19 +0000188// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000189static SkFaceRec* ref_ft_face(uint32_t fontID) {
190 SkFaceRec* rec = gFaceRecHead;
191 while (rec) {
192 if (rec->fFontID == fontID) {
193 SkASSERT(rec->fFace);
194 rec->fRefCnt += 1;
195 return rec;
196 }
197 rec = rec->fNext;
198 }
199
200 SkStream* strm = SkFontHost::OpenStream(fontID);
201 if (NULL == strm) {
202 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000203 return 0;
204 }
205
206 // this passes ownership of strm to the rec
207 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
208
209 FT_Open_Args args;
210 memset(&args, 0, sizeof(args));
211 const void* memoryBase = strm->getMemoryBase();
212
213 if (NULL != memoryBase) {
214//printf("mmap(%s)\n", keyString.c_str());
215 args.flags = FT_OPEN_MEMORY;
216 args.memory_base = (const FT_Byte*)memoryBase;
217 args.memory_size = strm->getLength();
218 } else {
219//printf("fopen(%s)\n", keyString.c_str());
220 args.flags = FT_OPEN_STREAM;
221 args.stream = &rec->fFTStream;
222 }
223
224 FT_Error err = FT_Open_Face(gFTLibrary, &args, 0, &rec->fFace);
225
226 if (err) { // bad filename, try the default font
227 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
228 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000229 return 0;
230 } else {
231 SkASSERT(rec->fFace);
232 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
233 rec->fNext = gFaceRecHead;
234 gFaceRecHead = rec;
235 rec->fRefCnt = 1;
236 return rec;
237 }
238}
239
240static void unref_ft_face(FT_Face face) {
241 SkFaceRec* rec = gFaceRecHead;
242 SkFaceRec* prev = NULL;
243 while (rec) {
244 SkFaceRec* next = rec->fNext;
245 if (rec->fFace == face) {
246 if (--rec->fRefCnt == 0) {
247 if (prev) {
248 prev->fNext = next;
249 } else {
250 gFaceRecHead = next;
251 }
252 FT_Done_Face(face);
253 SkDELETE(rec);
254 }
255 return;
256 }
257 prev = rec;
258 rec = next;
259 }
260 SkASSERT("shouldn't get here, face not in list");
261}
262
263///////////////////////////////////////////////////////////////////////////
264
reed@android.com36a4c2a2009-07-22 19:52:11 +0000265void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
reed@android.com36a4c2a2009-07-22 19:52:11 +0000266 SkPaint::Hinting h = rec->getHinting();
267 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
reed@android.come4d0bc02009-07-24 19:53:20 +0000268 // collapse full->normaling hinting if we're not doing LCD
269 h = SkPaint::kNormal_Hinting;
270 } else if (rec->fSubpixelPositioning && SkPaint::kNo_Hinting != h) {
271 // to do subpixel, we must have at most slight hinting
272 h = SkPaint::kSlight_Hinting;
reed@android.com36a4c2a2009-07-22 19:52:11 +0000273 }
reed@android.come4d0bc02009-07-24 19:53:20 +0000274 rec->setHinting(h);
reed@android.com36a4c2a2009-07-22 19:52:11 +0000275}
276
reed@android.com8a1c16f2008-12-17 15:59:43 +0000277SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000278 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000279 SkAutoMutexAcquire ac(gFTMutex);
280
reed@android.com8a1c16f2008-12-17 15:59:43 +0000281 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000282 if (!InitFreetype()) {
283 sk_throw();
284 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000285 }
286 ++gFTCount;
287
288 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000289 fFTSize = NULL;
290 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000291 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000292 if (NULL == fFaceRec) {
293 return;
294 }
295 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000296
297 // compute our factors from the record
298
299 SkMatrix m;
300
301 fRec.getSingleMatrix(&m);
302
303#ifdef DUMP_STRIKE_CREATION
304 SkString keyString;
305 SkFontHost::GetDescriptorKeyString(desc, &keyString);
306 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
307 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
308 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
309 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000310 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000311#endif
312
313 // now compute our scale factors
314 SkScalar sx = m.getScaleX();
315 SkScalar sy = m.getScaleY();
316
317 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
318 // sort of give up on hinting
319 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
320 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
321 sx = sy = SkScalarAve(sx, sy);
322
323 SkScalar inv = SkScalarInvert(sx);
324
325 // flip the skew elements to go from our Y-down system to FreeType's
326 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
327 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
328 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
329 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
330 } else {
331 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
332 fMatrix22.xy = fMatrix22.yx = 0;
333 }
334
335 fScaleX = SkScalarToFixed(sx);
336 fScaleY = SkScalarToFixed(sy);
337
338 // compute the flags we send to Load_Glyph
339 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000340 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000341
agl@chromium.org309485b2009-07-21 17:41:32 +0000342 switch (fRec.getHinting()) {
343 case SkPaint::kNo_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000344 loadFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000345 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000346 case SkPaint::kSlight_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000347 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000348 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000349 case SkPaint::kNormal_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000350 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000351 break;
352 case SkPaint::kFull_Hinting:
reed@android.come4d0bc02009-07-24 19:53:20 +0000353 loadFlags = FT_LOAD_TARGET_NORMAL;
agl@chromium.org309485b2009-07-21 17:41:32 +0000354 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000355 loadFlags = FT_LOAD_TARGET_LCD;
agl@chromium.org309485b2009-07-21 17:41:32 +0000356 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
reed@android.come4d0bc02009-07-24 19:53:20 +0000357 loadFlags = FT_LOAD_TARGET_LCD_V;
358 break;
359 default:
360 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000361 break;
362 }
363
reed@android.come4d0bc02009-07-24 19:53:20 +0000364 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000365 }
366
367 // now create the FT_Size
368
369 {
370 FT_Error err;
371
372 err = FT_New_Size(fFace, &fFTSize);
373 if (err != 0) {
374 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
375 fFaceRec->fFontID, fScaleX, fScaleY, err));
376 fFace = NULL;
377 return;
378 }
379
380 err = FT_Activate_Size(fFTSize);
381 if (err != 0) {
382 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
383 fFaceRec->fFontID, fScaleX, fScaleY, err));
384 fFTSize = NULL;
385 }
386
387 err = FT_Set_Char_Size( fFace,
388 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
389 72, 72);
390 if (err != 0) {
391 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
392 fFaceRec->fFontID, fScaleX, fScaleY, err));
393 fFace = NULL;
394 return;
395 }
396
397 FT_Set_Transform( fFace, &fMatrix22, NULL);
398 }
399}
400
401SkScalerContext_FreeType::~SkScalerContext_FreeType() {
402 if (fFTSize != NULL) {
403 FT_Done_Size(fFTSize);
404 }
405
406 SkAutoMutexAcquire ac(gFTMutex);
407
408 if (fFace != NULL) {
409 unref_ft_face(fFace);
410 }
411 if (--gFTCount == 0) {
412// SkDEBUGF(("FT_Done_FreeType\n"));
413 FT_Done_FreeType(gFTLibrary);
414 SkDEBUGCODE(gFTLibrary = NULL;)
415 }
416}
417
418/* We call this before each use of the fFace, since we may be sharing
419 this face with other context (at different sizes).
420*/
421FT_Error SkScalerContext_FreeType::setupSize() {
422 /* In the off-chance that a font has been removed, we want to error out
423 right away, so call resolve just to be sure.
424
425 TODO: perhaps we can skip this, by walking the global font cache and
426 killing all of the contexts when we know that a given fontID is going
427 away...
428 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000429 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000430 return (FT_Error)-1;
431 }
432
433 FT_Error err = FT_Activate_Size(fFTSize);
434
435 if (err != 0) {
436 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
437 fFaceRec->fFontID, fScaleX, fScaleY, err));
438 fFTSize = NULL;
439 } else {
440 // seems we need to reset this every time (not sure why, but without it
441 // I get random italics from some other fFTSize)
442 FT_Set_Transform( fFace, &fMatrix22, NULL);
443 }
444 return err;
445}
446
447unsigned SkScalerContext_FreeType::generateGlyphCount() const {
448 return fFace->num_glyphs;
449}
450
451uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
452 return SkToU16(FT_Get_Char_Index( fFace, uni ));
453}
454
455static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
456 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000457 case SkMask::kHorizontalLCD_Format:
458 case SkMask::kVerticalLCD_Format:
459 SkASSERT(!"An LCD format should never be passed here");
460 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000461 case SkMask::kBW_Format:
462 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000463 case SkMask::kA8_Format:
464 default:
465 return FT_PIXEL_MODE_GRAY;
466 }
467}
468
reed@android.com8a1c16f2008-12-17 15:59:43 +0000469void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
470#ifdef FT_ADVANCES_H
471 /* unhinted and light hinted text have linearly scaled advances
472 * which are very cheap to compute with some font formats...
473 */
474 {
475 SkAutoMutexAcquire ac(gFTMutex);
476
477 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000478 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000479 return;
480 }
481
482 FT_Error error;
483 FT_Fixed advance;
484
485 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
486 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
487 &advance );
488 if (0 == error) {
489 glyph->fRsbDelta = 0;
490 glyph->fLsbDelta = 0;
491 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
492 glyph->fAdvanceY = 0;
493 return;
494 }
495 }
496#endif /* FT_ADVANCES_H */
497 /* otherwise, we need to load/hint the glyph, which is slower */
498 this->generateMetrics(glyph);
499 return;
500}
501
502void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
503 SkAutoMutexAcquire ac(gFTMutex);
504
505 glyph->fRsbDelta = 0;
506 glyph->fLsbDelta = 0;
507
508 FT_Error err;
509
510 if (this->setupSize()) {
511 goto ERROR;
512 }
513
514 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
515 if (err != 0) {
516 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
517 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
518 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000519 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000520 return;
521 }
522
523 switch ( fFace->glyph->format ) {
524 case FT_GLYPH_FORMAT_OUTLINE:
525 FT_BBox bbox;
526
527 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
528
agl@chromium.org309485b2009-07-21 17:41:32 +0000529 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000530 int dx = glyph->getSubXFixed() >> 10;
531 int dy = glyph->getSubYFixed() >> 10;
532 // negate dy since freetype-y-goes-up and skia-y-goes-down
533 bbox.xMin += dx;
534 bbox.yMin -= dy;
535 bbox.xMax += dx;
536 bbox.yMax -= dy;
537 }
538
539 bbox.xMin &= ~63;
540 bbox.yMin &= ~63;
541 bbox.xMax = (bbox.xMax + 63) & ~63;
542 bbox.yMax = (bbox.yMax + 63) & ~63;
543
544 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
545 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
546 glyph->fTop = -SkToS16(bbox.yMax >> 6);
547 glyph->fLeft = SkToS16(bbox.xMin >> 6);
548 break;
549
550 case FT_GLYPH_FORMAT_BITMAP:
551 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
552 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
553 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
554 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
555 break;
556
557 default:
558 SkASSERT(!"unknown glyph format");
559 goto ERROR;
560 }
561
agl@chromium.org309485b2009-07-21 17:41:32 +0000562 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000563 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
564 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
565 if (fRec.fFlags & kDevKernText_Flag) {
566 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
567 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
568 }
569 } else {
570 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
571 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
572 }
573
574#ifdef ENABLE_GLYPH_SPEW
575 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
576 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
577#endif
578}
579
reed@android.comf5493692009-07-22 19:21:01 +0000580#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000581namespace skia_freetype_support {
582// extern functions from SkFontHost_FreeType_Subpixel
583extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
584extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
585}
586
587using namespace skia_freetype_support;
588#endif
589
reed@android.com8a1c16f2008-12-17 15:59:43 +0000590void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
591 SkAutoMutexAcquire ac(gFTMutex);
592
593 FT_Error err;
594
595 if (this->setupSize()) {
596 goto ERROR;
597 }
598
599 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
600 if (err != 0) {
601 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
602 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
603 ERROR:
604 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
605 return;
606 }
607
agl@chromium.org309485b2009-07-21 17:41:32 +0000608 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
609 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
610
reed@android.com8a1c16f2008-12-17 15:59:43 +0000611 switch ( fFace->glyph->format ) {
612 case FT_GLYPH_FORMAT_OUTLINE: {
613 FT_Outline* outline = &fFace->glyph->outline;
614 FT_BBox bbox;
615 FT_Bitmap target;
616
617 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000618 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000619 dx = glyph.getSubXFixed() >> 10;
620 dy = glyph.getSubYFixed() >> 10;
621 // negate dy since freetype-y-goes-up and skia-y-goes-down
622 dy = -dy;
623 }
624 FT_Outline_Get_CBox(outline, &bbox);
625 /*
626 what we really want to do for subpixel is
627 offset(dx, dy)
628 compute_bounds
629 offset(bbox & !63)
630 but that is two calls to offset, so we do the following, which
631 achieves the same thing with only one offset call.
632 */
633 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
634 dy - ((bbox.yMin + dy) & ~63));
635
reed@android.comf5493692009-07-22 19:21:01 +0000636#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000637 if (lcdRenderMode) {
638 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
639 // we have to call FT_Render_Glyph and memcpy the image out.
640 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
641 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
642 FT_Render_Glyph(fFace->glyph, mode);
643
644 if (isVertical)
645 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
646 else
647 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
648
649 break;
650 }
651#endif
652
reed@android.com8a1c16f2008-12-17 15:59:43 +0000653 target.width = glyph.fWidth;
654 target.rows = glyph.fHeight;
655 target.pitch = glyph.rowBytes();
656 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
657 target.pixel_mode = compute_pixel_mode(
658 (SkMask::Format)fRec.fMaskFormat);
659 target.num_grays = 256;
660
661 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
662 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
663 } break;
664
665 case FT_GLYPH_FORMAT_BITMAP: {
666 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
667 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
668 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
669 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
670
671 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
672 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000673
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000674 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
675 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
676 unsigned dstRowBytes = glyph.rowBytes();
677 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
678 unsigned extraRowBytes = dstRowBytes - minRowBytes;
679
680 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
681 memcpy(dst, src, minRowBytes);
682 memset(dst + minRowBytes, 0, extraRowBytes);
683 src += srcRowBytes;
684 dst += dstRowBytes;
685 }
686 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
687 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
688 uint8_t byte = 0;
689 int bits = 0;
690 const uint8_t* src_row = src;
691 uint8_t* dst_row = dst;
692
693 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
694 if (!bits) {
695 byte = *src_row++;
696 bits = 8;
697 }
698
699 *dst_row++ = byte & 0x80 ? 0xff : 0;
700 bits--;
701 byte <<= 1;
702 }
703
704 src += fFace->glyph->bitmap.pitch;
705 dst += glyph.rowBytes();
706 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000707 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000708
709 if (lcdRenderMode)
710 glyph.expandA8ToLCD();
711
reed@android.com8a1c16f2008-12-17 15:59:43 +0000712 } break;
713
714 default:
715 SkASSERT(!"unknown glyph format");
716 goto ERROR;
717 }
718}
719
720///////////////////////////////////////////////////////////////////////////////
721
722#define ft2sk(x) SkFixedToScalar((x) << 10)
723
reed@android.com6f252972009-01-14 16:46:16 +0000724#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000725 #define CONST_PARAM const
726#else // older freetype doesn't use const here
727 #define CONST_PARAM
728#endif
729
730static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
731 SkPath* path = (SkPath*)ctx;
732 path->close(); // to close the previous contour (if any)
733 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
734 return 0;
735}
736
737static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
738 SkPath* path = (SkPath*)ctx;
739 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
740 return 0;
741}
742
743static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
744 void* ctx) {
745 SkPath* path = (SkPath*)ctx;
746 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
747 return 0;
748}
749
750static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
751 CONST_PARAM FT_Vector* pt2, void* ctx) {
752 SkPath* path = (SkPath*)ctx;
753 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
754 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
755 return 0;
756}
757
758void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
759 SkPath* path) {
760 SkAutoMutexAcquire ac(gFTMutex);
761
762 SkASSERT(&glyph && path);
763
764 if (this->setupSize()) {
765 path->reset();
766 return;
767 }
768
769 uint32_t flags = fLoadGlyphFlags;
770 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
771 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
772
773 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
774
775 if (err != 0) {
776 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
777 glyph.getGlyphID(fBaseGlyphCount), flags, err));
778 path->reset();
779 return;
780 }
781
782 FT_Outline_Funcs funcs;
783
784 funcs.move_to = move_proc;
785 funcs.line_to = line_proc;
786 funcs.conic_to = quad_proc;
787 funcs.cubic_to = cubic_proc;
788 funcs.shift = 0;
789 funcs.delta = 0;
790
791 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
792
793 if (err != 0) {
794 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
795 glyph.getGlyphID(fBaseGlyphCount), flags, err));
796 path->reset();
797 return;
798 }
799
800 path->close();
801}
802
803void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
804 SkPaint::FontMetrics* my) {
805 if (NULL == mx && NULL == my) {
806 return;
807 }
808
809 SkAutoMutexAcquire ac(gFTMutex);
810
811 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000812 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000813 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000814 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000815 }
816 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000817 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000818 }
819 return;
820 }
821
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000822 FT_Face face = fFace;
823 int upem = face->units_per_EM;
824 if (upem <= 0) {
825 goto ERROR;
826 }
827
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000828 SkPoint pts[6];
829 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000830 SkFixed scaleY = fScaleY;
831 SkFixed mxy = fMatrix22.xy;
832 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000833 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
834 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000835
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000836 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837 if (leading < 0) {
838 leading = 0;
839 }
840
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000841 // Try to get the OS/2 table from the font. This contains the specific
842 // average font width metrics which Windows uses.
843 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
844
reed@android.com8a1c16f2008-12-17 15:59:43 +0000845 ys[0] = -face->bbox.yMax;
846 ys[1] = -face->ascender;
847 ys[2] = -face->descender;
848 ys[3] = -face->bbox.yMin;
849 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000850 ys[5] = os2 ? os2->xAvgCharWidth : 0;
851
852 SkScalar x_height;
853 if (os2 && os2->sxHeight) {
854 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
855 } else {
856 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
857 if (x_glyph) {
858 FT_BBox bbox;
859 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
860 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
861 x_height = SkIntToScalar(bbox.yMax) / 64;
862 } else {
863 x_height = 0;
864 }
865 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000866
867 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000868 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000869 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
870 SkFixed x = SkFixedMul(mxy, y);
871 y = SkFixedMul(myy, y);
872 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
873 }
874
875 if (mx) {
876 mx->fTop = pts[0].fX;
877 mx->fAscent = pts[1].fX;
878 mx->fDescent = pts[2].fX;
879 mx->fBottom = pts[3].fX;
880 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000881 mx->fAvgCharWidth = pts[5].fX;
882 mx->fXMin = xmin;
883 mx->fXMax = xmax;
884 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000885 }
886 if (my) {
887 my->fTop = pts[0].fY;
888 my->fAscent = pts[1].fY;
889 my->fDescent = pts[2].fY;
890 my->fBottom = pts[3].fY;
891 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000892 my->fAvgCharWidth = pts[5].fY;
893 my->fXMin = xmin;
894 my->fXMax = xmax;
895 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000896 }
897}
898
899////////////////////////////////////////////////////////////////////////
900////////////////////////////////////////////////////////////////////////
901
902SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000903 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
904 if (!c->success()) {
905 SkDELETE(c);
906 c = NULL;
907 }
908 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000909}
910
911///////////////////////////////////////////////////////////////////////////////
912
913/* Export this so that other parts of our FonttHost port can make use of our
914 ability to extract the name+style from a stream, using FreeType's api.
915*/
916SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
917 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +0000918 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000919 name->set(NULL);
920 return SkTypeface::kNormal;
921 }
922
923 FT_Open_Args args;
924 memset(&args, 0, sizeof(args));
925
926 const void* memoryBase = stream->getMemoryBase();
927 FT_StreamRec streamRec;
928
929 if (NULL != memoryBase) {
930 args.flags = FT_OPEN_MEMORY;
931 args.memory_base = (const FT_Byte*)memoryBase;
932 args.memory_size = stream->getLength();
933 } else {
934 memset(&streamRec, 0, sizeof(streamRec));
935 streamRec.size = stream->read(NULL, 0);
936 streamRec.descriptor.pointer = stream;
937 streamRec.read = sk_stream_read;
938 streamRec.close = sk_stream_close;
939
940 args.flags = FT_OPEN_STREAM;
941 args.stream = &streamRec;
942 }
943
944 FT_Face face;
945 if (FT_Open_Face(library, &args, 0, &face)) {
946 FT_Done_FreeType(library);
947 name->set(NULL);
948 return SkTypeface::kNormal;
949 }
950
951 name->set(face->family_name);
952 int style = SkTypeface::kNormal;
953
954 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
955 style |= SkTypeface::kBold;
956 }
957 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
958 style |= SkTypeface::kItalic;
959 }
960
961 FT_Done_Face(face);
962 FT_Done_FreeType(library);
963 return (SkTypeface::Style)style;
964}