blob: 1b1d47b5ce1532911a6bd234f4ae843e8d050634 [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.orgc3a2ae52011-02-03 21:48:23 +0000452 if (strcmp(fontType, "Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000453 info->fType = SkAdvancedTypefaceMetrics::kType1_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000454 } else if (strcmp(fontType, "CID Type 1") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000455 info->fType = SkAdvancedTypefaceMetrics::kType1CID_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000456 cid = true;
457 } else if (strcmp(fontType, "CFF") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000458 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000459 } else if (strcmp(fontType, "TrueType") == 0) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000460 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000461 cid = true;
462 TT_Header* ttHeader;
463 if ((ttHeader = (TT_Header*)FT_Get_Sfnt_Table(face,
464 ft_sfnt_head)) != NULL) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000465 info->fEmSize = ttHeader->Units_Per_EM;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000466 }
467 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000468
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000469 SkASSERT(!FT_HAS_VERTICAL(face));
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000470#ifdef FT_IS_CID_KEYED
471 SkASSERT(FT_IS_CID_KEYED(face) ==
472 (info->fType == SkAdvancedTypefaceMetrics::kType1CID_Font));
473#endif
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000474
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000475 info->fStyle = 0;
476 if (FT_IS_FIXED_WIDTH(face))
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000477 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000478 if (face->style_flags & FT_STYLE_FLAG_ITALIC)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000479 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000480 // We should set either Symbolic or Nonsymbolic; Nonsymbolic if the font's
481 // character set is a subset of 'Adobe standard Latin.'
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000482 info->fStyle |= SkAdvancedTypefaceMetrics::kSymbolic_Style;
483
484 PS_FontInfoRec ps_info;
485 TT_Postscript* tt_info;
486 if (FT_Get_PS_Font_Info(face, &ps_info) == 0) {
487 info->fItalicAngle = ps_info.italic_angle;
488 } else if ((tt_info =
489 (TT_Postscript*)FT_Get_Sfnt_Table(face,
490 ft_sfnt_post)) != NULL) {
491 info->fItalicAngle = SkFixedToScalar(tt_info->italicAngle);
492 } else {
493 info->fItalicAngle = 0;
494 }
495
496 info->fAscent = face->ascender;
497 info->fDescent = face->descender;
498
499 // Figure out a good guess for StemV - Min width of i, I, !, 1.
500 // This probably isn't very good with an italic font.
501 int16_t min_width = SHRT_MAX;
502 char stem_chars[] = {'i', 'I', '!', '1'};
503 for (size_t i = 0; i < SK_ARRAY_COUNT(stem_chars); i++) {
504 FT_BBox bbox;
505 if (GetLetterCBox(face, stem_chars[i], &bbox)) {
506 int16_t width = bbox.xMax - bbox.xMin;
507 if (width > 0 && width < min_width) {
508 min_width = width;
509 info->fStemV = min_width;
510 }
511 }
512 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000513
514 TT_PCLT* pclt_info;
515 TT_OS2* os2_table;
516 if ((pclt_info = (TT_PCLT*)FT_Get_Sfnt_Table(face, ft_sfnt_pclt)) != NULL) {
517 info->fCapHeight = pclt_info->CapHeight;
518 uint8_t serif_style = pclt_info->SerifStyle & 0x3F;
519 if (serif_style >= 2 && serif_style <= 6)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000520 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000521 else if (serif_style >= 9 && serif_style <= 12)
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000522 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000523 } else if ((os2_table =
524 (TT_OS2*)FT_Get_Sfnt_Table(face, ft_sfnt_os2)) != NULL) {
525 info->fCapHeight = os2_table->sCapHeight;
526 } else {
527 // Figure out a good guess for CapHeight: average the height of M and X.
528 FT_BBox m_bbox, x_bbox;
529 bool got_m, got_x;
530 got_m = GetLetterCBox(face, 'M', &m_bbox);
531 got_x = GetLetterCBox(face, 'X', &x_bbox);
532 if (got_m && got_x) {
533 info->fCapHeight = (m_bbox.yMax - m_bbox.yMin + x_bbox.yMax -
534 x_bbox.yMin) / 2;
535 } else if (got_m && !got_x) {
536 info->fCapHeight = m_bbox.yMax - m_bbox.yMin;
537 } else if (!got_m && got_x) {
538 info->fCapHeight = x_bbox.yMax - x_bbox.yMin;
539 }
540 }
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000541
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000542 info->fBBox = SkIRect::MakeLTRB(face->bbox.xMin, face->bbox.yMax,
543 face->bbox.xMax, face->bbox.yMin);
544
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000545 if (perGlyphInfo && canEmbed(face) && FT_IS_SCALABLE(face) &&
546 info->fType != SkAdvancedTypefaceMetrics::kOther_Font) {
vandebo@chromium.orgc48b2b32011-02-02 02:11:22 +0000547 if (FT_IS_FIXED_WIDTH(face)) {
548 appendRange(&info->fGlyphWidths, 0);
549 int16_t advance = face->max_advance_width;
550 info->fGlyphWidths->fAdvance.append(1, &advance);
551 finishRange(info->fGlyphWidths.get(), 0,
552 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
553 } else if(!cid) {
554 appendRange(&info->fGlyphWidths, 0);
555 // So as to not blow out the stack, get advances in batches.
556 for (int gID = 0; gID < face->num_glyphs; gID += 128) {
557 FT_Fixed advances[128];
558 int advanceCount = 128;
559 if (gID + advanceCount > face->num_glyphs)
560 advanceCount = face->num_glyphs - gID + 1;
561 getAdvances(face, gID, advanceCount, FT_LOAD_NO_SCALE,
562 advances);
563 for (int i = 0; i < advanceCount; i++) {
564 int16_t advance = advances[gID + i];
565 info->fGlyphWidths->fAdvance.append(1, &advance);
566 }
567 }
568 finishRange(info->fGlyphWidths.get(), face->num_glyphs - 1,
569 SkAdvancedTypefaceMetrics::WidthRange::kRange);
570 } else {
571 info->fGlyphWidths.reset(getAdvanceData(face, &getWidthAdvance));
572 }
573
574 if (info->fType == SkAdvancedTypefaceMetrics::kType1_Font) {
575 // Postscript fonts may contain more than 255 glyphs, so we end up
576 // using multiple font descriptions with a glyph ordering. Record
577 // the name of each glyph.
578 info->fGlyphNames.reset(
579 new SkAutoTArray<SkString>(face->num_glyphs));
580 for (int gID = 0; gID < face->num_glyphs; gID++) {
581 char glyphName[128]; // PS limit for names is 127 bytes.
582 FT_Get_Glyph_Name(face, gID, glyphName, 128);
583 info->fGlyphNames->get()[gID].set(glyphName);
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000584 }
585 }
586 }
587
vandebo@chromium.orgc3a2ae52011-02-03 21:48:23 +0000588 if (!canEmbed(face))
589 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
590
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000591 unref_ft_face(face);
592 return info;
593}
reed@google.com618ef5e2011-01-26 22:10:41 +0000594///////////////////////////////////////////////////////////////////////////
595
596void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
597 if (!gLCDSupportValid) {
598 InitFreetype();
599 FT_Done_FreeType(gFTLibrary);
600 }
601
602 if (!gLCDSupport && rec->isLCD()) {
603 // If the runtime Freetype library doesn't support LCD mode, we disable
604 // it here.
605 rec->fMaskFormat = SkMask::kA8_Format;
606 }
607
608 SkPaint::Hinting h = rec->getHinting();
609 if (SkPaint::kFull_Hinting == h && !rec->isLCD()) {
610 // collapse full->normal hinting if we're not doing LCD
611 h = SkPaint::kNormal_Hinting;
612 } else if ((rec->fFlags & SkScalerContext::kSubpixelPositioning_Flag) &&
613 SkPaint::kNo_Hinting != h) {
614 // to do subpixel, we must have at most slight hinting
615 h = SkPaint::kSlight_Hinting;
616 }
617 rec->setHinting(h);
618}
vandebo@chromium.org2a22e102011-01-25 21:01:34 +0000619
reed@android.com8a1c16f2008-12-17 15:59:43 +0000620SkScalerContext_FreeType::SkScalerContext_FreeType(const SkDescriptor* desc)
reed@android.com62900b42009-02-11 15:07:19 +0000621 : SkScalerContext(desc) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000622 SkAutoMutexAcquire ac(gFTMutex);
623
reed@android.com8a1c16f2008-12-17 15:59:43 +0000624 if (gFTCount == 0) {
reed@android.com659aaf92009-07-23 15:20:21 +0000625 if (!InitFreetype()) {
626 sk_throw();
627 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000628 }
629 ++gFTCount;
630
631 // load the font file
reed@android.com62900b42009-02-11 15:07:19 +0000632 fFTSize = NULL;
633 fFace = NULL;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000634 fFaceRec = ref_ft_face(fRec.fFontID);
reed@android.com62900b42009-02-11 15:07:19 +0000635 if (NULL == fFaceRec) {
636 return;
637 }
638 fFace = fFaceRec->fFace;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000639
640 // compute our factors from the record
641
642 SkMatrix m;
643
644 fRec.getSingleMatrix(&m);
645
646#ifdef DUMP_STRIKE_CREATION
647 SkString keyString;
648 SkFontHost::GetDescriptorKeyString(desc, &keyString);
649 printf("========== strike [%g %g %g] [%g %g %g %g] hints %d format %d %s\n", SkScalarToFloat(fRec.fTextSize),
650 SkScalarToFloat(fRec.fPreScaleX), SkScalarToFloat(fRec.fPreSkewX),
651 SkScalarToFloat(fRec.fPost2x2[0][0]), SkScalarToFloat(fRec.fPost2x2[0][1]),
652 SkScalarToFloat(fRec.fPost2x2[1][0]), SkScalarToFloat(fRec.fPost2x2[1][1]),
agl@chromium.org309485b2009-07-21 17:41:32 +0000653 fRec.getHinting(), fRec.fMaskFormat, keyString.c_str());
reed@android.com8a1c16f2008-12-17 15:59:43 +0000654#endif
655
656 // now compute our scale factors
657 SkScalar sx = m.getScaleX();
658 SkScalar sy = m.getScaleY();
659
660 if (m.getSkewX() || m.getSkewY() || sx < 0 || sy < 0) {
661 // sort of give up on hinting
662 sx = SkMaxScalar(SkScalarAbs(sx), SkScalarAbs(m.getSkewX()));
663 sy = SkMaxScalar(SkScalarAbs(m.getSkewY()), SkScalarAbs(sy));
664 sx = sy = SkScalarAve(sx, sy);
665
666 SkScalar inv = SkScalarInvert(sx);
667
668 // flip the skew elements to go from our Y-down system to FreeType's
669 fMatrix22.xx = SkScalarToFixed(SkScalarMul(m.getScaleX(), inv));
670 fMatrix22.xy = -SkScalarToFixed(SkScalarMul(m.getSkewX(), inv));
671 fMatrix22.yx = -SkScalarToFixed(SkScalarMul(m.getSkewY(), inv));
672 fMatrix22.yy = SkScalarToFixed(SkScalarMul(m.getScaleY(), inv));
673 } else {
674 fMatrix22.xx = fMatrix22.yy = SK_Fixed1;
675 fMatrix22.xy = fMatrix22.yx = 0;
676 }
677
678 fScaleX = SkScalarToFixed(sx);
679 fScaleY = SkScalarToFixed(sy);
680
681 // compute the flags we send to Load_Glyph
682 {
reed@android.come4d0bc02009-07-24 19:53:20 +0000683 FT_Int32 loadFlags = FT_LOAD_DEFAULT;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000684
agl@chromium.org70a303f2010-05-10 14:15:50 +0000685 if (SkMask::kBW_Format == fRec.fMaskFormat) {
686 // See http://code.google.com/p/chromium/issues/detail?id=43252#c24
687 loadFlags = FT_LOAD_TARGET_MONO;
688 if (fRec.getHinting() == SkPaint::kNo_Hinting)
689 loadFlags = FT_LOAD_NO_HINTING;
690 } else {
691 switch (fRec.getHinting()) {
692 case SkPaint::kNo_Hinting:
693 loadFlags = FT_LOAD_NO_HINTING;
694 break;
695 case SkPaint::kSlight_Hinting:
696 loadFlags = FT_LOAD_TARGET_LIGHT; // This implies FORCE_AUTOHINT
697 break;
698 case SkPaint::kNormal_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000699 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag)
700 loadFlags = FT_LOAD_FORCE_AUTOHINT;
701 else
702 loadFlags = FT_LOAD_NO_AUTOHINT;
agl@chromium.org70a303f2010-05-10 14:15:50 +0000703 break;
704 case SkPaint::kFull_Hinting:
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000705 if (fRec.fFlags & SkScalerContext::kAutohinting_Flag) {
706 loadFlags = FT_LOAD_FORCE_AUTOHINT;
707 break;
708 }
agl@chromium.org70a303f2010-05-10 14:15:50 +0000709 loadFlags = FT_LOAD_TARGET_NORMAL;
710 if (SkMask::kHorizontalLCD_Format == fRec.fMaskFormat)
711 loadFlags = FT_LOAD_TARGET_LCD;
712 else if (SkMask::kVerticalLCD_Format == fRec.fMaskFormat)
713 loadFlags = FT_LOAD_TARGET_LCD_V;
714 break;
715 default:
716 SkDebugf("---------- UNKNOWN hinting %d\n", fRec.getHinting());
717 break;
718 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000719 }
720
agl@chromium.org99e1b902010-01-05 01:19:44 +0000721 if ((fRec.fFlags & SkScalerContext::kEmbeddedBitmapText_Flag) == 0)
agl@chromium.orge0d08992009-08-07 19:19:23 +0000722 loadFlags |= FT_LOAD_NO_BITMAP;
agl@chromium.orge0d08992009-08-07 19:19:23 +0000723
reed@android.come4d0bc02009-07-24 19:53:20 +0000724 fLoadGlyphFlags = loadFlags;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000725 }
726
727 // now create the FT_Size
728
729 {
730 FT_Error err;
731
732 err = FT_New_Size(fFace, &fFTSize);
733 if (err != 0) {
734 SkDEBUGF(("SkScalerContext_FreeType::FT_New_Size(%x): FT_Set_Char_Size(0x%x, 0x%x) returned 0x%x\n",
735 fFaceRec->fFontID, fScaleX, fScaleY, err));
736 fFace = NULL;
737 return;
738 }
739
740 err = FT_Activate_Size(fFTSize);
741 if (err != 0) {
742 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
743 fFaceRec->fFontID, fScaleX, fScaleY, err));
744 fFTSize = NULL;
745 }
746
747 err = FT_Set_Char_Size( fFace,
748 SkFixedToFDot6(fScaleX), SkFixedToFDot6(fScaleY),
749 72, 72);
750 if (err != 0) {
751 SkDEBUGF(("SkScalerContext_FreeType::FT_Set_Char_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
752 fFaceRec->fFontID, fScaleX, fScaleY, err));
753 fFace = NULL;
754 return;
755 }
756
757 FT_Set_Transform( fFace, &fMatrix22, NULL);
758 }
759}
760
761SkScalerContext_FreeType::~SkScalerContext_FreeType() {
762 if (fFTSize != NULL) {
763 FT_Done_Size(fFTSize);
764 }
765
766 SkAutoMutexAcquire ac(gFTMutex);
767
768 if (fFace != NULL) {
769 unref_ft_face(fFace);
770 }
771 if (--gFTCount == 0) {
772// SkDEBUGF(("FT_Done_FreeType\n"));
773 FT_Done_FreeType(gFTLibrary);
774 SkDEBUGCODE(gFTLibrary = NULL;)
775 }
776}
777
778/* We call this before each use of the fFace, since we may be sharing
779 this face with other context (at different sizes).
780*/
781FT_Error SkScalerContext_FreeType::setupSize() {
782 /* In the off-chance that a font has been removed, we want to error out
783 right away, so call resolve just to be sure.
784
785 TODO: perhaps we can skip this, by walking the global font cache and
786 killing all of the contexts when we know that a given fontID is going
787 away...
788 */
reed@android.comb1d9d2e2009-03-04 17:37:51 +0000789 if (!SkFontHost::ValidFontID(fRec.fFontID)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000790 return (FT_Error)-1;
791 }
792
793 FT_Error err = FT_Activate_Size(fFTSize);
794
795 if (err != 0) {
796 SkDEBUGF(("SkScalerContext_FreeType::FT_Activate_Size(%x, 0x%x, 0x%x) returned 0x%x\n",
797 fFaceRec->fFontID, fScaleX, fScaleY, err));
798 fFTSize = NULL;
799 } else {
800 // seems we need to reset this every time (not sure why, but without it
801 // I get random italics from some other fFTSize)
802 FT_Set_Transform( fFace, &fMatrix22, NULL);
803 }
804 return err;
805}
806
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000807void SkScalerContext_FreeType::emboldenOutline(FT_Outline* outline) {
808 FT_Pos strength;
809 strength = FT_MulFix(fFace->units_per_EM, fFace->size->metrics.y_scale)
810 / 24;
811 FT_Outline_Embolden(outline, strength);
812}
813
reed@android.com8a1c16f2008-12-17 15:59:43 +0000814unsigned SkScalerContext_FreeType::generateGlyphCount() const {
815 return fFace->num_glyphs;
816}
817
818uint16_t SkScalerContext_FreeType::generateCharToGlyph(SkUnichar uni) {
819 return SkToU16(FT_Get_Char_Index( fFace, uni ));
820}
821
reed@android.com9d3a9852010-01-08 14:07:42 +0000822SkUnichar SkScalerContext_FreeType::generateGlyphToChar(uint16_t glyph) {
823 // iterate through each cmap entry, looking for matching glyph indices
824 FT_UInt glyphIndex;
825 SkUnichar charCode = FT_Get_First_Char( fFace, &glyphIndex );
826
827 while (glyphIndex != 0) {
828 if (glyphIndex == glyph) {
829 return charCode;
830 }
831 charCode = FT_Get_Next_Char( fFace, charCode, &glyphIndex );
832 }
833
834 return 0;
835}
836
reed@android.com8a1c16f2008-12-17 15:59:43 +0000837static FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) {
838 switch (format) {
agl@chromium.org309485b2009-07-21 17:41:32 +0000839 case SkMask::kHorizontalLCD_Format:
840 case SkMask::kVerticalLCD_Format:
841 SkASSERT(!"An LCD format should never be passed here");
842 return FT_PIXEL_MODE_GRAY;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000843 case SkMask::kBW_Format:
844 return FT_PIXEL_MODE_MONO;
reed@android.com8a1c16f2008-12-17 15:59:43 +0000845 case SkMask::kA8_Format:
846 default:
847 return FT_PIXEL_MODE_GRAY;
848 }
849}
850
reed@android.com8a1c16f2008-12-17 15:59:43 +0000851void SkScalerContext_FreeType::generateAdvance(SkGlyph* glyph) {
852#ifdef FT_ADVANCES_H
853 /* unhinted and light hinted text have linearly scaled advances
854 * which are very cheap to compute with some font formats...
855 */
856 {
857 SkAutoMutexAcquire ac(gFTMutex);
858
859 if (this->setupSize()) {
reed@android.com62900b42009-02-11 15:07:19 +0000860 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000861 return;
862 }
863
864 FT_Error error;
865 FT_Fixed advance;
866
867 error = FT_Get_Advance( fFace, glyph->getGlyphID(fBaseGlyphCount),
868 fLoadGlyphFlags | FT_ADVANCE_FLAG_FAST_ONLY,
869 &advance );
870 if (0 == error) {
871 glyph->fRsbDelta = 0;
872 glyph->fLsbDelta = 0;
873 glyph->fAdvanceX = advance; // advance *2/3; //DEBUG
874 glyph->fAdvanceY = 0;
875 return;
876 }
877 }
878#endif /* FT_ADVANCES_H */
879 /* otherwise, we need to load/hint the glyph, which is slower */
880 this->generateMetrics(glyph);
881 return;
882}
883
884void SkScalerContext_FreeType::generateMetrics(SkGlyph* glyph) {
885 SkAutoMutexAcquire ac(gFTMutex);
886
887 glyph->fRsbDelta = 0;
888 glyph->fLsbDelta = 0;
889
890 FT_Error err;
891
892 if (this->setupSize()) {
893 goto ERROR;
894 }
895
896 err = FT_Load_Glyph( fFace, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags );
897 if (err != 0) {
898 SkDEBUGF(("SkScalerContext_FreeType::generateMetrics(%x): FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
899 fFaceRec->fFontID, glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, err));
900 ERROR:
reed@android.com62900b42009-02-11 15:07:19 +0000901 glyph->zeroMetrics();
reed@android.com8a1c16f2008-12-17 15:59:43 +0000902 return;
903 }
904
905 switch ( fFace->glyph->format ) {
906 case FT_GLYPH_FORMAT_OUTLINE:
907 FT_BBox bbox;
908
senorblanco@chromium.org4526a842010-02-05 23:08:20 +0000909 if (fRec.fFlags & kEmbolden_Flag) {
910 emboldenOutline(&fFace->glyph->outline);
911 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000912 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
913
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000914 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000915 int dx = glyph->getSubXFixed() >> 10;
916 int dy = glyph->getSubYFixed() >> 10;
917 // negate dy since freetype-y-goes-up and skia-y-goes-down
918 bbox.xMin += dx;
919 bbox.yMin -= dy;
920 bbox.xMax += dx;
921 bbox.yMax -= dy;
922 }
923
924 bbox.xMin &= ~63;
925 bbox.yMin &= ~63;
926 bbox.xMax = (bbox.xMax + 63) & ~63;
927 bbox.yMax = (bbox.yMax + 63) & ~63;
928
929 glyph->fWidth = SkToU16((bbox.xMax - bbox.xMin) >> 6);
930 glyph->fHeight = SkToU16((bbox.yMax - bbox.yMin) >> 6);
931 glyph->fTop = -SkToS16(bbox.yMax >> 6);
932 glyph->fLeft = SkToS16(bbox.xMin >> 6);
933 break;
934
935 case FT_GLYPH_FORMAT_BITMAP:
agl@chromium.orge76073b2010-06-04 20:31:17 +0000936 if (fRec.fFlags & kEmbolden_Flag) {
937 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
938 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
939 }
reed@android.com8a1c16f2008-12-17 15:59:43 +0000940 glyph->fWidth = SkToU16(fFace->glyph->bitmap.width);
941 glyph->fHeight = SkToU16(fFace->glyph->bitmap.rows);
942 glyph->fTop = -SkToS16(fFace->glyph->bitmap_top);
943 glyph->fLeft = SkToS16(fFace->glyph->bitmap_left);
944 break;
945
946 default:
947 SkASSERT(!"unknown glyph format");
948 goto ERROR;
949 }
950
agl@chromium.orga2c71cb2010-06-17 20:49:17 +0000951 if ((fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) == 0) {
reed@android.com8a1c16f2008-12-17 15:59:43 +0000952 glyph->fAdvanceX = SkFDot6ToFixed(fFace->glyph->advance.x);
953 glyph->fAdvanceY = -SkFDot6ToFixed(fFace->glyph->advance.y);
954 if (fRec.fFlags & kDevKernText_Flag) {
955 glyph->fRsbDelta = SkToS8(fFace->glyph->rsb_delta);
956 glyph->fLsbDelta = SkToS8(fFace->glyph->lsb_delta);
957 }
958 } else {
959 glyph->fAdvanceX = SkFixedMul(fMatrix22.xx, fFace->glyph->linearHoriAdvance);
960 glyph->fAdvanceY = -SkFixedMul(fMatrix22.yx, fFace->glyph->linearHoriAdvance);
961 }
962
963#ifdef ENABLE_GLYPH_SPEW
964 SkDEBUGF(("FT_Set_Char_Size(this:%p sx:%x sy:%x ", this, fScaleX, fScaleY));
965 SkDEBUGF(("Metrics(glyph:%d flags:0x%x) w:%d\n", glyph->getGlyphID(fBaseGlyphCount), fLoadGlyphFlags, glyph->fWidth));
966#endif
967}
968
reed@android.comf5493692009-07-22 19:21:01 +0000969#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +0000970namespace skia_freetype_support {
971// extern functions from SkFontHost_FreeType_Subpixel
972extern void CopyFreetypeBitmapToLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
973extern void CopyFreetypeBitmapToVerticalLCDMask(const SkGlyph& dest, const FT_Bitmap& source);
974}
975
976using namespace skia_freetype_support;
977#endif
978
reed@android.com8a1c16f2008-12-17 15:59:43 +0000979void SkScalerContext_FreeType::generateImage(const SkGlyph& glyph) {
980 SkAutoMutexAcquire ac(gFTMutex);
981
982 FT_Error err;
983
984 if (this->setupSize()) {
985 goto ERROR;
986 }
987
988 err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), fLoadGlyphFlags);
989 if (err != 0) {
990 SkDEBUGF(("SkScalerContext_FreeType::generateImage: FT_Load_Glyph(glyph:%d width:%d height:%d rb:%d flags:%d) returned 0x%x\n",
991 glyph.getGlyphID(fBaseGlyphCount), glyph.fWidth, glyph.fHeight, glyph.rowBytes(), fLoadGlyphFlags, err));
992 ERROR:
993 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
994 return;
995 }
996
agl@chromium.org309485b2009-07-21 17:41:32 +0000997 const bool lcdRenderMode = fRec.fMaskFormat == SkMask::kHorizontalLCD_Format ||
998 fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
999
reed@android.com8a1c16f2008-12-17 15:59:43 +00001000 switch ( fFace->glyph->format ) {
1001 case FT_GLYPH_FORMAT_OUTLINE: {
1002 FT_Outline* outline = &fFace->glyph->outline;
1003 FT_BBox bbox;
1004 FT_Bitmap target;
1005
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001006 if (fRec.fFlags & kEmbolden_Flag) {
1007 emboldenOutline(outline);
1008 }
1009
reed@android.com8a1c16f2008-12-17 15:59:43 +00001010 int dx = 0, dy = 0;
agl@chromium.orga2c71cb2010-06-17 20:49:17 +00001011 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001012 dx = glyph.getSubXFixed() >> 10;
1013 dy = glyph.getSubYFixed() >> 10;
1014 // negate dy since freetype-y-goes-up and skia-y-goes-down
1015 dy = -dy;
1016 }
1017 FT_Outline_Get_CBox(outline, &bbox);
1018 /*
1019 what we really want to do for subpixel is
1020 offset(dx, dy)
1021 compute_bounds
1022 offset(bbox & !63)
1023 but that is two calls to offset, so we do the following, which
1024 achieves the same thing with only one offset call.
1025 */
1026 FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63),
1027 dy - ((bbox.yMin + dy) & ~63));
1028
reed@android.comf5493692009-07-22 19:21:01 +00001029#if defined(SK_SUPPORT_LCDTEXT)
agl@chromium.org309485b2009-07-21 17:41:32 +00001030 if (lcdRenderMode) {
1031 // FT_Outline_Get_Bitmap cannot render LCD glyphs. In this case
1032 // we have to call FT_Render_Glyph and memcpy the image out.
1033 const bool isVertical = fRec.fMaskFormat == SkMask::kVerticalLCD_Format;
1034 FT_Render_Mode mode = isVertical ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD;
1035 FT_Render_Glyph(fFace->glyph, mode);
1036
1037 if (isVertical)
1038 CopyFreetypeBitmapToVerticalLCDMask(glyph, fFace->glyph->bitmap);
1039 else
1040 CopyFreetypeBitmapToLCDMask(glyph, fFace->glyph->bitmap);
1041
1042 break;
1043 }
1044#endif
1045
reed@android.com8a1c16f2008-12-17 15:59:43 +00001046 target.width = glyph.fWidth;
1047 target.rows = glyph.fHeight;
1048 target.pitch = glyph.rowBytes();
1049 target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage);
1050 target.pixel_mode = compute_pixel_mode(
1051 (SkMask::Format)fRec.fMaskFormat);
1052 target.num_grays = 256;
1053
1054 memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight);
1055 FT_Outline_Get_Bitmap(gFTLibrary, outline, &target);
1056 } break;
1057
1058 case FT_GLYPH_FORMAT_BITMAP: {
agl@chromium.orge76073b2010-06-04 20:31:17 +00001059 if (fRec.fFlags & kEmbolden_Flag) {
1060 FT_GlyphSlot_Own_Bitmap(fFace->glyph);
1061 FT_Bitmap_Embolden(gFTLibrary, &fFace->glyph->bitmap, kBitmapEmboldenStrength, 0);
1062 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001063 SkASSERT_CONTINUE(glyph.fWidth == fFace->glyph->bitmap.width);
1064 SkASSERT_CONTINUE(glyph.fHeight == fFace->glyph->bitmap.rows);
1065 SkASSERT_CONTINUE(glyph.fTop == -fFace->glyph->bitmap_top);
1066 SkASSERT_CONTINUE(glyph.fLeft == fFace->glyph->bitmap_left);
1067
1068 const uint8_t* src = (const uint8_t*)fFace->glyph->bitmap.buffer;
1069 uint8_t* dst = (uint8_t*)glyph.fImage;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001070
agl@chromium.org558434a2009-08-11 17:22:38 +00001071 if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ||
1072 (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
1073 glyph.fMaskFormat == SkMask::kBW_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001074 unsigned srcRowBytes = fFace->glyph->bitmap.pitch;
1075 unsigned dstRowBytes = glyph.rowBytes();
1076 unsigned minRowBytes = SkMin32(srcRowBytes, dstRowBytes);
1077 unsigned extraRowBytes = dstRowBytes - minRowBytes;
1078
1079 for (int y = fFace->glyph->bitmap.rows - 1; y >= 0; --y) {
1080 memcpy(dst, src, minRowBytes);
1081 memset(dst + minRowBytes, 0, extraRowBytes);
1082 src += srcRowBytes;
1083 dst += dstRowBytes;
1084 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001085 } else if (fFace->glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO &&
agl@chromium.orge95c91e2010-01-04 18:27:55 +00001086 (glyph.fMaskFormat == SkMask::kA8_Format ||
1087 glyph.fMaskFormat == SkMask::kHorizontalLCD_Format ||
1088 glyph.fMaskFormat == SkMask::kVerticalLCD_Format)) {
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001089 for (int y = 0; y < fFace->glyph->bitmap.rows; ++y) {
1090 uint8_t byte = 0;
1091 int bits = 0;
1092 const uint8_t* src_row = src;
1093 uint8_t* dst_row = dst;
1094
1095 for (int x = 0; x < fFace->glyph->bitmap.width; ++x) {
1096 if (!bits) {
1097 byte = *src_row++;
1098 bits = 8;
1099 }
1100
1101 *dst_row++ = byte & 0x80 ? 0xff : 0;
1102 bits--;
1103 byte <<= 1;
1104 }
1105
1106 src += fFace->glyph->bitmap.pitch;
1107 dst += glyph.rowBytes();
1108 }
agl@chromium.org558434a2009-08-11 17:22:38 +00001109 } else {
1110 SkASSERT(!"unknown glyph bitmap transform needed");
reed@android.com8a1c16f2008-12-17 15:59:43 +00001111 }
agl@chromium.org309485b2009-07-21 17:41:32 +00001112
1113 if (lcdRenderMode)
1114 glyph.expandA8ToLCD();
1115
reed@android.com8a1c16f2008-12-17 15:59:43 +00001116 } break;
1117
1118 default:
1119 SkASSERT(!"unknown glyph format");
1120 goto ERROR;
1121 }
1122}
1123
1124///////////////////////////////////////////////////////////////////////////////
1125
1126#define ft2sk(x) SkFixedToScalar((x) << 10)
1127
reed@android.com6f252972009-01-14 16:46:16 +00001128#if FREETYPE_MAJOR >= 2 && FREETYPE_MINOR >= 2
reed@android.com8a1c16f2008-12-17 15:59:43 +00001129 #define CONST_PARAM const
1130#else // older freetype doesn't use const here
1131 #define CONST_PARAM
1132#endif
1133
1134static int move_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1135 SkPath* path = (SkPath*)ctx;
1136 path->close(); // to close the previous contour (if any)
1137 path->moveTo(ft2sk(pt->x), -ft2sk(pt->y));
1138 return 0;
1139}
1140
1141static int line_proc(CONST_PARAM FT_Vector* pt, void* ctx) {
1142 SkPath* path = (SkPath*)ctx;
1143 path->lineTo(ft2sk(pt->x), -ft2sk(pt->y));
1144 return 0;
1145}
1146
1147static int quad_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1148 void* ctx) {
1149 SkPath* path = (SkPath*)ctx;
1150 path->quadTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x), -ft2sk(pt1->y));
1151 return 0;
1152}
1153
1154static int cubic_proc(CONST_PARAM FT_Vector* pt0, CONST_PARAM FT_Vector* pt1,
1155 CONST_PARAM FT_Vector* pt2, void* ctx) {
1156 SkPath* path = (SkPath*)ctx;
1157 path->cubicTo(ft2sk(pt0->x), -ft2sk(pt0->y), ft2sk(pt1->x),
1158 -ft2sk(pt1->y), ft2sk(pt2->x), -ft2sk(pt2->y));
1159 return 0;
1160}
1161
1162void SkScalerContext_FreeType::generatePath(const SkGlyph& glyph,
1163 SkPath* path) {
1164 SkAutoMutexAcquire ac(gFTMutex);
1165
1166 SkASSERT(&glyph && path);
1167
1168 if (this->setupSize()) {
1169 path->reset();
1170 return;
1171 }
1172
1173 uint32_t flags = fLoadGlyphFlags;
1174 flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline
1175 flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline)
1176
1177 FT_Error err = FT_Load_Glyph( fFace, glyph.getGlyphID(fBaseGlyphCount), flags);
1178
1179 if (err != 0) {
1180 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1181 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1182 path->reset();
1183 return;
1184 }
1185
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001186 if (fRec.fFlags & kEmbolden_Flag) {
1187 emboldenOutline(&fFace->glyph->outline);
1188 }
1189
reed@android.com8a1c16f2008-12-17 15:59:43 +00001190 FT_Outline_Funcs funcs;
1191
1192 funcs.move_to = move_proc;
1193 funcs.line_to = line_proc;
1194 funcs.conic_to = quad_proc;
1195 funcs.cubic_to = cubic_proc;
1196 funcs.shift = 0;
1197 funcs.delta = 0;
1198
1199 err = FT_Outline_Decompose(&fFace->glyph->outline, &funcs, path);
1200
1201 if (err != 0) {
1202 SkDEBUGF(("SkScalerContext_FreeType::generatePath: FT_Load_Glyph(glyph:%d flags:%d) returned 0x%x\n",
1203 glyph.getGlyphID(fBaseGlyphCount), flags, err));
1204 path->reset();
1205 return;
1206 }
1207
1208 path->close();
1209}
1210
1211void SkScalerContext_FreeType::generateFontMetrics(SkPaint::FontMetrics* mx,
1212 SkPaint::FontMetrics* my) {
1213 if (NULL == mx && NULL == my) {
1214 return;
1215 }
1216
1217 SkAutoMutexAcquire ac(gFTMutex);
1218
1219 if (this->setupSize()) {
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001220 ERROR:
reed@android.com8a1c16f2008-12-17 15:59:43 +00001221 if (mx) {
reed@android.com4516f472009-06-29 16:25:36 +00001222 sk_bzero(mx, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001223 }
1224 if (my) {
reed@android.com4516f472009-06-29 16:25:36 +00001225 sk_bzero(my, sizeof(SkPaint::FontMetrics));
reed@android.com8a1c16f2008-12-17 15:59:43 +00001226 }
1227 return;
1228 }
1229
reed@android.coma8a8b8b2009-05-04 15:00:11 +00001230 FT_Face face = fFace;
1231 int upem = face->units_per_EM;
1232 if (upem <= 0) {
1233 goto ERROR;
1234 }
1235
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001236 SkPoint pts[6];
1237 SkFixed ys[6];
reed@android.com8a1c16f2008-12-17 15:59:43 +00001238 SkFixed scaleY = fScaleY;
1239 SkFixed mxy = fMatrix22.xy;
1240 SkFixed myy = fMatrix22.yy;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001241 SkScalar xmin = SkIntToScalar(face->bbox.xMin) / upem;
1242 SkScalar xmax = SkIntToScalar(face->bbox.xMax) / upem;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001243
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001244 int leading = face->height - (face->ascender + -face->descender);
reed@android.com8a1c16f2008-12-17 15:59:43 +00001245 if (leading < 0) {
1246 leading = 0;
1247 }
1248
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001249 // Try to get the OS/2 table from the font. This contains the specific
1250 // average font width metrics which Windows uses.
1251 TT_OS2* os2 = (TT_OS2*) FT_Get_Sfnt_Table(face, ft_sfnt_os2);
1252
reed@android.com8a1c16f2008-12-17 15:59:43 +00001253 ys[0] = -face->bbox.yMax;
1254 ys[1] = -face->ascender;
1255 ys[2] = -face->descender;
1256 ys[3] = -face->bbox.yMin;
1257 ys[4] = leading;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001258 ys[5] = os2 ? os2->xAvgCharWidth : 0;
1259
1260 SkScalar x_height;
1261 if (os2 && os2->sxHeight) {
1262 x_height = SkFixedToScalar(SkMulDiv(fScaleX, os2->sxHeight, upem));
1263 } else {
1264 const FT_UInt x_glyph = FT_Get_Char_Index(fFace, 'x');
1265 if (x_glyph) {
1266 FT_BBox bbox;
1267 FT_Load_Glyph(fFace, x_glyph, fLoadGlyphFlags);
senorblanco@chromium.org4526a842010-02-05 23:08:20 +00001268 if (fRec.fFlags & kEmbolden_Flag) {
1269 emboldenOutline(&fFace->glyph->outline);
1270 }
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001271 FT_Outline_Get_CBox(&fFace->glyph->outline, &bbox);
1272 x_height = SkIntToScalar(bbox.yMax) / 64;
1273 } else {
1274 x_height = 0;
1275 }
1276 }
reed@android.com8a1c16f2008-12-17 15:59:43 +00001277
1278 // convert upem-y values into scalar points
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001279 for (int i = 0; i < 6; i++) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001280 SkFixed y = SkMulDiv(scaleY, ys[i], upem);
1281 SkFixed x = SkFixedMul(mxy, y);
1282 y = SkFixedMul(myy, y);
1283 pts[i].set(SkFixedToScalar(x), SkFixedToScalar(y));
1284 }
1285
1286 if (mx) {
1287 mx->fTop = pts[0].fX;
1288 mx->fAscent = pts[1].fX;
1289 mx->fDescent = pts[2].fX;
1290 mx->fBottom = pts[3].fX;
1291 mx->fLeading = pts[4].fX;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001292 mx->fAvgCharWidth = pts[5].fX;
1293 mx->fXMin = xmin;
1294 mx->fXMax = xmax;
1295 mx->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001296 }
1297 if (my) {
1298 my->fTop = pts[0].fY;
1299 my->fAscent = pts[1].fY;
1300 my->fDescent = pts[2].fY;
1301 my->fBottom = pts[3].fY;
1302 my->fLeading = pts[4].fY;
agl@chromium.orgcc3096b2009-04-22 22:09:04 +00001303 my->fAvgCharWidth = pts[5].fY;
1304 my->fXMin = xmin;
1305 my->fXMax = xmax;
1306 my->fXHeight = x_height;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001307 }
1308}
1309
1310////////////////////////////////////////////////////////////////////////
1311////////////////////////////////////////////////////////////////////////
1312
1313SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
reed@android.com62900b42009-02-11 15:07:19 +00001314 SkScalerContext_FreeType* c = SkNEW_ARGS(SkScalerContext_FreeType, (desc));
1315 if (!c->success()) {
1316 SkDELETE(c);
1317 c = NULL;
1318 }
1319 return c;
reed@android.com8a1c16f2008-12-17 15:59:43 +00001320}
1321
1322///////////////////////////////////////////////////////////////////////////////
1323
1324/* Export this so that other parts of our FonttHost port can make use of our
1325 ability to extract the name+style from a stream, using FreeType's api.
1326*/
1327SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name) {
1328 FT_Library library;
reed@android.combfbd4ff2009-07-23 17:44:41 +00001329 if (FT_Init_FreeType(&library)) {
reed@android.com8a1c16f2008-12-17 15:59:43 +00001330 name->set(NULL);
1331 return SkTypeface::kNormal;
1332 }
1333
1334 FT_Open_Args args;
1335 memset(&args, 0, sizeof(args));
1336
1337 const void* memoryBase = stream->getMemoryBase();
1338 FT_StreamRec streamRec;
1339
1340 if (NULL != memoryBase) {
1341 args.flags = FT_OPEN_MEMORY;
1342 args.memory_base = (const FT_Byte*)memoryBase;
1343 args.memory_size = stream->getLength();
1344 } else {
1345 memset(&streamRec, 0, sizeof(streamRec));
1346 streamRec.size = stream->read(NULL, 0);
1347 streamRec.descriptor.pointer = stream;
1348 streamRec.read = sk_stream_read;
1349 streamRec.close = sk_stream_close;
1350
1351 args.flags = FT_OPEN_STREAM;
1352 args.stream = &streamRec;
1353 }
1354
1355 FT_Face face;
1356 if (FT_Open_Face(library, &args, 0, &face)) {
1357 FT_Done_FreeType(library);
1358 name->set(NULL);
1359 return SkTypeface::kNormal;
1360 }
1361
1362 name->set(face->family_name);
1363 int style = SkTypeface::kNormal;
1364
1365 if (face->style_flags & FT_STYLE_FLAG_BOLD) {
1366 style |= SkTypeface::kBold;
1367 }
1368 if (face->style_flags & FT_STYLE_FLAG_ITALIC) {
1369 style |= SkTypeface::kItalic;
1370 }
1371
1372 FT_Done_Face(face);
1373 FT_Done_FreeType(library);
1374 return (SkTypeface::Style)style;
1375}