blob: b350202d6bc50ad118556b9879258609d072c174 [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) {
266 // collapse full->normaling hinting if we're not doing LCD
267 SkPaint::Hinting h = rec->getHinting();
268 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
269 rec->setHinting(SkPaint::kNormal_Hinting);
270 }
271}
272
reed@android.com8a1c16f2008-12-17 15:59:43 +0000273SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000274 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000275 SkAutoMutexAcquire ac(gFTMutex);
276
277 FT_Error err;
278
279 if (gFTCount == 0) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000280 const bool success = InitFreetype();
281 SkASSERT(success);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000282 }
283 ++gFTCount;
284
285 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000286 fFTSize = NULL;
287 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000288 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000289 if (NULL == fFaceRec) {
290 return;
291 }
292 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000293
294 // compute our factors from the record
295
296 SkMatrix m;
297
298 fRec.getSingleMatrix(&m);
299
300#ifdef DUMP_STRIKE_CREATION
301 SkString keyString;
302 SkFontHost::GetDescriptorKeyString(desc, &keyString);
303 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
304 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
305 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
306 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000307 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000308#endif
309
310 // now compute our scale factors
311 SkScalar sx = m.getScaleX();
312 SkScalar sy = m.getScaleY();
313
314 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
315 // sort of give up on hinting
316 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
317 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
318 sx = sy = SkScalarAve(sx, sy);
319
320 SkScalar inv = SkScalarInvert(sx);
321
322 // flip the skew elements to go from our Y-down system to FreeType's
323 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
324 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
325 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
326 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
327 } else {
328 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
329 fMatrix22.xy = fMatrix22.yx = 0;
330 }
331
332 fScaleX = SkScalarToFixed(sx);
333 fScaleY = SkScalarToFixed(sy);
334
335 // compute the flags we send to Load_Glyph
336 {
agl@chromium.org309485b2009-07-21 17:41:32 +0000337 FT_Int32 hintingFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000338
agl@chromium.org309485b2009-07-21 17:41:32 +0000339 switch (fRec.getHinting()) {
340 case SkPaint::kNo_Hinting:
341 hintingFlags = FT_LOAD_NO_HINTING;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000342 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000343 case SkPaint::kSlight_Hinting:
344 hintingFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
reed@android.com8a1c16f2008-12-17 15:59:43 +0000345 break;
agl@chromium.org309485b2009-07-21 17:41:32 +0000346 case SkPaint::kNormal_Hinting:
347 hintingFlags |= FT_LOAD_TARGET_NORMAL;
348 break;
349 case SkPaint::kFull_Hinting:
350 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
351 hintingFlags = FT_LOAD_TARGET_LCD;
352 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
353 hintingFlags = FT_LOAD_TARGET_LCD_V;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000354 break;
355 }
356
agl@chromium.org309485b2009-07-21 17:41:32 +0000357 fLoadGlyphFlags = hintingFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000358 }
359
360 // now create the FT_Size
361
362 {
363 FT_Error err;
364
365 err = FT_New_Size(fFace, &fFTSize);
366 if (err != 0) {
367 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
368 fFaceRec->fFontID, fScaleX, fScaleY, err));
369 fFace = NULL;
370 return;
371 }
372
373 err = FT_Activate_Size(fFTSize);
374 if (err != 0) {
375 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
376 fFaceRec->fFontID, fScaleX, fScaleY, err));
377 fFTSize = NULL;
378 }
379
380 err = FT_Set_Char_Size( fFace,
381 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
382 72, 72);
383 if (err != 0) {
384 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
385 fFaceRec->fFontID, fScaleX, fScaleY, err));
386 fFace = NULL;
387 return;
388 }
389
390 FT_Set_Transform( fFace, &fMatrix22, NULL);
391 }
392}
393
394SkScalerContext_FreeType::~SkScalerContext_FreeType() {
395 if (fFTSize != NULL) {
396 FT_Done_Size(fFTSize);
397 }
398
399 SkAutoMutexAcquire ac(gFTMutex);
400
401 if (fFace != NULL) {
402 unref_ft_face(fFace);
403 }
404 if (--gFTCount == 0) {
405// SkDEBUGF(("FT_Done_FreeType\n"));
406 FT_Done_FreeType(gFTLibrary);
407 SkDEBUGCODE(gFTLibrary = NULL;)
408 }
409}
410
411/* We call this before each use of the fFace, since we may be sharing
412 this face with other context (at different sizes).
413*/
414FT_Error SkScalerContext_FreeType::setupSize() {
415 /* In the off-chance that a font has been removed, we want to error out
416 right away, so call resolve just to be sure.
417
418 TODO: perhaps we can skip this, by walking the global font cache and
419 killing all of the contexts when we know that a given fontID is going
420 away...
421 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000422 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000423 return (FT_Error)-1;
424 }
425
426 FT_Error err = FT_Activate_Size(fFTSize);
427
428 if (err != 0) {
429 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
430 fFaceRec->fFontID, fScaleX, fScaleY, err));
431 fFTSize = NULL;
432 } else {
433 // seems we need to reset this every time (not sure why, but without it
434 // I get random italics from some other fFTSize)
435 FT_Set_Transform( fFace, &fMatrix22, NULL);
436 }
437 return err;
438}
439
440unsigned SkScalerContext_FreeType::generateGlyphCount() const {
441 return fFace->num_glyphs;
442}
443
444uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
445 return SkToU16(FT_Get_Char_Index( fFace, uni ));
446}
447
448static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
449 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000450 case SkMask::kHorizontalLCD_Format:
451 case SkMask::kVerticalLCD_Format:
452 SkASSERT(!"An LCD format should never be passed here");
453 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000454 case SkMask::kBW_Format:
455 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000456 case SkMask::kA8_Format:
457 default:
458 return FT_PIXEL_MODE_GRAY;
459 }
460}
461
reed@android.com8a1c16f2008-12-17 15:59:43 +0000462void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
463#ifdef FT_ADVANCES_H
464 /* unhinted and light hinted text have linearly scaled advances
465 * which are very cheap to compute with some font formats...
466 */
467 {
468 SkAutoMutexAcquire ac(gFTMutex);
469
470 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000471 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000472 return;
473 }
474
475 FT_Error error;
476 FT_Fixed advance;
477
478 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
479 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
480 &advance );
481 if (0 == error) {
482 glyph->fRsbDelta = 0;
483 glyph->fLsbDelta = 0;
484 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
485 glyph->fAdvanceY = 0;
486 return;
487 }
488 }
489#endif /* FT_ADVANCES_H */
490 /* otherwise, we need to load/hint the glyph, which is slower */
491 this->generateMetrics(glyph);
492 return;
493}
494
495void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
496 SkAutoMutexAcquire ac(gFTMutex);
497
498 glyph->fRsbDelta = 0;
499 glyph->fLsbDelta = 0;
500
501 FT_Error err;
502
503 if (this->setupSize()) {
504 goto ERROR;
505 }
506
507 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
508 if (err != 0) {
509 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
510 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
511 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000512 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000513 return;
514 }
515
516 switch ( fFace->glyph->format ) {
517 case FT_GLYPH_FORMAT_OUTLINE:
518 FT_BBox bbox;
519
520 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
521
agl@chromium.org309485b2009-07-21 17:41:32 +0000522 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000523 int dx = glyph->getSubXFixed() >> 10;
524 int dy = glyph->getSubYFixed() >> 10;
525 // negate dy since freetype-y-goes-up and skia-y-goes-down
526 bbox.xMin += dx;
527 bbox.yMin -= dy;
528 bbox.xMax += dx;
529 bbox.yMax -= dy;
530 }
531
532 bbox.xMin &= ~63;
533 bbox.yMin &= ~63;
534 bbox.xMax = (bbox.xMax + 63) & ~63;
535 bbox.yMax = (bbox.yMax + 63) & ~63;
536
537 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
538 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
539 glyph->fTop = -SkToS16(bbox.yMax >> 6);
540 glyph->fLeft = SkToS16(bbox.xMin >> 6);
541 break;
542
543 case FT_GLYPH_FORMAT_BITMAP:
544 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
545 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
546 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
547 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
548 break;
549
550 default:
551 SkASSERT(!"unknown glyph format");
552 goto ERROR;
553 }
554
agl@chromium.org309485b2009-07-21 17:41:32 +0000555 if (!fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000556 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
557 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
558 if (fRec.fFlags & kDevKernText_Flag) {
559 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
560 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
561 }
562 } else {
563 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
564 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
565 }
566
567#ifdef ENABLE_GLYPH_SPEW
568 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
569 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
570#endif
571}
572
reed@android.comf5493692009-07-22 19:21:01 +0000573#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000574namespace skia_freetype_support {
575// extern functions from SkFontHost_FreeType_Subpixel
576extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
577extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
578}
579
580using namespace skia_freetype_support;
581#endif
582
reed@android.com8a1c16f2008-12-17 15:59:43 +0000583void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
584 SkAutoMutexAcquire ac(gFTMutex);
585
586 FT_Error err;
587
588 if (this->setupSize()) {
589 goto ERROR;
590 }
591
592 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
593 if (err != 0) {
594 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
595 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
596 ERROR:
597 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
598 return;
599 }
600
agl@chromium.org309485b2009-07-21 17:41:32 +0000601 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
602 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
603
reed@android.com8a1c16f2008-12-17 15:59:43 +0000604 switch ( fFace->glyph->format ) {
605 case FT_GLYPH_FORMAT_OUTLINE: {
606 FT_Outline* outline = &fFace->glyph->outline;
607 FT_BBox bbox;
608 FT_Bitmap target;
609
610 int dx = 0, dy = 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000611 if (fRec.fSubpixelPositioning) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000612 dx = glyph.getSubXFixed() >> 10;
613 dy = glyph.getSubYFixed() >> 10;
614 // negate dy since freetype-y-goes-up and skia-y-goes-down
615 dy = -dy;
616 }
617 FT_Outline_Get_CBox(outline, &bbox);
618 /*
619 what we really want to do for subpixel is
620 offset(dx, dy)
621 compute_bounds
622 offset(bbox & !63)
623 but that is two calls to offset, so we do the following, which
624 achieves the same thing with only one offset call.
625 */
626 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
627 dy - ((bbox.yMin + dy) & ~63));
628
reed@android.comf5493692009-07-22 19:21:01 +0000629#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000630 if (lcdRenderMode) {
631 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
632 // we have to call FT_Render_Glyph and memcpy the image out.
633 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
634 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
635 FT_Render_Glyph(fFace->glyph, mode);
636
637 if (isVertical)
638 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
639 else
640 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
641
642 break;
643 }
644#endif
645
reed@android.com8a1c16f2008-12-17 15:59:43 +0000646 target.width = glyph.fWidth;
647 target.rows = glyph.fHeight;
648 target.pitch = glyph.rowBytes();
649 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
650 target.pixel_mode = compute_pixel_mode(
651 (SkMask::Format)fRec.fMaskFormat);
652 target.num_grays = 256;
653
654 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
655 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
656 } break;
657
658 case FT_GLYPH_FORMAT_BITMAP: {
659 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
660 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
661 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
662 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
663
664 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
665 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000666
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000667 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
668 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
669 unsigned dstRowBytes = glyph.rowBytes();
670 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
671 unsigned extraRowBytes = dstRowBytes - minRowBytes;
672
673 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
674 memcpy(dst, src, minRowBytes);
675 memset(dst + minRowBytes, 0, extraRowBytes);
676 src += srcRowBytes;
677 dst += dstRowBytes;
678 }
679 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
680 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
681 uint8_t byte = 0;
682 int bits = 0;
683 const uint8_t* src_row = src;
684 uint8_t* dst_row = dst;
685
686 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
687 if (!bits) {
688 byte = *src_row++;
689 bits = 8;
690 }
691
692 *dst_row++ = byte & 0x80 ? 0xff : 0;
693 bits--;
694 byte <<= 1;
695 }
696
697 src += fFace->glyph->bitmap.pitch;
698 dst += glyph.rowBytes();
699 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000700 }
agl@chromium.org309485b2009-07-21 17:41:32 +0000701
702 if (lcdRenderMode)
703 glyph.expandA8ToLCD();
704
reed@android.com8a1c16f2008-12-17 15:59:43 +0000705 } break;
706
707 default:
708 SkASSERT(!"unknown glyph format");
709 goto ERROR;
710 }
711}
712
713///////////////////////////////////////////////////////////////////////////////
714
715#define ft2sk(x) SkFixedToScalar((x) << 10)
716
reed@android.com6f252972009-01-14 16:46:16 +0000717#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +0000718 #define CONST_PARAM const
719#else // older freetype doesn't use const here
720 #define CONST_PARAM
721#endif
722
723static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
724 SkPath* path = (SkPath*)ctx;
725 path->close(); // to close the previous contour (if any)
726 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
727 return 0;
728}
729
730static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
731 SkPath* path = (SkPath*)ctx;
732 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
733 return 0;
734}
735
736static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
737 void* ctx) {
738 SkPath* path = (SkPath*)ctx;
739 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
740 return 0;
741}
742
743static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
744 CONST_PARAM FT_Vector* pt2, void* ctx) {
745 SkPath* path = (SkPath*)ctx;
746 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
747 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
748 return 0;
749}
750
751void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
752 SkPath* path) {
753 SkAutoMutexAcquire ac(gFTMutex);
754
755 SkASSERT(&glyph && path);
756
757 if (this->setupSize()) {
758 path->reset();
759 return;
760 }
761
762 uint32_t flags = fLoadGlyphFlags;
763 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
764 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
765
766 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
767
768 if (err != 0) {
769 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
770 glyph.getGlyphID(fBaseGlyphCount), flags, err));
771 path->reset();
772 return;
773 }
774
775 FT_Outline_Funcs funcs;
776
777 funcs.move_to = move_proc;
778 funcs.line_to = line_proc;
779 funcs.conic_to = quad_proc;
780 funcs.cubic_to = cubic_proc;
781 funcs.shift = 0;
782 funcs.delta = 0;
783
784 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
785
786 if (err != 0) {
787 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
788 glyph.getGlyphID(fBaseGlyphCount), flags, err));
789 path->reset();
790 return;
791 }
792
793 path->close();
794}
795
796void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
797 SkPaint::FontMetrics* my) {
798 if (NULL == mx && NULL == my) {
799 return;
800 }
801
802 SkAutoMutexAcquire ac(gFTMutex);
803
804 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000805 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +0000806 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +0000807 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000808 }
809 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +0000810 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000811 }
812 return;
813 }
814
reed@android.coma8a8b8b2009-05-04 15:00:11 +0000815 FT_Face face = fFace;
816 int upem = face->units_per_EM;
817 if (upem <= 0) {
818 goto ERROR;
819 }
820
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000821 SkPoint pts[6];
822 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +0000823 SkFixed scaleY = fScaleY;
824 SkFixed mxy = fMatrix22.xy;
825 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000826 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
827 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000828
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000829 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000830 if (leading < 0) {
831 leading = 0;
832 }
833
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000834 // Try to get the OS/2 table from the font. This contains the specific
835 // average font width metrics which Windows uses.
836 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
837
reed@android.com8a1c16f2008-12-17 15:59:43 +0000838 ys[0] = -face->bbox.yMax;
839 ys[1] = -face->ascender;
840 ys[2] = -face->descender;
841 ys[3] = -face->bbox.yMin;
842 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000843 ys[5] = os2 ? os2->xAvgCharWidth : 0;
844
845 SkScalar x_height;
846 if (os2 && os2->sxHeight) {
847 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
848 } else {
849 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
850 if (x_glyph) {
851 FT_BBox bbox;
852 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
853 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
854 x_height = SkIntToScalar(bbox.yMax) / 64;
855 } else {
856 x_height = 0;
857 }
858 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000859
860 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000861 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000862 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
863 SkFixed x = SkFixedMul(mxy, y);
864 y = SkFixedMul(myy, y);
865 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
866 }
867
868 if (mx) {
869 mx->fTop = pts[0].fX;
870 mx->fAscent = pts[1].fX;
871 mx->fDescent = pts[2].fX;
872 mx->fBottom = pts[3].fX;
873 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000874 mx->fAvgCharWidth = pts[5].fX;
875 mx->fXMin = xmin;
876 mx->fXMax = xmax;
877 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000878 }
879 if (my) {
880 my->fTop = pts[0].fY;
881 my->fAscent = pts[1].fY;
882 my->fDescent = pts[2].fY;
883 my->fBottom = pts[3].fY;
884 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000885 my->fAvgCharWidth = pts[5].fY;
886 my->fXMin = xmin;
887 my->fXMax = xmax;
888 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000889 }
890}
891
892////////////////////////////////////////////////////////////////////////
893////////////////////////////////////////////////////////////////////////
894
895SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +0000896 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
897 if (!c->success()) {
898 SkDELETE(c);
899 c = NULL;
900 }
901 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000902}
903
904///////////////////////////////////////////////////////////////////////////////
905
906/* Export this so that other parts of our FonttHost port can make use of our
907 ability to extract the name+style from a stream, using FreeType's api.
908*/
909SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
910 FT_Library library;
agl@chromium.org309485b2009-07-21 17:41:32 +0000911 if (!InitFreetype()) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000912 name->set(NULL);
913 return SkTypeface::kNormal;
914 }
915
916 FT_Open_Args args;
917 memset(&args, 0, sizeof(args));
918
919 const void* memoryBase = stream->getMemoryBase();
920 FT_StreamRec streamRec;
921
922 if (NULL != memoryBase) {
923 args.flags = FT_OPEN_MEMORY;
924 args.memory_base = (const FT_Byte*)memoryBase;
925 args.memory_size = stream->getLength();
926 } else {
927 memset(&streamRec, 0, sizeof(streamRec));
928 streamRec.size = stream->read(NULL, 0);
929 streamRec.descriptor.pointer = stream;
930 streamRec.read = sk_stream_read;
931 streamRec.close = sk_stream_close;
932
933 args.flags = FT_OPEN_STREAM;
934 args.stream = &streamRec;
935 }
936
937 FT_Face face;
938 if (FT_Open_Face(library, &args, 0, &face)) {
939 FT_Done_FreeType(library);
940 name->set(NULL);
941 return SkTypeface::kNormal;
942 }
943
944 name->set(face->family_name);
945 int style = SkTypeface::kNormal;
946
947 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
948 style |= SkTypeface::kBold;
949 }
950 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
951 style |= SkTypeface::kItalic;
952 }
953
954 FT_Done_Face(face);
955 FT_Done_FreeType(library);
956 return (SkTypeface::Style)style;
957}