blob: fd6af07ba46f7772c98ee5b061dca790a3e4e3e5 [file] [log] [blame]
reed@android.com8a1c16f2008-12-17 15:59:43 +00001/* libs/graphics/ports/SkFontHost_FreeType.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
reed@android.com8a1c16f2008-12-17 15:59:43 +000018#include "SkBitmap.h"
19#include "SkCanvas.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000020#include "SkColorPriv.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000021#include "SkDescriptor.h"
22#include "SkFDot6.h"
23#include "SkFontHost.h"
24#include "SkMask.h"
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +000025#include "SkAdvancedTypefaceMetrics.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000026#include "SkScalerContext.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000027#include "SkStream.h"
28#include "SkString.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000029#include "SkTemplates.h"
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000030#include "SkThread.h"
reed@android.com8a1c16f2008-12-17 15:59:43 +000031
32#include <ft2build.h>
33#include FT_FREETYPE_H
34#include FT_OUTLINE_H
35#include FT_SIZES_H
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000036#include FT_TRUETYPE_TABLES_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000037#include FT_TYPE1_TABLES_H
agl@chromium.orge76073b2010-06-04 20:31:17 +000038#include FT_BITMAP_H
agl@chromium.org36bb6972010-06-04 20:57:16 +000039// In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file.
40#include FT_SYNTHESIS_H
vandebo@chromium.org2a22e102011-01-25 21:01:34 +000041#include FT_XFREE86_H
agl@chromium.org309485b2009-07-21 17:41:32 +000042
reed@android.comf5493692009-07-22 19:21:01 +000043#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +000044#include FT_LCD_FILTER_H
45#endif
46
reed@android.com8a1c16f2008-12-17 15:59:43 +000047#ifdef FT_ADVANCES_H
48#include FT_ADVANCES_H
49#endif
50
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000051#if 0
52// Also include the files by name for build tools which require this.
53#include <freetype/freetype.h>
54#include <freetype/ftoutln.h>
55#include <freetype/ftsizes.h>
56#include <freetype/tttables.h>
57#include <freetype/ftadvanc.h>
agl@chromium.org309485b2009-07-21 17:41:32 +000058#include <freetype/ftlcdfil.h>
agl@chromium.orge76073b2010-06-04 20:31:17 +000059#include <freetype/ftbitmap.h>
agl@chromium.org36bb6972010-06-04 20:57:16 +000060#include <freetype/ftsynth.h>
agl@chromium.orgcc3096b2009-04-22 22:09:04 +000061#endif
62
reed@android.com8a1c16f2008-12-17 15:59:43 +000063//#define ENABLE_GLYPH_SPEW // for tracing calls
64//#define DUMP_STRIKE_CREATION
65
66#ifdef SK_DEBUG
67 #define SkASSERT_CONTINUE(pred) \
68 do { \
69 if (!(pred)) \
70 SkDebugf("file %s:%d: assert failed '" #pred "'\n", __FILE__, __LINE__); \
71 } while (false)
72#else
73 #define SkASSERT_CONTINUE(pred)
74#endif
75
76//////////////////////////////////////////////////////////////////////////
77
78struct SkFaceRec;
79
80static SkMutex gFTMutex;
81static int gFTCount;
82static FT_Library gFTLibrary;
83static SkFaceRec* gFaceRecHead;
agl@chromium.orgf18d8762009-07-28 18:38:08 +000084static bool gLCDSupportValid; // true iff |gLCDSupport| has been set.
85static bool gLCDSupport; // true iff LCD is supported by the runtime.
reed@android.com8a1c16f2008-12-17 15:59:43 +000086
87/////////////////////////////////////////////////////////////////////////
88
agl@chromium.orge76073b2010-06-04 20:31:17 +000089// See http://freetype.sourceforge.net/freetype2/docs/reference/ft2-bitmap_handling.html#FT_Bitmap_Embolden
90// This value was chosen by eyeballing the result in Firefox and trying to match it.
91static const FT_Pos kBitmapEmboldenStrength = 1 << 6;
92
agl@chromium.org309485b2009-07-21 17:41:32 +000093static bool
94InitFreetype() {
95 FT_Error err = FT_Init_FreeType(&gFTLibrary);
96 if (err)
97 return false;
98
reed@android.comf5493692009-07-22 19:21:01 +000099#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000100 // Setup LCD filtering. This reduces colour fringes for LCD rendered
101 // glyphs.
102 err = FT_Library_SetLcdFilter(gFTLibrary, FT_LCD_FILTER_DEFAULT);
agl@chromium.orgf18d8762009-07-28 18:38:08 +0000103 gLCDSupport = err == 0;
agl@chromium.org309485b2009-07-21 17:41:32 +0000104#endif
reed@android.com61608aa2009-07-31 14:52:54 +0000105 gLCDSupportValid = true;
agl@chromium.org309485b2009-07-21 17:41:32 +0000106
107 return true;
108}
109
reed@android.com8a1c16f2008-12-17 15:59:43 +0000110class SkScalerContext_FreeType : public SkScalerContext {
111public:
112 SkScalerContext_FreeType(const SkDescriptor* desc);
113 virtual ~SkScalerContext_FreeType();
agl@chromium.orgcc3096b2009-04-22 22:09:04 +0000114
reed@android.com62900b42009-02-11 15:07:19 +0000115 bool success() const {
reed@android.coma0f5d152009-06-22 17:38:10 +0000116 return fFaceRec != NULL &&
117 fFTSize != NULL &&
118 fFace != NULL;
reed@android.com62900b42009-02-11 15:07:19 +0000119 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000120
121protected:
122 virtual unsigned generateGlyphCount() const;
123 virtual uint16_t generateCharToGlyph(SkUnichar uni);
124 virtual void generateAdvance(SkGlyph* glyph);
125 virtual void generateMetrics(SkGlyph* glyph);
126 virtual void generateImage(const SkGlyph& glyph);
127 virtual void generatePath(const SkGlyph& glyph, SkPath* path);
128 virtual void generateFontMetrics(SkPaint::FontMetrics* mx,
129 SkPaint::FontMetrics* my);
reed@android.com9d3a9852010-01-08 14:07:42 +0000130 virtual SkUnichar generateGlyphToChar(uint16_t glyph);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000131
132private:
133 SkFaceRec* fFaceRec;
134 FT_Face fFace; // reference to shared face in gFaceRecHead
135 FT_Size fFTSize; // our own copy
136 SkFixed fScaleX, fScaleY;
137 FT_Matrix fMatrix22;
138 uint32_t fLoadGlyphFlags;
139
140 FT_Error setupSize();
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000141 void emboldenOutline(FT_Outline* outline);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000142};
143
144///////////////////////////////////////////////////////////////////////////
145///////////////////////////////////////////////////////////////////////////
146
147#include "SkStream.h"
148
149struct SkFaceRec {
150 SkFaceRec* fNext;
151 FT_Face fFace;
152 FT_StreamRec fFTStream;
153 SkStream* fSkStream;
154 uint32_t fRefCnt;
155 uint32_t fFontID;
156
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000157 // assumes ownership of the stream, will call unref() when its done
reed@android.com8a1c16f2008-12-17 15:59:43 +0000158 SkFaceRec(SkStream* strm, uint32_t fontID);
159 ~SkFaceRec() {
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000160 fSkStream->unref();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000161 }
162};
163
164extern "C" {
165 static unsigned long sk_stream_read(FT_Stream stream,
166 unsigned long offset,
167 unsigned char* buffer,
168 unsigned long count ) {
169 SkStream* str = (SkStream*)stream->descriptor.pointer;
170
171 if (count) {
172 if (!str->rewind()) {
173 return 0;
174 } else {
175 unsigned long ret;
176 if (offset) {
177 ret = str->read(NULL, offset);
178 if (ret != offset) {
179 return 0;
180 }
181 }
182 ret = str->read(buffer, count);
183 if (ret != count) {
184 return 0;
185 }
186 count = ret;
187 }
188 }
189 return count;
190 }
191
192 static void sk_stream_close( FT_Stream stream) {}
193}
194
195SkFaceRec::SkFaceRec(SkStream* strm, uint32_t fontID)
196 : fSkStream(strm), fFontID(fontID) {
197// SkDEBUGF(("SkFaceRec: opening %s (%p)\n", key.c_str(), strm));
198
reed@android.com4516f472009-06-29 16:25:36 +0000199 sk_bzero(&fFTStream, sizeof(fFTStream));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000200 fFTStream.size = fSkStream->getLength();
201 fFTStream.descriptor.pointer = fSkStream;
202 fFTStream.read = sk_stream_read;
203 fFTStream.close = sk_stream_close;
204}
205
reed@android.com62900b42009-02-11 15:07:19 +0000206// Will return 0 on failure
reed@android.com8a1c16f2008-12-17 15:59:43 +0000207static SkFaceRec* ref_ft_face(uint32_t fontID) {
208 SkFaceRec* rec = gFaceRecHead;
209 while (rec) {
210 if (rec->fFontID == fontID) {
211 SkASSERT(rec->fFace);
212 rec->fRefCnt += 1;
213 return rec;
214 }
215 rec = rec->fNext;
216 }
217
218 SkStream* strm = SkFontHost::OpenStream(fontID);
219 if (NULL == strm) {
220 SkDEBUGF(("SkFontHost::OpenStream failed opening %x\n", fontID));
reed@android.com8a1c16f2008-12-17 15:59:43 +0000221 return 0;
222 }
223
224 // this passes ownership of strm to the rec
225 rec = SkNEW_ARGS(SkFaceRec, (strm, fontID));
226
227 FT_Open_Args args;
228 memset(&args, 0, sizeof(args));
229 const void* memoryBase = strm->getMemoryBase();
230
231 if (NULL != memoryBase) {
232//printf("mmap(%s)\n", keyString.c_str());
233 args.flags = FT_OPEN_MEMORY;
234 args.memory_base = (const FT_Byte*)memoryBase;
235 args.memory_size = strm->getLength();
236 } else {
237//printf("fopen(%s)\n", keyString.c_str());
238 args.flags = FT_OPEN_STREAM;
239 args.stream = &rec->fFTStream;
240 }
241
agl@chromium.org61a678a2010-08-06 18:08:18 +0000242 int face_index;
243 int length = SkFontHost::GetFileName(fontID, NULL, 0, &face_index);
244 FT_Error err = FT_Open_Face(gFTLibrary, &args, length ? face_index : 0,
245 &rec->fFace);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000246
247 if (err) { // bad filename, try the default font
248 fprintf(stderr, "ERROR: unable to open font '%x'\n", fontID);
249 SkDELETE(rec);
reed@android.com8a1c16f2008-12-17 15:59:43 +0000250 return 0;
251 } else {
252 SkASSERT(rec->fFace);
253 //fprintf(stderr, "Opened font '%s'\n", filename.c_str());
254 rec->fNext = gFaceRecHead;
255 gFaceRecHead = rec;
256 rec->fRefCnt = 1;
257 return rec;
258 }
259}
260
261static void unref_ft_face(FT_Face face) {
262 SkFaceRec* rec = gFaceRecHead;
263 SkFaceRec* prev = NULL;
264 while (rec) {
265 SkFaceRec* next = rec->fNext;
266 if (rec->fFace == face) {
267 if (--rec->fRefCnt == 0) {
268 if (prev) {
269 prev->fNext = next;
270 } else {
271 gFaceRecHead = next;
272 }
273 FT_Done_Face(face);
274 SkDELETE(rec);
275 }
276 return;
277 }
278 prev = rec;
279 rec = next;
280 }
281 SkASSERT("shouldn't get here, face not in list");
282}
283
284///////////////////////////////////////////////////////////////////////////
285
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000286// Work around for old versions of freetype.
287static FT_Error getAdvances(FT_Face face, FT_UInt start, FT_UInt count,
288 FT_Int32 loadFlags, FT_Fixed* advances) {
289#ifdef FT_ADVANCES_H
290 return FT_Get_Advances(face, start, count, loadFlags, advances);
291#else
292 if (!face || start >= face->num_glyphs ||
293 start + count > face->num_glyphs || loadFlags != FT_LOAD_NO_SCALE) {
294 return 6; // "Invalid argument."
295 }
296 if (count == 0)
297 return 0;
298
299 for (int i = 0; i < count; i++) {
300 FT_Error err = FT_Load_Glyph(face, start + i, FT_LOAD_NO_SCALE);
301 if (err)
302 return err;
303 advances[i] = face->glyph->advance.x;
304 }
305
306 return 0;
307#endif
308}
309
310static bool canEmbed(FT_Face face) {
311#ifdef FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING
312 FT_UShort fsType = FT_Get_FSType_Flags(face);
313 return (fsType & (FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING |
314 FT_FSTYPE_BITMAP_EMBEDDING_ONLY)) == 0;
315#else
316 // No embedding is 0x2 and bitmap embedding only is 0x200.
317 TT_OS2* os2_table;
318 if ((os2_table = (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
319 return (os2_table->fsType & 0x202) == 0;
320 }
321 return false; // We tried, fail safe.
322#endif
323}
324
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000325static bool GetLetterCBox(FT_Face face, char letter, FT_BBox* bbox) {
326 const FT_UInt glyph_id = FT_Get_Char_Index(face, letter);
327 if (!glyph_id)
328 return false;
329 FT_Load_Glyph(face, glyph_id, FT_LOAD_NO_SCALE);
330 FT_Outline_Get_CBox(&face->glyph->outline, bbox);
331 return true;
332}
333
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000334static int16_t getWidthAdvance(FT_Face face, int gId) {
335 FT_Fixed advance = 0;
336 SkAssertResult(getAdvances(face, gId, 1, FT_LOAD_NO_SCALE, &advance) == 0);
337 return advance;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000338}
339
340template <typename Data>
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000341static void resetRange(SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* range,
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000342 int startId) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000343 range->fStartId = startId;
344 range->fAdvance.setCount(0);
345}
346
347template <typename Data>
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000348static SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* appendRange(
349 SkTScopedPtr<SkAdvancedTypefaceMetrics::AdvanceMetric<Data> >* nextSlot,
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000350 int startId) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000351 nextSlot->reset(new SkAdvancedTypefaceMetrics::AdvanceMetric<Data>);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000352 resetRange(nextSlot->get(), startId);
353 return nextSlot->get();
354}
355
356template <typename Data>
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000357static void finishRange(
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000358 SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* range,
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000359 int endId,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000360 typename SkAdvancedTypefaceMetrics::AdvanceMetric<Data>::MetricType
361 type) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000362 range->fEndId = endId;
363 range->fType = type;
364 int newLength;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000365 if (type == SkAdvancedTypefaceMetrics::AdvanceMetric<Data>::kRange)
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000366 newLength = endId - range->fStartId + 1;
367 else
368 newLength = 1;
369 SkASSERT(range->fAdvance.count() >= newLength);
370 range->fAdvance.setCount(newLength);
371}
372
373template <typename Data>
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000374static SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* getAdvanceData(
375 FT_Face face, Data (*getAdvance)(FT_Face face, int gId)) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000376 // Assuming that an ASCII representation of a width or a glyph id is,
377 // on average, 3 characters long gives the following cut offs for
378 // using different range types:
379 // When currently in a range
380 // - Removing 4 0's is a win
381 // - Removing 5 repeats is a win
382 // When not currently in a range
383 // - Removing 1 0 is a win
384 // - Removing 3 repeats is a win
385
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000386 SkTScopedPtr<SkAdvancedTypefaceMetrics::AdvanceMetric<Data> > result;
387 SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* curRange;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000388 curRange = appendRange(&result, 0);
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000389 Data lastAdvance = SHRT_MIN;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000390 int repeats = 0;
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000391 for (int gId = 0; gId < face->num_glyphs; gId++) {
392 Data advance = getAdvance(face, gId);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000393 if (advance == lastAdvance) {
394 repeats++;
395 } else if (curRange->fAdvance.count() == repeats + 1) {
396 if (lastAdvance == 0 && repeats >= 0) {
397 resetRange(curRange, gId);
398 } else if (repeats >= 2) {
399 finishRange(curRange, gId - 1,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000400 SkAdvancedTypefaceMetrics::WidthRange::kRun);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000401 curRange = appendRange(&curRange->fNext, gId);
402 }
403 repeats = 0;
404 } else {
405 if (lastAdvance == 0 && repeats >= 3) {
406 finishRange(curRange, gId - repeats - 2,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000407 SkAdvancedTypefaceMetrics::WidthRange::kRange);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000408 curRange = appendRange(&curRange->fNext, gId);
409 } else if (repeats >= 4) {
410 finishRange(curRange, gId - repeats - 2,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000411 SkAdvancedTypefaceMetrics::WidthRange::kRange);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000412 curRange = appendRange(&curRange->fNext, gId - repeats - 1);
413 curRange->fAdvance.append(1, &lastAdvance);
414 finishRange(curRange, gId - 1,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000415 SkAdvancedTypefaceMetrics::WidthRange::kRun);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000416 curRange = appendRange(&curRange->fNext, gId);
417 }
418 repeats = 0;
419 }
420 curRange->fAdvance.append(1, &advance);
421 lastAdvance = advance;
422 }
423 finishRange(curRange, face->num_glyphs - 1,
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000424 SkAdvancedTypefaceMetrics::WidthRange::kRange);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000425 return result.release();
426}
427
428// static
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000429SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
430 uint32_t fontID, bool perGlyphInfo) {
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000431 SkAutoMutexAcquire ac(gFTMutex);
432 FT_Library libInit = NULL;
433 if (gFTCount == 0) {
434 if (!InitFreetype())
435 sk_throw();
436 libInit = gFTLibrary;
437 }
438 SkAutoTCallIProc<struct FT_LibraryRec_, FT_Done_FreeType> ftLib(libInit);
439 SkFaceRec* rec = ref_ft_face(fontID);
440 if (NULL == rec)
441 return NULL;
442 FT_Face face = rec->fFace;
443
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000444 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
445 info->fFontName.set(FT_Get_Postscript_Name(face));
446 info->fMultiMaster = FT_HAS_MULTIPLE_MASTERS(face);
447 info->fLastGlyphID = face->num_glyphs - 1;
448 info->fEmSize = 1000;
449
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000450 bool cid = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000451 const char* fontType = FT_Get_X11_Font_Format(face);
vandebo@chromium.org16be6b82011-01-28 21:28:56 +0000452 if (!canEmbed(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000453 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454 } else if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000455 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000456 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000457 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000458 cid = true;
459 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000460 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000461 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000462 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000463 cid = true;
464 TT_Header* ttHeader;
465 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
466 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000467 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000468 }
469 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000470
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000471 if (info->fType == SkAdvancedTypefaceMetrics::kOther_Font ||
472 info->fType == SkAdvancedTypefaceMetrics::kNotEmbeddable_Font ||
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000473 !FT_IS_SCALABLE(face)) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000474 perGlyphInfo = false;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000475 }
476
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000477 SkASSERT(!FT_HAS_VERTICAL(face));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000478#ifdef FT_IS_CID_KEYED
479 SkASSERT(FT_IS_CID_KEYED(face) ==
480 (info->fType == SkAdvancedTypefaceMetrics::kType1CID_Font));
481#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000482
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000483 info->fStyle = 0;
484 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000485 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000486 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000487 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000488 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
489 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000490 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
491
492 PS_FontInfoRec ps_info;
493 TT_Postscript* tt_info;
494 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
495 info->fItalicAngle = ps_info.italic_angle;
496 } else if ((tt_info =
497 (TT_Postscript*)FT_Get_Sfnt_Table(face,
498 ft_sfnt_post)) != NULL) {
499 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
500 } else {
501 info->fItalicAngle = 0;
502 }
503
504 info->fAscent = face->ascender;
505 info->fDescent = face->descender;
506
507 // Figure out a good guess for StemV - Min width of i, I, !, 1.
508 // This probably isn't very good with an italic font.
509 int16_t min_width = SHRT_MAX;
510 char stem_chars[] = {'i', 'I', '!', '1'};
511 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
512 FT_BBox bbox;
513 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
514 int16_t width = bbox.xMax - bbox.xMin;
515 if (width > 0 && width < min_width) {
516 min_width = width;
517 info->fStemV = min_width;
518 }
519 }
520 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521
522 TT_PCLT* pclt_info;
523 TT_OS2* os2_table;
524 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
525 info->fCapHeight = pclt_info->CapHeight;
526 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
527 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000528 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000529 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000530 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000531 } else if ((os2_table =
532 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
533 info->fCapHeight = os2_table->sCapHeight;
534 } else {
535 // Figure out a good guess for CapHeight: average the height of M and X.
536 FT_BBox m_bbox, x_bbox;
537 bool got_m, got_x;
538 got_m = GetLetterCBox(face, 'M', &m_bbox);
539 got_x = GetLetterCBox(face, 'X', &x_bbox);
540 if (got_m && got_x) {
541 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
542 x_bbox.yMin) / 2;
543 } else if (got_m && !got_x) {
544 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
545 } else if (!got_m && got_x) {
546 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
547 }
548 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000549
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000550 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
551 face->bbox.xMax, face->bbox.yMin);
552
553 if (perGlyphInfo) {
554 if (FT_IS_FIXED_WIDTH(face)) {
555 appendRange(&info->fGlyphWidths, 0);
556 int16_t advance = face->max_advance_width;
557 info->fGlyphWidths->fAdvance.append(1, &advance);
558 finishRange(info->fGlyphWidths.get(), 0,
559 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
560 } else if(!cid) {
561 appendRange(&info->fGlyphWidths, 0);
562 // So as to not blow out the stack, get advances in batches.
563 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
564 FT_Fixed advances[128];
565 int advanceCount = 128;
566 if (gID + advanceCount > face->num_glyphs)
567 advanceCount = face->num_glyphs - gID + 1;
568 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
569 advances);
570 for (int i = 0; i < advanceCount; i++) {
571 int16_t advance = advances[gID + i];
572 info->fGlyphWidths->fAdvance.append(1, &advance);
573 }
574 }
575 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
576 SkAdvancedTypefaceMetrics::WidthRange::kRange);
577 } else {
578 info->fGlyphWidths.reset(getAdvanceData(face, &getWidthAdvance));
579 }
580
581 if (info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
582 // Postscript fonts may contain more than 255 glyphs, so we end up
583 // using multiple font descriptions with a glyph ordering. Record
584 // the name of each glyph.
585 info->fGlyphNames.reset(
586 new SkAutoTArray<SkString>(face->num_glyphs));
587 for (int gID = 0; gID < face->num_glyphs; gID++) {
588 char glyphName[128]; // PS limit for names is 127 bytes.
589 FT_Get_Glyph_Name(face, gID, glyphName, 128);
590 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000591 }
592 }
593 }
594
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000595 unref_ft_face(face);
596 return info;
597}
reed@google.com618ef5e2011-01-26 22:10:41 +0000598///////////////////////////////////////////////////////////////////////////
599
600void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
601 if (!gLCDSupportValid) {
602 InitFreetype();
603 FT_Done_FreeType(gFTLibrary);
604 }
605
606 if (!gLCDSupport && rec->isLCD()) {
607 // If the runtime Freetype library doesn't support LCD mode, we disable
608 // it here.
609 rec->fMaskFormat = SkMask::kA8_Format;
610 }
611
612 SkPaint::Hinting h = rec->getHinting();
613 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
614 // collapse full->normal hinting if we're not doing LCD
615 h = SkPaint::kNormal_Hinting;
616 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
617 SkPaint::kNo_Hinting != h) {
618 // to do subpixel, we must have at most slight hinting
619 h = SkPaint::kSlight_Hinting;
620 }
621 rec->setHinting(h);
622}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000623
reed@android.com8a1c16f2008-12-17 15:59:43 +0000624SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000625 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000626 SkAutoMutexAcquire ac(gFTMutex);
627
reed@android.com8a1c16f2008-12-17 15:59:43 +0000628 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000629 if (!InitFreetype()) {
630 sk_throw();
631 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000632 }
633 ++gFTCount;
634
635 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000636 fFTSize = NULL;
637 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000638 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000639 if (NULL == fFaceRec) {
640 return;
641 }
642 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000643
644 // compute our factors from the record
645
646 SkMatrix m;
647
648 fRec.getSingleMatrix(&m);
649
650#ifdef DUMP_STRIKE_CREATION
651 SkString keyString;
652 SkFontHost::GetDescriptorKeyString(desc, &keyString);
653 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
654 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
655 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
656 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000657 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000658#endif
659
660 // now compute our scale factors
661 SkScalar sx = m.getScaleX();
662 SkScalar sy = m.getScaleY();
663
664 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
665 // sort of give up on hinting
666 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
667 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
668 sx = sy = SkScalarAve(sx, sy);
669
670 SkScalar inv = SkScalarInvert(sx);
671
672 // flip the skew elements to go from our Y-down system to FreeType's
673 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
674 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
675 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
676 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
677 } else {
678 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
679 fMatrix22.xy = fMatrix22.yx = 0;
680 }
681
682 fScaleX = SkScalarToFixed(sx);
683 fScaleY = SkScalarToFixed(sy);
684
685 // compute the flags we send to Load_Glyph
686 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000687 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000688
agl@chromium.org70a303f2010-05-10 14:15:50 +0000689 if (SkMask::kBW_Format == fRec.fMaskFormat) {
690 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
691 loadFlags = FT_LOAD_TARGET_MONO;
692 if (fRec.getHinting() == SkPaint::kNo_Hinting)
693 loadFlags = FT_LOAD_NO_HINTING;
694 } else {
695 switch (fRec.getHinting()) {
696 case SkPaint::kNo_Hinting:
697 loadFlags = FT_LOAD_NO_HINTING;
698 break;
699 case SkPaint::kSlight_Hinting:
700 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
701 break;
702 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000703 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
704 loadFlags = FT_LOAD_FORCE_AUTOHINT;
705 else
706 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000707 break;
708 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000709 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
710 loadFlags = FT_LOAD_FORCE_AUTOHINT;
711 break;
712 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000713 loadFlags = FT_LOAD_TARGET_NORMAL;
714 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
715 loadFlags = FT_LOAD_TARGET_LCD;
716 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
717 loadFlags = FT_LOAD_TARGET_LCD_V;
718 break;
719 default:
720 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
721 break;
722 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000723 }
724
agl@chromium.org99e1b902010-01-05 01:19:44 +0000725 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000726 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000727
reed@android.come4d0bc02009-07-24 19:53:20 +0000728 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000729 }
730
731 // now create the FT_Size
732
733 {
734 FT_Error err;
735
736 err = FT_New_Size(fFace, &fFTSize);
737 if (err != 0) {
738 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
739 fFaceRec->fFontID, fScaleX, fScaleY, err));
740 fFace = NULL;
741 return;
742 }
743
744 err = FT_Activate_Size(fFTSize);
745 if (err != 0) {
746 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
747 fFaceRec->fFontID, fScaleX, fScaleY, err));
748 fFTSize = NULL;
749 }
750
751 err = FT_Set_Char_Size( fFace,
752 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
753 72, 72);
754 if (err != 0) {
755 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
756 fFaceRec->fFontID, fScaleX, fScaleY, err));
757 fFace = NULL;
758 return;
759 }
760
761 FT_Set_Transform( fFace, &fMatrix22, NULL);
762 }
763}
764
765SkScalerContext_FreeType::~SkScalerContext_FreeType() {
766 if (fFTSize != NULL) {
767 FT_Done_Size(fFTSize);
768 }
769
770 SkAutoMutexAcquire ac(gFTMutex);
771
772 if (fFace != NULL) {
773 unref_ft_face(fFace);
774 }
775 if (--gFTCount == 0) {
776// SkDEBUGF(("FT_Done_FreeType\n"));
777 FT_Done_FreeType(gFTLibrary);
778 SkDEBUGCODE(gFTLibrary = NULL;)
779 }
780}
781
782/* We call this before each use of the fFace, since we may be sharing
783 this face with other context (at different sizes).
784*/
785FT_Error SkScalerContext_FreeType::setupSize() {
786 /* In the off-chance that a font has been removed, we want to error out
787 right away, so call resolve just to be sure.
788
789 TODO: perhaps we can skip this, by walking the global font cache and
790 killing all of the contexts when we know that a given fontID is going
791 away...
792 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000793 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000794 return (FT_Error)-1;
795 }
796
797 FT_Error err = FT_Activate_Size(fFTSize);
798
799 if (err != 0) {
800 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
801 fFaceRec->fFontID, fScaleX, fScaleY, err));
802 fFTSize = NULL;
803 } else {
804 // seems we need to reset this every time (not sure why, but without it
805 // I get random italics from some other fFTSize)
806 FT_Set_Transform( fFace, &fMatrix22, NULL);
807 }
808 return err;
809}
810
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000811void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
812 FT_Pos strength;
813 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
814 / 24;
815 FT_Outline_Embolden(outline, strength);
816}
817
reed@android.com8a1c16f2008-12-17 15:59:43 +0000818unsigned SkScalerContext_FreeType::generateGlyphCount() const {
819 return fFace->num_glyphs;
820}
821
822uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
823 return SkToU16(FT_Get_Char_Index( fFace, uni ));
824}
825
reed@android.com9d3a9852010-01-08 14:07:42 +0000826SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
827 // iterate through each cmap entry, looking for matching glyph indices
828 FT_UInt glyphIndex;
829 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
830
831 while (glyphIndex != 0) {
832 if (glyphIndex == glyph) {
833 return charCode;
834 }
835 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
836 }
837
838 return 0;
839}
840
reed@android.com8a1c16f2008-12-17 15:59:43 +0000841static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
842 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000843 case SkMask::kHorizontalLCD_Format:
844 case SkMask::kVerticalLCD_Format:
845 SkASSERT(!"An LCD format should never be passed here");
846 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000847 case SkMask::kBW_Format:
848 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000849 case SkMask::kA8_Format:
850 default:
851 return FT_PIXEL_MODE_GRAY;
852 }
853}
854
reed@android.com8a1c16f2008-12-17 15:59:43 +0000855void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
856#ifdef FT_ADVANCES_H
857 /* unhinted and light hinted text have linearly scaled advances
858 * which are very cheap to compute with some font formats...
859 */
860 {
861 SkAutoMutexAcquire ac(gFTMutex);
862
863 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000864 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000865 return;
866 }
867
868 FT_Error error;
869 FT_Fixed advance;
870
871 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
872 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
873 &advance );
874 if (0 == error) {
875 glyph->fRsbDelta = 0;
876 glyph->fLsbDelta = 0;
877 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
878 glyph->fAdvanceY = 0;
879 return;
880 }
881 }
882#endif /* FT_ADVANCES_H */
883 /* otherwise, we need to load/hint the glyph, which is slower */
884 this->generateMetrics(glyph);
885 return;
886}
887
888void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
889 SkAutoMutexAcquire ac(gFTMutex);
890
891 glyph->fRsbDelta = 0;
892 glyph->fLsbDelta = 0;
893
894 FT_Error err;
895
896 if (this->setupSize()) {
897 goto ERROR;
898 }
899
900 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
901 if (err != 0) {
902 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
903 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
904 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000905 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000906 return;
907 }
908
909 switch ( fFace->glyph->format ) {
910 case FT_GLYPH_FORMAT_OUTLINE:
911 FT_BBox bbox;
912
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000913 if (fRec.fFlags & kEmbolden_Flag) {
914 emboldenOutline(&fFace->glyph->outline);
915 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000916 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
917
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000918 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000919 int dx = glyph->getSubXFixed() >> 10;
920 int dy = glyph->getSubYFixed() >> 10;
921 // negate dy since freetype-y-goes-up and skia-y-goes-down
922 bbox.xMin += dx;
923 bbox.yMin -= dy;
924 bbox.xMax += dx;
925 bbox.yMax -= dy;
926 }
927
928 bbox.xMin &= ~63;
929 bbox.yMin &= ~63;
930 bbox.xMax = (bbox.xMax + 63) & ~63;
931 bbox.yMax = (bbox.yMax + 63) & ~63;
932
933 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
934 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
935 glyph->fTop = -SkToS16(bbox.yMax >> 6);
936 glyph->fLeft = SkToS16(bbox.xMin >> 6);
937 break;
938
939 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000940 if (fRec.fFlags & kEmbolden_Flag) {
941 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
942 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
943 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000944 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
945 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
946 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
947 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
948 break;
949
950 default:
951 SkASSERT(!"unknown glyph format");
952 goto ERROR;
953 }
954
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000955 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000956 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
957 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
958 if (fRec.fFlags & kDevKernText_Flag) {
959 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
960 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
961 }
962 } else {
963 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
964 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
965 }
966
967#ifdef ENABLE_GLYPH_SPEW
968 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
969 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
970#endif
971}
972
reed@android.comf5493692009-07-22 19:21:01 +0000973#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000974namespace skia_freetype_support {
975// extern functions from SkFontHost_FreeType_Subpixel
976extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
977extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
978}
979
980using namespace skia_freetype_support;
981#endif
982
reed@android.com8a1c16f2008-12-17 15:59:43 +0000983void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
984 SkAutoMutexAcquire ac(gFTMutex);
985
986 FT_Error err;
987
988 if (this->setupSize()) {
989 goto ERROR;
990 }
991
992 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
993 if (err != 0) {
994 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
995 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
996 ERROR:
997 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
998 return;
999 }
1000
agl@chromium.org309485b2009-07-21 17:41:32 +00001001 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1002 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
1003
reed@android.com8a1c16f2008-12-17 15:59:43 +00001004 switch ( fFace->glyph->format ) {
1005 case FT_GLYPH_FORMAT_OUTLINE: {
1006 FT_Outline* outline = &fFace->glyph->outline;
1007 FT_BBox bbox;
1008 FT_Bitmap target;
1009
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001010 if (fRec.fFlags & kEmbolden_Flag) {
1011 emboldenOutline(outline);
1012 }
1013
reed@android.com8a1c16f2008-12-17 15:59:43 +00001014 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001015 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001016 dx = glyph.getSubXFixed() >> 10;
1017 dy = glyph.getSubYFixed() >> 10;
1018 // negate dy since freetype-y-goes-up and skia-y-goes-down
1019 dy = -dy;
1020 }
1021 FT_Outline_Get_CBox(outline, &bbox);
1022 /*
1023 what we really want to do for subpixel is
1024 offset(dx, dy)
1025 compute_bounds
1026 offset(bbox & !63)
1027 but that is two calls to offset, so we do the following, which
1028 achieves the same thing with only one offset call.
1029 */
1030 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1031 dy - ((bbox.yMin + dy) & ~63));
1032
reed@android.comf5493692009-07-22 19:21:01 +00001033#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +00001034 if (lcdRenderMode) {
1035 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
1036 // we have to call FT_Render_Glyph and memcpy the image out.
1037 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
1038 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
1039 FT_Render_Glyph(fFace->glyph, mode);
1040
1041 if (isVertical)
1042 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
1043 else
1044 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
1045
1046 break;
1047 }
1048#endif
1049
reed@android.com8a1c16f2008-12-17 15:59:43 +00001050 target.width = glyph.fWidth;
1051 target.rows = glyph.fHeight;
1052 target.pitch = glyph.rowBytes();
1053 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1054 target.pixel_mode = compute_pixel_mode(
1055 (SkMask::Format)fRec.fMaskFormat);
1056 target.num_grays = 256;
1057
1058 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1059 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1060 } break;
1061
1062 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001063 if (fRec.fFlags & kEmbolden_Flag) {
1064 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1065 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1066 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001067 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1068 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1069 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1070 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1071
1072 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1073 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001074
agl@chromium.org558434a2009-08-11 17:22:38 +00001075 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1076 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1077 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001078 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1079 unsigned dstRowBytes = glyph.rowBytes();
1080 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1081 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1082
1083 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1084 memcpy(dst, src, minRowBytes);
1085 memset(dst + minRowBytes, 0, extraRowBytes);
1086 src += srcRowBytes;
1087 dst += dstRowBytes;
1088 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001089 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001090 (glyph.fMaskFormat == SkMask::kA8_Format ||
1091 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1092 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001093 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1094 uint8_t byte = 0;
1095 int bits = 0;
1096 const uint8_t* src_row = src;
1097 uint8_t* dst_row = dst;
1098
1099 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1100 if (!bits) {
1101 byte = *src_row++;
1102 bits = 8;
1103 }
1104
1105 *dst_row++ = byte & 0x80 ? 0xff : 0;
1106 bits--;
1107 byte <<= 1;
1108 }
1109
1110 src += fFace->glyph->bitmap.pitch;
1111 dst += glyph.rowBytes();
1112 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001113 } else {
1114 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001115 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001116
1117 if (lcdRenderMode)
1118 glyph.expandA8ToLCD();
1119
reed@android.com8a1c16f2008-12-17 15:59:43 +00001120 } break;
1121
1122 default:
1123 SkASSERT(!"unknown glyph format");
1124 goto ERROR;
1125 }
1126}
1127
1128///////////////////////////////////////////////////////////////////////////////
1129
1130#define ft2sk(x) SkFixedToScalar((x) << 10)
1131
reed@android.com6f252972009-01-14 16:46:16 +00001132#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001133 #define CONST_PARAM const
1134#else // older freetype doesn't use const here
1135 #define CONST_PARAM
1136#endif
1137
1138static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1139 SkPath* path = (SkPath*)ctx;
1140 path->close(); // to close the previous contour (if any)
1141 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1142 return 0;
1143}
1144
1145static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1146 SkPath* path = (SkPath*)ctx;
1147 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1148 return 0;
1149}
1150
1151static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1152 void* ctx) {
1153 SkPath* path = (SkPath*)ctx;
1154 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1155 return 0;
1156}
1157
1158static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1159 CONST_PARAM FT_Vector* pt2, void* ctx) {
1160 SkPath* path = (SkPath*)ctx;
1161 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1162 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1163 return 0;
1164}
1165
1166void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1167 SkPath* path) {
1168 SkAutoMutexAcquire ac(gFTMutex);
1169
1170 SkASSERT(&glyph && path);
1171
1172 if (this->setupSize()) {
1173 path->reset();
1174 return;
1175 }
1176
1177 uint32_t flags = fLoadGlyphFlags;
1178 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1179 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1180
1181 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1182
1183 if (err != 0) {
1184 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1185 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1186 path->reset();
1187 return;
1188 }
1189
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001190 if (fRec.fFlags & kEmbolden_Flag) {
1191 emboldenOutline(&fFace->glyph->outline);
1192 }
1193
reed@android.com8a1c16f2008-12-17 15:59:43 +00001194 FT_Outline_Funcs funcs;
1195
1196 funcs.move_to = move_proc;
1197 funcs.line_to = line_proc;
1198 funcs.conic_to = quad_proc;
1199 funcs.cubic_to = cubic_proc;
1200 funcs.shift = 0;
1201 funcs.delta = 0;
1202
1203 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1204
1205 if (err != 0) {
1206 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1207 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1208 path->reset();
1209 return;
1210 }
1211
1212 path->close();
1213}
1214
1215void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1216 SkPaint::FontMetrics* my) {
1217 if (NULL == mx && NULL == my) {
1218 return;
1219 }
1220
1221 SkAutoMutexAcquire ac(gFTMutex);
1222
1223 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001224 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001225 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001226 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001227 }
1228 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001229 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001230 }
1231 return;
1232 }
1233
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001234 FT_Face face = fFace;
1235 int upem = face->units_per_EM;
1236 if (upem <= 0) {
1237 goto ERROR;
1238 }
1239
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001240 SkPoint pts[6];
1241 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001242 SkFixed scaleY = fScaleY;
1243 SkFixed mxy = fMatrix22.xy;
1244 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001245 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1246 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001247
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001248 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001249 if (leading < 0) {
1250 leading = 0;
1251 }
1252
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001253 // Try to get the OS/2 table from the font. This contains the specific
1254 // average font width metrics which Windows uses.
1255 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1256
reed@android.com8a1c16f2008-12-17 15:59:43 +00001257 ys[0] = -face->bbox.yMax;
1258 ys[1] = -face->ascender;
1259 ys[2] = -face->descender;
1260 ys[3] = -face->bbox.yMin;
1261 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001262 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1263
1264 SkScalar x_height;
1265 if (os2 && os2->sxHeight) {
1266 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1267 } else {
1268 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1269 if (x_glyph) {
1270 FT_BBox bbox;
1271 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001272 if (fRec.fFlags & kEmbolden_Flag) {
1273 emboldenOutline(&fFace->glyph->outline);
1274 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001275 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1276 x_height = SkIntToScalar(bbox.yMax) / 64;
1277 } else {
1278 x_height = 0;
1279 }
1280 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001281
1282 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001283 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001284 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1285 SkFixed x = SkFixedMul(mxy, y);
1286 y = SkFixedMul(myy, y);
1287 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1288 }
1289
1290 if (mx) {
1291 mx->fTop = pts[0].fX;
1292 mx->fAscent = pts[1].fX;
1293 mx->fDescent = pts[2].fX;
1294 mx->fBottom = pts[3].fX;
1295 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001296 mx->fAvgCharWidth = pts[5].fX;
1297 mx->fXMin = xmin;
1298 mx->fXMax = xmax;
1299 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001300 }
1301 if (my) {
1302 my->fTop = pts[0].fY;
1303 my->fAscent = pts[1].fY;
1304 my->fDescent = pts[2].fY;
1305 my->fBottom = pts[3].fY;
1306 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001307 my->fAvgCharWidth = pts[5].fY;
1308 my->fXMin = xmin;
1309 my->fXMax = xmax;
1310 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001311 }
1312}
1313
1314////////////////////////////////////////////////////////////////////////
1315////////////////////////////////////////////////////////////////////////
1316
1317SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001318 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1319 if (!c->success()) {
1320 SkDELETE(c);
1321 c = NULL;
1322 }
1323 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001324}
1325
1326///////////////////////////////////////////////////////////////////////////////
1327
1328/* Export this so that other parts of our FonttHost port can make use of our
1329 ability to extract the name+style from a stream, using FreeType's api.
1330*/
1331SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
1332 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001333 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001334 name->set(NULL);
1335 return SkTypeface::kNormal;
1336 }
1337
1338 FT_Open_Args args;
1339 memset(&args, 0, sizeof(args));
1340
1341 const void* memoryBase = stream->getMemoryBase();
1342 FT_StreamRec streamRec;
1343
1344 if (NULL != memoryBase) {
1345 args.flags = FT_OPEN_MEMORY;
1346 args.memory_base = (const FT_Byte*)memoryBase;
1347 args.memory_size = stream->getLength();
1348 } else {
1349 memset(&streamRec, 0, sizeof(streamRec));
1350 streamRec.size = stream->read(NULL, 0);
1351 streamRec.descriptor.pointer = stream;
1352 streamRec.read = sk_stream_read;
1353 streamRec.close = sk_stream_close;
1354
1355 args.flags = FT_OPEN_STREAM;
1356 args.stream = &streamRec;
1357 }
1358
1359 FT_Face face;
1360 if (FT_Open_Face(library, &args, 0, &face)) {
1361 FT_Done_FreeType(library);
1362 name->set(NULL);
1363 return SkTypeface::kNormal;
1364 }
1365
1366 name->set(face->family_name);
1367 int style = SkTypeface::kNormal;
1368
1369 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1370 style |= SkTypeface::kBold;
1371 }
1372 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1373 style |= SkTypeface::kItalic;
1374 }
1375
1376 FT_Done_Face(face);
1377 FT_Done_FreeType(library);
1378 return (SkTypeface::Style)style;
1379}