blob: 8438cc36112b096811c461bc41db20e526c9a8c0 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
reed@android.com0680d6c2008-12-19 19:46:15 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00009#include <vector>
10#ifdef SK_BUILD_FOR_MAC
11#import <ApplicationServices/ApplicationServices.h>
12#endif
reed@android.com0680d6c2008-12-19 19:46:15 +000013
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000014#ifdef SK_BUILD_FOR_IOS
15#include <CoreText/CoreText.h>
16#include <CoreGraphics/CoreGraphics.h>
17#include <CoreFoundation/CoreFoundation.h>
18#endif
19
20#include "SkFontHost.h"
21#include "SkCGUtils.h"
22#include "SkColorPriv.h"
23#include "SkDescriptor.h"
24#include "SkEndian.h"
25#include "SkFontDescriptor.h"
26#include "SkFloatingPoint.h"
27#include "SkGlyph.h"
28#include "SkMaskGamma.h"
29#include "SkSFNTHeader.h"
30#include "SkOTTable_glyf.h"
31#include "SkOTTable_head.h"
32#include "SkOTTable_hhea.h"
33#include "SkOTTable_loca.h"
34#include "SkOTUtils.h"
35#include "SkPaint.h"
36#include "SkPath.h"
37#include "SkString.h"
38#include "SkStream.h"
39#include "SkThread.h"
40#include "SkTypeface_mac.h"
41#include "SkUtils.h"
42#include "SkTypefaceCache.h"
43
44class SkScalerContext_Mac;
45
46// Being templated and taking const T* prevents calling
47// CFSafeRelease(autoCFRelease) through implicit conversion.
48template <typename T> static void CFSafeRelease(/*CFTypeRef*/const T* cfTypeRef) {
49 if (cfTypeRef) {
50 CFRelease(cfTypeRef);
51 }
52}
53
54// Being templated and taking const T* prevents calling
55// CFSafeRetain(autoCFRelease) through implicit conversion.
56template <typename T> static void CFSafeRetain(/*CFTypeRef*/const T* cfTypeRef) {
57 if (cfTypeRef) {
58 CFRetain(cfTypeRef);
59 }
60}
61
62/** Acts like a CFRef, but calls CFSafeRelease when it goes out of scope. */
63template<typename CFRef> class AutoCFRelease : private SkNoncopyable {
64public:
65 explicit AutoCFRelease(CFRef cfRef = NULL) : fCFRef(cfRef) { }
66 ~AutoCFRelease() { CFSafeRelease(fCFRef); }
67
68 void reset(CFRef that = NULL) {
69 CFSafeRetain(that);
70 CFSafeRelease(fCFRef);
71 fCFRef = that;
72 }
73
74 AutoCFRelease& operator =(CFRef that) {
75 reset(that);
76 return *this;
77 }
78
79 operator CFRef() const { return fCFRef; }
80 CFRef get() const { return fCFRef; }
81
82private:
83 CFRef fCFRef;
84};
85
86template<typename T> class AutoCGTable : SkNoncopyable {
87public:
88 AutoCGTable(CGFontRef font)
89 //Undocumented: the tag parameter in this call is expected in machine order and not BE order.
90 : fCFData(CGFontCopyTableForTag(font, SkSetFourByteTag(T::TAG0, T::TAG1, T::TAG2, T::TAG3)))
91 , fData(fCFData ? reinterpret_cast<const T*>(CFDataGetBytePtr(fCFData)) : NULL)
92 { }
93
94 const T* operator->() const { return fData; }
95
96private:
97 AutoCFRelease<CFDataRef> fCFData;
98public:
99 const T* fData;
100};
101
102// inline versions of these rect helpers
103
104static bool CGRectIsEmpty_inline(const CGRect& rect) {
105 return rect.size.width <= 0 || rect.size.height <= 0;
106}
107
108static void CGRectInset_inline(CGRect* rect, CGFloat dx, CGFloat dy) {
109 rect->origin.x += dx;
110 rect->origin.y += dy;
111 rect->size.width -= dx * 2;
112 rect->size.height -= dy * 2;
113}
114
115static CGFloat CGRectGetMinX_inline(const CGRect& rect) {
116 return rect.origin.x;
117}
118
119static CGFloat CGRectGetMaxX_inline(const CGRect& rect) {
120 return rect.origin.x + rect.size.width;
121}
122
123static CGFloat CGRectGetMinY_inline(const CGRect& rect) {
124 return rect.origin.y;
125}
126
127static CGFloat CGRectGetMaxY_inline(const CGRect& rect) {
128 return rect.origin.y + rect.size.height;
129}
130
131static CGFloat CGRectGetWidth_inline(const CGRect& rect) {
132 return rect.size.width;
133}
134
135///////////////////////////////////////////////////////////////////////////////
136
137static void sk_memset_rect32(uint32_t* ptr, uint32_t value,
138 size_t width, size_t height, size_t rowBytes) {
139 SkASSERT(width);
140 SkASSERT(width * sizeof(uint32_t) <= rowBytes);
141
142 if (width >= 32) {
143 while (height) {
144 sk_memset32(ptr, value, width);
145 ptr = (uint32_t*)((char*)ptr + rowBytes);
146 height -= 1;
147 }
148 return;
149 }
150
151 rowBytes -= width * sizeof(uint32_t);
152
153 if (width >= 8) {
154 while (height) {
155 int w = width;
156 do {
157 *ptr++ = value; *ptr++ = value;
158 *ptr++ = value; *ptr++ = value;
159 *ptr++ = value; *ptr++ = value;
160 *ptr++ = value; *ptr++ = value;
161 w -= 8;
162 } while (w >= 8);
163 while (--w >= 0) {
164 *ptr++ = value;
165 }
166 ptr = (uint32_t*)((char*)ptr + rowBytes);
167 height -= 1;
168 }
169 } else {
170 while (height) {
171 int w = width;
172 do {
173 *ptr++ = value;
174 } while (--w > 0);
175 ptr = (uint32_t*)((char*)ptr + rowBytes);
176 height -= 1;
177 }
178 }
179}
180
181#include <sys/utsname.h>
182
183typedef uint32_t CGRGBPixel;
184
185static unsigned CGRGBPixel_getAlpha(CGRGBPixel pixel) {
186 return pixel & 0xFF;
187}
188
189// The calls to support subpixel are present in 10.5, but are not included in
190// the 10.5 SDK. The needed calls have been extracted from the 10.6 SDK and are
191// included below. To verify that CGContextSetShouldSubpixelQuantizeFonts, for
192// instance, is present in the 10.5 CoreGraphics libary, use:
193// cd /Developer/SDKs/MacOSX10.5.sdk/System/Library/Frameworks/
194// cd ApplicationServices.framework/Frameworks/CoreGraphics.framework/
195// nm CoreGraphics | grep CGContextSetShouldSubpixelQuantizeFonts
196
197#if !defined(MAC_OS_X_VERSION_10_6) || (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6)
198CG_EXTERN void CGContextSetAllowsFontSmoothing(CGContextRef context, bool value);
199CG_EXTERN void CGContextSetAllowsFontSubpixelPositioning(CGContextRef context, bool value);
200CG_EXTERN void CGContextSetShouldSubpixelPositionFonts(CGContextRef context, bool value);
201CG_EXTERN void CGContextSetAllowsFontSubpixelQuantization(CGContextRef context, bool value);
202CG_EXTERN void CGContextSetShouldSubpixelQuantizeFonts(CGContextRef context, bool value);
203#endif
204
205static const char FONT_DEFAULT_NAME[] = "Lucida Sans";
206
207// See Source/WebKit/chromium/base/mac/mac_util.mm DarwinMajorVersionInternal for original source.
208static int readVersion() {
209 struct utsname info;
210 if (uname(&info) != 0) {
211 SkDebugf("uname failed\n");
212 return 0;
213 }
214 if (strcmp(info.sysname, "Darwin") != 0) {
215 SkDebugf("unexpected uname sysname %s\n", info.sysname);
216 return 0;
217 }
218 char* dot = strchr(info.release, '.');
219 if (!dot) {
220 SkDebugf("expected dot in uname release %s\n", info.release);
221 return 0;
222 }
223 int version = atoi(info.release);
224 if (version == 0) {
225 SkDebugf("could not parse uname release %s\n", info.release);
226 }
227 return version;
228}
229
230static int darwinVersion() {
231 static int darwin_version = readVersion();
232 return darwin_version;
233}
234
235static bool isLeopard() {
236 return darwinVersion() == 9;
237}
238
239static bool isSnowLeopard() {
240 return darwinVersion() == 10;
241}
242
243static bool isLion() {
244 return darwinVersion() == 11;
245}
246
247static bool isMountainLion() {
248 return darwinVersion() == 12;
249}
250
251static bool isLCDFormat(unsigned format) {
252 return SkMask::kLCD16_Format == format || SkMask::kLCD32_Format == format;
253}
254
255static CGFloat ScalarToCG(SkScalar scalar) {
256 if (sizeof(CGFloat) == sizeof(float)) {
257 return SkScalarToFloat(scalar);
258 } else {
259 SkASSERT(sizeof(CGFloat) == sizeof(double));
260 return (CGFloat) SkScalarToDouble(scalar);
261 }
262}
263
264static SkScalar CGToScalar(CGFloat cgFloat) {
265 if (sizeof(CGFloat) == sizeof(float)) {
266 return SkFloatToScalar(cgFloat);
267 } else {
268 SkASSERT(sizeof(CGFloat) == sizeof(double));
269 return SkDoubleToScalar(cgFloat);
270 }
271}
272
273static CGAffineTransform MatrixToCGAffineTransform(const SkMatrix& matrix,
274 SkScalar sx = SK_Scalar1,
275 SkScalar sy = SK_Scalar1) {
276 return CGAffineTransformMake( ScalarToCG(matrix[SkMatrix::kMScaleX] * sx),
277 -ScalarToCG(matrix[SkMatrix::kMSkewY] * sy),
278 -ScalarToCG(matrix[SkMatrix::kMSkewX] * sx),
279 ScalarToCG(matrix[SkMatrix::kMScaleY] * sy),
280 ScalarToCG(matrix[SkMatrix::kMTransX] * sx),
281 ScalarToCG(matrix[SkMatrix::kMTransY] * sy));
282}
283
284static SkScalar getFontScale(CGFontRef cgFont) {
285 int unitsPerEm = CGFontGetUnitsPerEm(cgFont);
286 return SkScalarInvert(SkIntToScalar(unitsPerEm));
287}
288
289///////////////////////////////////////////////////////////////////////////////
290
291#define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)
292#define BITMAP_INFO_GRAY (kCGImageAlphaNone)
293
294/**
295 * There does not appear to be a publicly accessable API for determining if lcd
296 * font smoothing will be applied if we request it. The main issue is that if
297 * smoothing is applied a gamma of 2.0 will be used, if not a gamma of 1.0.
298 */
299static bool supports_LCD() {
300 static int gSupportsLCD = -1;
301 if (gSupportsLCD >= 0) {
302 return (bool) gSupportsLCD;
303 }
304 uint32_t rgb = 0;
305 AutoCFRelease<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB());
306 AutoCFRelease<CGContextRef> cgContext(CGBitmapContextCreate(&rgb, 1, 1, 8, 4,
307 colorspace, BITMAP_INFO_RGB));
308 CGContextSelectFont(cgContext, "Helvetica", 16, kCGEncodingMacRoman);
309 CGContextSetShouldSmoothFonts(cgContext, true);
310 CGContextSetShouldAntialias(cgContext, true);
311 CGContextSetTextDrawingMode(cgContext, kCGTextFill);
312 CGContextSetGrayFillColor(cgContext, 1, 1);
313 CGContextShowTextAtPoint(cgContext, -1, 0, "|", 1);
314 uint32_t r = (rgb >> 16) & 0xFF;
315 uint32_t g = (rgb >> 8) & 0xFF;
316 uint32_t b = (rgb >> 0) & 0xFF;
317 gSupportsLCD = (r != g || r != b);
318 return (bool) gSupportsLCD;
319}
320
321class Offscreen {
322public:
323 Offscreen();
324
325 CGRGBPixel* getCG(const SkScalerContext_Mac& context, const SkGlyph& glyph,
326 CGGlyph glyphID, size_t* rowBytesPtr,
327 bool generateA8FromLCD);
328
329private:
330 enum {
331 kSize = 32 * 32 * sizeof(CGRGBPixel)
332 };
333 SkAutoSMalloc<kSize> fImageStorage;
334 AutoCFRelease<CGColorSpaceRef> fRGBSpace;
335
336 // cached state
337 AutoCFRelease<CGContextRef> fCG;
338 SkISize fSize;
339 bool fDoAA;
340 bool fDoLCD;
341
342 static int RoundSize(int dimension) {
343 return SkNextPow2(dimension);
344 }
345};
346
347Offscreen::Offscreen() : fRGBSpace(NULL), fCG(NULL) {
348 fSize.set(0, 0);
349}
350
351///////////////////////////////////////////////////////////////////////////////
352
353static SkTypeface::Style computeStyleBits(CTFontRef font, bool* isMonospace) {
354 unsigned style = SkTypeface::kNormal;
355 CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font);
356
357 if (traits & kCTFontBoldTrait) {
358 style |= SkTypeface::kBold;
359 }
360 if (traits & kCTFontItalicTrait) {
361 style |= SkTypeface::kItalic;
362 }
363 if (isMonospace) {
364 *isMonospace = (traits & kCTFontMonoSpaceTrait) != 0;
365 }
366 return (SkTypeface::Style)style;
367}
368
369static SkFontID CTFontRef_to_SkFontID(CTFontRef fontRef) {
370 SkFontID id = 0;
371// CTFontGetPlatformFont and ATSFontRef are not supported on iOS, so we have to
372// bracket this to be Mac only.
373#ifdef SK_BUILD_FOR_MAC
374 ATSFontRef ats = CTFontGetPlatformFont(fontRef, NULL);
375 id = (SkFontID)ats;
376 if (id != 0) {
377 id &= 0x3FFFFFFF; // make top two bits 00
378 return id;
379 }
380#endif
381 // CTFontGetPlatformFont returns NULL if the font is local
382 // (e.g., was created by a CSS3 @font-face rule).
383 AutoCFRelease<CGFontRef> cgFont(CTFontCopyGraphicsFont(fontRef, NULL));
384 AutoCGTable<SkOTTableHead> headTable(cgFont);
385 if (headTable.fData) {
386 id = (SkFontID) headTable->checksumAdjustment;
387 id = (id & 0x3FFFFFFF) | 0x40000000; // make top two bits 01
388 }
389 // well-formed fonts have checksums, but as a last resort, use the pointer.
390 if (id == 0) {
391 id = (SkFontID) (uintptr_t) fontRef;
392 id = (id & 0x3FFFFFFF) | 0x80000000; // make top two bits 10
393 }
394 return id;
395}
396
397class SkTypeface_Mac : public SkTypeface {
398public:
399 SkTypeface_Mac(SkTypeface::Style style, SkFontID fontID, bool isMonospace,
400 CTFontRef fontRef, const char name[])
401 : SkTypeface(style, fontID, isMonospace)
402 , fName(name)
403 , fFontRef(fontRef) // caller has already called CFRetain for us
404 {
405 SkASSERT(fontRef);
406 }
407
408 SkString fName;
409 AutoCFRelease<CTFontRef> fFontRef;
410
411protected:
412 friend class SkFontHost; // to access our protected members for deprecated methods
413
414 virtual int onGetUPEM() const SK_OVERRIDE;
415 virtual int onGetTableTags(SkFontTableTag tags[]) const SK_OVERRIDE;
416 virtual size_t onGetTableData(SkFontTableTag, size_t offset,
417 size_t length, void* data) const SK_OVERRIDE;
418 virtual SkScalerContext* onCreateScalerContext(const SkDescriptor*) const SK_OVERRIDE;
419 virtual void onFilterRec(SkScalerContextRec*) const SK_OVERRIDE;
420 virtual void onGetFontDescriptor(SkFontDescriptor*) const SK_OVERRIDE;
reed@google.com2689f612013-03-20 20:01:47 +0000421 virtual SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics(
422 SkAdvancedTypefaceMetrics::PerGlyphInfo,
423 const uint32_t*, uint32_t) const SK_OVERRIDE;
skia.committer@gmail.comc1641fc2013-03-21 07:01:39 +0000424
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000425private:
426 typedef SkTypeface INHERITED;
427};
428
429static SkTypeface* NewFromFontRef(CTFontRef fontRef, const char name[]) {
430 SkASSERT(fontRef);
431 bool isMonospace;
432 SkTypeface::Style style = computeStyleBits(fontRef, &isMonospace);
433 SkFontID fontID = CTFontRef_to_SkFontID(fontRef);
434
435 return new SkTypeface_Mac(style, fontID, isMonospace, fontRef, name);
436}
437
438static SkTypeface* NewFromName(const char familyName[], SkTypeface::Style theStyle) {
439 CTFontRef ctFont = NULL;
440
441 CTFontSymbolicTraits ctFontTraits = 0;
442 if (theStyle & SkTypeface::kBold) {
443 ctFontTraits |= kCTFontBoldTrait;
444 }
445 if (theStyle & SkTypeface::kItalic) {
446 ctFontTraits |= kCTFontItalicTrait;
447 }
448
449 // Create the font info
450 AutoCFRelease<CFStringRef> cfFontName(
451 CFStringCreateWithCString(NULL, familyName, kCFStringEncodingUTF8));
452
453 AutoCFRelease<CFNumberRef> cfFontTraits(
454 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &ctFontTraits));
455
456 AutoCFRelease<CFMutableDictionaryRef> cfAttributes(
457 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
458 &kCFTypeDictionaryKeyCallBacks,
459 &kCFTypeDictionaryValueCallBacks));
460
461 AutoCFRelease<CFMutableDictionaryRef> cfTraits(
462 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
463 &kCFTypeDictionaryKeyCallBacks,
464 &kCFTypeDictionaryValueCallBacks));
465
466 // Create the font
467 if (cfFontName != NULL && cfFontTraits != NULL && cfAttributes != NULL && cfTraits != NULL) {
468 CFDictionaryAddValue(cfTraits, kCTFontSymbolicTrait, cfFontTraits);
469
470 CFDictionaryAddValue(cfAttributes, kCTFontFamilyNameAttribute, cfFontName);
471 CFDictionaryAddValue(cfAttributes, kCTFontTraitsAttribute, cfTraits);
472
473 AutoCFRelease<CTFontDescriptorRef> ctFontDesc(
474 CTFontDescriptorCreateWithAttributes(cfAttributes));
475
476 if (ctFontDesc != NULL) {
477 if (isLeopard()) {
478 // CTFontCreateWithFontDescriptor on Leopard ignores the name
479 AutoCFRelease<CTFontRef> ctNamed(CTFontCreateWithName(cfFontName, 1, NULL));
480 ctFont = CTFontCreateCopyWithAttributes(ctNamed, 1, NULL, ctFontDesc);
481 } else {
482 ctFont = CTFontCreateWithFontDescriptor(ctFontDesc, 0, NULL);
483 }
484 }
485 }
486
487 return ctFont ? NewFromFontRef(ctFont, familyName) : NULL;
488}
489
490static CTFontRef GetFontRefFromFontID(SkFontID fontID) {
491 SkTypeface_Mac* face = reinterpret_cast<SkTypeface_Mac*>(SkTypefaceCache::FindByID(fontID));
492 return face ? face->fFontRef.get() : NULL;
493}
494
495static SkTypeface* GetDefaultFace() {
496 SK_DECLARE_STATIC_MUTEX(gMutex);
497 SkAutoMutexAcquire ma(gMutex);
498
499 static SkTypeface* gDefaultFace;
500
501 if (NULL == gDefaultFace) {
502 gDefaultFace = NewFromName(FONT_DEFAULT_NAME, SkTypeface::kNormal);
503 SkTypefaceCache::Add(gDefaultFace, SkTypeface::kNormal);
504 }
505 return gDefaultFace;
506}
507
508///////////////////////////////////////////////////////////////////////////////
509
510extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);
511CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face) {
512 const SkTypeface_Mac* macface = (const SkTypeface_Mac*)face;
513 return macface ? macface->fFontRef.get() : NULL;
514}
515
516/* This function is visible on the outside. It first searches the cache, and if
517 * not found, returns a new entry (after adding it to the cache).
518 */
519SkTypeface* SkCreateTypefaceFromCTFont(CTFontRef fontRef) {
520 SkFontID fontID = CTFontRef_to_SkFontID(fontRef);
521 SkTypeface* face = SkTypefaceCache::FindByID(fontID);
522 if (face) {
523 face->ref();
524 } else {
525 face = NewFromFontRef(fontRef, NULL);
526 SkTypefaceCache::Add(face, face->style());
527 // NewFromFontRef doesn't retain the parameter, but the typeface it
528 // creates does release it in its destructor, so we balance that with
529 // a retain call here.
530 CFRetain(fontRef);
531 }
532 SkASSERT(face->getRefCnt() > 1);
533 return face;
534}
535
536struct NameStyleRec {
537 const char* fName;
538 SkTypeface::Style fStyle;
539};
540
541static bool FindByNameStyle(SkTypeface* face, SkTypeface::Style style,
542 void* ctx) {
543 const SkTypeface_Mac* mface = reinterpret_cast<SkTypeface_Mac*>(face);
544 const NameStyleRec* rec = reinterpret_cast<const NameStyleRec*>(ctx);
545
546 return rec->fStyle == style && mface->fName.equals(rec->fName);
547}
548
549static const char* map_css_names(const char* name) {
550 static const struct {
551 const char* fFrom; // name the caller specified
552 const char* fTo; // "canonical" name we map to
553 } gPairs[] = {
554 { "sans-serif", "Helvetica" },
555 { "serif", "Times" },
556 { "monospace", "Courier" }
557 };
558
559 for (size_t i = 0; i < SK_ARRAY_COUNT(gPairs); i++) {
560 if (strcmp(name, gPairs[i].fFrom) == 0) {
561 return gPairs[i].fTo;
562 }
563 }
564 return name; // no change
565}
566
567SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
568 const char familyName[],
569 SkTypeface::Style style) {
570 if (familyName) {
571 familyName = map_css_names(familyName);
572 }
573
574 // Clone an existing typeface
575 // TODO: only clone if style matches the familyFace's style...
576 if (familyName == NULL && familyFace != NULL) {
577 familyFace->ref();
578 return const_cast<SkTypeface*>(familyFace);
579 }
580
581 if (!familyName || !*familyName) {
582 familyName = FONT_DEFAULT_NAME;
583 }
584
585 NameStyleRec rec = { familyName, style };
586 SkTypeface* face = SkTypefaceCache::FindByProcAndRef(FindByNameStyle, &rec);
587
588 if (NULL == face) {
589 face = NewFromName(familyName, style);
590 if (face) {
591 SkTypefaceCache::Add(face, style);
592 } else {
593 face = GetDefaultFace();
594 face->ref();
595 }
596 }
597 return face;
598}
599
600static void flip(SkMatrix* matrix) {
601 matrix->setSkewX(-matrix->getSkewX());
602 matrix->setSkewY(-matrix->getSkewY());
603}
604
605///////////////////////////////////////////////////////////////////////////////
606
607struct GlyphRect {
608 int16_t fMinX;
609 int16_t fMinY;
610 int16_t fMaxX;
611 int16_t fMaxY;
612};
613
614class SkScalerContext_Mac : public SkScalerContext {
615public:
reed@google.com0da48612013-03-19 16:06:52 +0000616 SkScalerContext_Mac(SkTypeface_Mac*, const SkDescriptor*);
617 virtual ~SkScalerContext_Mac();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000618
619
620protected:
621 unsigned generateGlyphCount(void) SK_OVERRIDE;
622 uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE;
623 void generateAdvance(SkGlyph* glyph) SK_OVERRIDE;
624 void generateMetrics(SkGlyph* glyph) SK_OVERRIDE;
625 void generateImage(const SkGlyph& glyph) SK_OVERRIDE;
626 void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE;
627 void generateFontMetrics(SkPaint::FontMetrics* mX, SkPaint::FontMetrics* mY) SK_OVERRIDE;
628
629private:
630 static void CTPathElement(void *info, const CGPathElement *element);
631 uint16_t getFBoundingBoxesGlyphOffset();
632 void getVerticalOffset(CGGlyph glyphID, SkIPoint* offset) const;
633 bool generateBBoxes();
634
635 CGAffineTransform fTransform;
636 SkMatrix fUnitMatrix; // without font size
637 SkMatrix fVerticalMatrix; // unit rotated
638 SkMatrix fMatrix; // with font size
639 SkMatrix fFBoundingBoxesMatrix; // lion-specific fix
640 Offscreen fOffscreen;
641 AutoCFRelease<CTFontRef> fCTFont;
642 AutoCFRelease<CTFontRef> fCTVerticalFont; // for vertical advance
643 AutoCFRelease<CGFontRef> fCGFont;
644 GlyphRect* fFBoundingBoxes;
645 uint16_t fFBoundingBoxesGlyphOffset;
646 uint16_t fGlyphCount;
647 bool fGeneratedFBoundingBoxes;
648 bool fDoSubPosition;
649 bool fVertical;
650
651 friend class Offscreen;
reed@google.com0da48612013-03-19 16:06:52 +0000652
653 typedef SkScalerContext INHERITED;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000654};
655
reed@google.com0da48612013-03-19 16:06:52 +0000656SkScalerContext_Mac::SkScalerContext_Mac(SkTypeface_Mac* typeface,
657 const SkDescriptor* desc)
658 : INHERITED(typeface, desc)
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000659 , fFBoundingBoxes(NULL)
660 , fFBoundingBoxesGlyphOffset(0)
661 , fGeneratedFBoundingBoxes(false)
662{
reed@google.com2689f612013-03-20 20:01:47 +0000663 CTFontRef ctFont = typeface->fFontRef.get();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000664 CFIndex numGlyphs = CTFontGetGlyphCount(ctFont);
665
666 // Get the state we need
667 fRec.getSingleMatrix(&fMatrix);
668 fUnitMatrix = fMatrix;
669
670 // extract the font size out of the matrix, but leave the skewing for italic
671 SkScalar reciprocal = SkScalarInvert(fRec.fTextSize);
672 fUnitMatrix.preScale(reciprocal, reciprocal);
673
674 SkASSERT(numGlyphs >= 1 && numGlyphs <= 0xFFFF);
675
676 fTransform = MatrixToCGAffineTransform(fMatrix);
677
678 CGAffineTransform transform;
679 CGFloat unitFontSize;
680 if (isLeopard()) {
681 // passing 1 for pointSize to Leopard sets the font size to 1 pt.
682 // pass the CoreText size explicitly
683 transform = MatrixToCGAffineTransform(fUnitMatrix);
684 unitFontSize = SkScalarToFloat(fRec.fTextSize);
685 } else {
686 // since our matrix includes everything, we pass 1 for pointSize
687 transform = fTransform;
688 unitFontSize = 1;
689 }
690 flip(&fUnitMatrix); // flip to fix up bounds later
691 fVertical = SkToBool(fRec.fFlags & kVertical_Flag);
692 AutoCFRelease<CTFontDescriptorRef> ctFontDesc;
693 if (fVertical) {
694 AutoCFRelease<CFMutableDictionaryRef> cfAttributes(CFDictionaryCreateMutable(
695 kCFAllocatorDefault, 0,
696 &kCFTypeDictionaryKeyCallBacks,
697 &kCFTypeDictionaryValueCallBacks));
698 if (cfAttributes) {
699 CTFontOrientation ctOrientation = kCTFontVerticalOrientation;
700 AutoCFRelease<CFNumberRef> cfVertical(CFNumberCreate(
701 kCFAllocatorDefault, kCFNumberSInt32Type, &ctOrientation));
702 CFDictionaryAddValue(cfAttributes, kCTFontOrientationAttribute, cfVertical);
703 ctFontDesc = CTFontDescriptorCreateWithAttributes(cfAttributes);
704 }
705 }
706 fCTFont = CTFontCreateCopyWithAttributes(ctFont, unitFontSize, &transform, ctFontDesc);
707 fCGFont = CTFontCopyGraphicsFont(fCTFont, NULL);
708 if (fVertical) {
709 CGAffineTransform rotateLeft = CGAffineTransformMake(0, -1, 1, 0, 0, 0);
710 transform = CGAffineTransformConcat(rotateLeft, transform);
711 fCTVerticalFont = CTFontCreateCopyWithAttributes(ctFont, unitFontSize, &transform, NULL);
712 fVerticalMatrix = fUnitMatrix;
713 if (isSnowLeopard()) {
714 SkScalar scale = SkScalarMul(fRec.fTextSize, getFontScale(fCGFont));
715 fVerticalMatrix.preScale(scale, scale);
716 } else {
717 fVerticalMatrix.preRotate(SkIntToScalar(90));
718 }
719 fVerticalMatrix.postScale(SK_Scalar1, -SK_Scalar1);
720 }
721 fGlyphCount = SkToU16(numGlyphs);
722 fDoSubPosition = SkToBool(fRec.fFlags & kSubpixelPositioning_Flag);
723}
724
725SkScalerContext_Mac::~SkScalerContext_Mac() {
726 delete[] fFBoundingBoxes;
727}
728
729CGRGBPixel* Offscreen::getCG(const SkScalerContext_Mac& context, const SkGlyph& glyph,
730 CGGlyph glyphID, size_t* rowBytesPtr,
731 bool generateA8FromLCD) {
732 if (!fRGBSpace) {
733 //It doesn't appear to matter what color space is specified.
734 //Regular blends and antialiased text are always (s*a + d*(1-a))
735 //and smoothed text is always g=2.0.
736 fRGBSpace = CGColorSpaceCreateDeviceRGB();
737 }
738
739 // default to kBW_Format
740 bool doAA = false;
741 bool doLCD = false;
742
743 if (SkMask::kBW_Format != glyph.fMaskFormat) {
744 doLCD = true;
745 doAA = true;
746 }
747
748 // FIXME: lcd smoothed un-hinted rasterization unsupported.
749 if (!generateA8FromLCD && SkMask::kA8_Format == glyph.fMaskFormat) {
750 doLCD = false;
751 doAA = true;
752 }
753
754 size_t rowBytes = fSize.fWidth * sizeof(CGRGBPixel);
755 if (!fCG || fSize.fWidth < glyph.fWidth || fSize.fHeight < glyph.fHeight) {
756 if (fSize.fWidth < glyph.fWidth) {
757 fSize.fWidth = RoundSize(glyph.fWidth);
758 }
759 if (fSize.fHeight < glyph.fHeight) {
760 fSize.fHeight = RoundSize(glyph.fHeight);
761 }
762
763 rowBytes = fSize.fWidth * sizeof(CGRGBPixel);
764 void* image = fImageStorage.reset(rowBytes * fSize.fHeight);
765 fCG = CGBitmapContextCreate(image, fSize.fWidth, fSize.fHeight, 8,
766 rowBytes, fRGBSpace, BITMAP_INFO_RGB);
767
768 // skia handles quantization itself, so we disable this for cg to get
769 // full fractional data from them.
770 CGContextSetAllowsFontSubpixelQuantization(fCG, false);
771 CGContextSetShouldSubpixelQuantizeFonts(fCG, false);
772
773 CGContextSetTextDrawingMode(fCG, kCGTextFill);
774 CGContextSetFont(fCG, context.fCGFont);
775 CGContextSetFontSize(fCG, 1);
776 CGContextSetTextMatrix(fCG, context.fTransform);
777
778 CGContextSetAllowsFontSubpixelPositioning(fCG, context.fDoSubPosition);
779 CGContextSetShouldSubpixelPositionFonts(fCG, context.fDoSubPosition);
780
781 // Draw white on black to create mask.
782 // TODO: Draw black on white and invert, CG has a special case codepath.
783 CGContextSetGrayFillColor(fCG, 1.0f, 1.0f);
784
785 // force our checks below to happen
786 fDoAA = !doAA;
787 fDoLCD = !doLCD;
788 }
789
790 if (fDoAA != doAA) {
791 CGContextSetShouldAntialias(fCG, doAA);
792 fDoAA = doAA;
793 }
794 if (fDoLCD != doLCD) {
795 CGContextSetShouldSmoothFonts(fCG, doLCD);
796 fDoLCD = doLCD;
797 }
798
799 CGRGBPixel* image = (CGRGBPixel*)fImageStorage.get();
800 // skip rows based on the glyph's height
801 image += (fSize.fHeight - glyph.fHeight) * fSize.fWidth;
802
803 // erase to black
804 sk_memset_rect32(image, 0, glyph.fWidth, glyph.fHeight, rowBytes);
805
806 float subX = 0;
807 float subY = 0;
808 if (context.fDoSubPosition) {
809 subX = SkFixedToFloat(glyph.getSubXFixed());
810 subY = SkFixedToFloat(glyph.getSubYFixed());
811 }
812 if (context.fVertical) {
813 SkIPoint offset;
814 context.getVerticalOffset(glyphID, &offset);
815 subX += offset.fX;
816 subY += offset.fY;
817 }
818 CGContextShowGlyphsAtPoint(fCG, -glyph.fLeft + subX,
819 glyph.fTop + glyph.fHeight - subY,
820 &glyphID, 1);
821
822 SkASSERT(rowBytesPtr);
823 *rowBytesPtr = rowBytes;
824 return image;
825}
826
827void SkScalerContext_Mac::getVerticalOffset(CGGlyph glyphID, SkIPoint* offset) const {
828 CGSize vertOffset;
829 CTFontGetVerticalTranslationsForGlyphs(fCTVerticalFont, &glyphID, &vertOffset, 1);
830 const SkPoint trans = {CGToScalar(vertOffset.width),
831 CGToScalar(vertOffset.height)};
832 SkPoint floatOffset;
833 fVerticalMatrix.mapPoints(&floatOffset, &trans, 1);
834 if (!isSnowLeopard()) {
835 // SnowLeopard fails to apply the font's matrix to the vertical metrics,
836 // but Lion and Leopard do. The unit matrix describes the font's matrix at
837 // point size 1. There may be some way to avoid mapping here by setting up
838 // fVerticalMatrix differently, but this works for now.
839 fUnitMatrix.mapPoints(&floatOffset, 1);
840 }
841 offset->fX = SkScalarRound(floatOffset.fX);
842 offset->fY = SkScalarRound(floatOffset.fY);
843}
844
845uint16_t SkScalerContext_Mac::getFBoundingBoxesGlyphOffset() {
846 if (fFBoundingBoxesGlyphOffset) {
847 return fFBoundingBoxesGlyphOffset;
848 }
849 fFBoundingBoxesGlyphOffset = fGlyphCount; // fallback for all fonts
850 AutoCGTable<SkOTTableHorizontalHeader> hheaTable(fCGFont);
851 if (hheaTable.fData) {
852 fFBoundingBoxesGlyphOffset = SkEndian_SwapBE16(hheaTable->numberOfHMetrics);
853 }
854 return fFBoundingBoxesGlyphOffset;
855}
reed@android.com0680d6c2008-12-19 19:46:15 +0000856
reed@android.comfeda2f92010-05-19 13:47:05 +0000857/*
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000858 * Lion has a bug in CTFontGetBoundingRectsForGlyphs which returns a bad value
859 * in theBounds.origin.x for fonts whose numOfLogHorMetrics is less than its
860 * glyph count. This workaround reads the glyph bounds from the font directly.
861 *
862 * The table is computed only if the font is a TrueType font, if the glyph
863 * value is >= fFBoundingBoxesGlyphOffset. (called only if fFBoundingBoxesGlyphOffset < fGlyphCount).
864 *
865 * TODO: A future optimization will compute fFBoundingBoxes once per CGFont, and
866 * compute fFBoundingBoxesMatrix once per font context.
867 */
868bool SkScalerContext_Mac::generateBBoxes() {
869 if (fGeneratedFBoundingBoxes) {
870 return NULL != fFBoundingBoxes;
871 }
872 fGeneratedFBoundingBoxes = true;
reed@android.com0bf64d42009-03-09 17:22:22 +0000873
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000874 AutoCGTable<SkOTTableHead> headTable(fCGFont);
875 if (!headTable.fData) {
876 return false;
877 }
878
879 AutoCGTable<SkOTTableIndexToLocation> locaTable(fCGFont);
880 if (!locaTable.fData) {
881 return false;
882 }
883
884 AutoCGTable<SkOTTableGlyph> glyfTable(fCGFont);
885 if (!glyfTable.fData) {
886 return false;
887 }
888
889 uint16_t entries = fGlyphCount - fFBoundingBoxesGlyphOffset;
890 fFBoundingBoxes = new GlyphRect[entries];
891
892 SkOTTableHead::IndexToLocFormat locaFormat = headTable->indexToLocFormat;
893 SkOTTableGlyph::Iterator glyphDataIter(*glyfTable.fData, *locaTable.fData, locaFormat);
894 glyphDataIter.advance(fFBoundingBoxesGlyphOffset);
895 for (uint16_t boundingBoxesIndex = 0; boundingBoxesIndex < entries; ++boundingBoxesIndex) {
896 const SkOTTableGlyphData* glyphData = glyphDataIter.next();
897 GlyphRect& rect = fFBoundingBoxes[boundingBoxesIndex];
898 rect.fMinX = SkEndian_SwapBE16(glyphData->xMin);
899 rect.fMinY = SkEndian_SwapBE16(glyphData->yMin);
900 rect.fMaxX = SkEndian_SwapBE16(glyphData->xMax);
901 rect.fMaxY = SkEndian_SwapBE16(glyphData->yMax);
902 }
903 fFBoundingBoxesMatrix = fMatrix;
904 flip(&fFBoundingBoxesMatrix);
905 SkScalar fontScale = getFontScale(fCGFont);
906 fFBoundingBoxesMatrix.preScale(fontScale, fontScale);
907 return true;
908}
909
910unsigned SkScalerContext_Mac::generateGlyphCount(void) {
911 return fGlyphCount;
912}
913
914uint16_t SkScalerContext_Mac::generateCharToGlyph(SkUnichar uni) {
915 CGGlyph cgGlyph;
916 UniChar theChar;
917
918 // Validate our parameters and state
919 SkASSERT(uni <= 0x0000FFFF);
920 SkASSERT(sizeof(CGGlyph) <= sizeof(uint16_t));
921
922 // Get the glyph
923 theChar = (UniChar) uni;
924
925 if (!CTFontGetGlyphsForCharacters(fCTFont, &theChar, &cgGlyph, 1)) {
926 cgGlyph = 0;
927 }
928
929 return cgGlyph;
930}
931
932void SkScalerContext_Mac::generateAdvance(SkGlyph* glyph) {
933 this->generateMetrics(glyph);
934}
935
936void SkScalerContext_Mac::generateMetrics(SkGlyph* glyph) {
937 CGSize advance;
938 CGRect bounds;
939 CGGlyph cgGlyph;
940
941 // Get the state we need
942 cgGlyph = (CGGlyph) glyph->getGlyphID(fBaseGlyphCount);
943
944 if (fVertical) {
945 if (!isSnowLeopard()) {
946 // Lion and Leopard respect the vertical font metrics.
947 CTFontGetBoundingRectsForGlyphs(fCTVerticalFont, kCTFontVerticalOrientation,
948 &cgGlyph, &bounds, 1);
949 } else {
950 // Snow Leopard and earlier respect the vertical font metrics for
951 // advances, but not bounds, so use the default box and adjust it below.
952 CTFontGetBoundingRectsForGlyphs(fCTFont, kCTFontDefaultOrientation,
953 &cgGlyph, &bounds, 1);
954 }
955 CTFontGetAdvancesForGlyphs(fCTVerticalFont, kCTFontVerticalOrientation,
956 &cgGlyph, &advance, 1);
957 } else {
958 CTFontGetBoundingRectsForGlyphs(fCTFont, kCTFontDefaultOrientation,
959 &cgGlyph, &bounds, 1);
960 CTFontGetAdvancesForGlyphs(fCTFont, kCTFontDefaultOrientation,
961 &cgGlyph, &advance, 1);
962 }
963
964 // BUG?
965 // 0x200B (zero-advance space) seems to return a huge (garbage) bounds, when
966 // it should be empty. So, if we see a zero-advance, we check if it has an
967 // empty path or not, and if so, we jam the bounds to 0. Hopefully a zero-advance
968 // is rare, so we won't incur a big performance cost for this extra check.
969 if (0 == advance.width && 0 == advance.height) {
970 AutoCFRelease<CGPathRef> path(CTFontCreatePathForGlyph(fCTFont, cgGlyph, NULL));
971 if (NULL == path || CGPathIsEmpty(path)) {
972 bounds = CGRectMake(0, 0, 0, 0);
973 }
974 }
975
976 glyph->zeroMetrics();
977 glyph->fAdvanceX = SkFloatToFixed_Check(advance.width);
978 glyph->fAdvanceY = -SkFloatToFixed_Check(advance.height);
979
980 if (CGRectIsEmpty_inline(bounds)) {
981 return;
982 }
983
984 if (isLeopard() && !fVertical) {
985 // Leopard does not consider the matrix skew in its bounds.
986 // Run the bounding rectangle through the skew matrix to determine
987 // the true bounds. However, this doesn't work if the font is vertical.
988 // FIXME (Leopard): If the font has synthetic italic (e.g., matrix skew)
989 // and the font is vertical, the bounds need to be recomputed.
990 SkRect glyphBounds = SkRect::MakeXYWH(
991 bounds.origin.x, bounds.origin.y,
992 bounds.size.width, bounds.size.height);
993 fUnitMatrix.mapRect(&glyphBounds);
994 bounds.origin.x = glyphBounds.fLeft;
995 bounds.origin.y = glyphBounds.fTop;
996 bounds.size.width = glyphBounds.width();
997 bounds.size.height = glyphBounds.height();
998 }
999 // Adjust the bounds
1000 //
1001 // CTFontGetBoundingRectsForGlyphs ignores the font transform, so we need
1002 // to transform the bounding box ourselves.
1003 //
1004 // The bounds are also expanded by 1 pixel, to give CG room for anti-aliasing.
1005 CGRectInset_inline(&bounds, -1, -1);
1006
1007 // Get the metrics
1008 bool lionAdjustedMetrics = false;
1009 if (isLion() || isMountainLion()) {
1010 if (cgGlyph < fGlyphCount && cgGlyph >= getFBoundingBoxesGlyphOffset() && generateBBoxes()){
1011 lionAdjustedMetrics = true;
1012 SkRect adjust;
1013 const GlyphRect& gRect = fFBoundingBoxes[cgGlyph - fFBoundingBoxesGlyphOffset];
1014 adjust.set(gRect.fMinX, gRect.fMinY, gRect.fMaxX, gRect.fMaxY);
1015 fFBoundingBoxesMatrix.mapRect(&adjust);
1016 bounds.origin.x = SkScalarToFloat(adjust.fLeft) - 1;
1017 bounds.origin.y = SkScalarToFloat(adjust.fTop) - 1;
1018 }
1019 // Lion returns fractions in the bounds
1020 glyph->fWidth = SkToU16(sk_float_ceil2int(bounds.size.width));
1021 glyph->fHeight = SkToU16(sk_float_ceil2int(bounds.size.height));
1022 } else {
1023 glyph->fWidth = SkToU16(sk_float_round2int(bounds.size.width));
1024 glyph->fHeight = SkToU16(sk_float_round2int(bounds.size.height));
1025 }
1026 glyph->fTop = SkToS16(-sk_float_round2int(CGRectGetMaxY_inline(bounds)));
1027 glyph->fLeft = SkToS16(sk_float_round2int(CGRectGetMinX_inline(bounds)));
1028 SkIPoint offset;
1029 if (fVertical && (isSnowLeopard() || lionAdjustedMetrics)) {
1030 // SnowLeopard doesn't respect vertical metrics, so compute them manually.
1031 // Also compute them for Lion when the metrics were computed by hand.
1032 getVerticalOffset(cgGlyph, &offset);
1033 glyph->fLeft += offset.fX;
1034 glyph->fTop += offset.fY;
1035 }
1036}
1037
1038#include "SkColorPriv.h"
1039
1040static void build_power_table(uint8_t table[], float ee) {
1041 for (int i = 0; i < 256; i++) {
1042 float x = i / 255.f;
1043 x = sk_float_pow(x, ee);
1044 int xx = SkScalarRoundToInt(SkFloatToScalar(x * 255));
1045 table[i] = SkToU8(xx);
1046 }
1047}
1048
1049/**
1050 * This will invert the gamma applied by CoreGraphics, so we can get linear
1051 * values.
1052 *
1053 * CoreGraphics obscurely defaults to 2.0 as the smoothing gamma value.
1054 * The color space used does not appear to affect this choice.
1055 */
1056static const uint8_t* getInverseGammaTableCoreGraphicSmoothing() {
1057 static bool gInited;
1058 static uint8_t gTableCoreGraphicsSmoothing[256];
1059 if (!gInited) {
1060 build_power_table(gTableCoreGraphicsSmoothing, 2.0f);
1061 gInited = true;
1062 }
1063 return gTableCoreGraphicsSmoothing;
1064}
1065
1066static void cgpixels_to_bits(uint8_t dst[], const CGRGBPixel src[], int count) {
1067 while (count > 0) {
1068 uint8_t mask = 0;
1069 for (int i = 7; i >= 0; --i) {
1070 mask |= (CGRGBPixel_getAlpha(*src++) >> 7) << i;
1071 if (0 == --count) {
1072 break;
1073 }
1074 }
1075 *dst++ = mask;
1076 }
1077}
1078
1079template<bool APPLY_PREBLEND>
1080static inline uint8_t rgb_to_a8(CGRGBPixel rgb, const uint8_t* table8) {
1081 U8CPU r = (rgb >> 16) & 0xFF;
1082 U8CPU g = (rgb >> 8) & 0xFF;
1083 U8CPU b = (rgb >> 0) & 0xFF;
1084 return sk_apply_lut_if<APPLY_PREBLEND>(SkComputeLuminance(r, g, b), table8);
1085}
1086template<bool APPLY_PREBLEND>
1087static void rgb_to_a8(const CGRGBPixel* SK_RESTRICT cgPixels, size_t cgRowBytes,
1088 const SkGlyph& glyph, const uint8_t* table8) {
1089 const int width = glyph.fWidth;
1090 size_t dstRB = glyph.rowBytes();
1091 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1092
1093 for (int y = 0; y < glyph.fHeight; y++) {
1094 for (int i = 0; i < width; ++i) {
1095 dst[i] = rgb_to_a8<APPLY_PREBLEND>(cgPixels[i], table8);
1096 }
1097 cgPixels = (CGRGBPixel*)((char*)cgPixels + cgRowBytes);
1098 dst += dstRB;
1099 }
1100}
1101
1102template<bool APPLY_PREBLEND>
1103static inline uint16_t rgb_to_lcd16(CGRGBPixel rgb, const uint8_t* tableR,
1104 const uint8_t* tableG,
1105 const uint8_t* tableB) {
1106 U8CPU r = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 16) & 0xFF, tableR);
1107 U8CPU g = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 8) & 0xFF, tableG);
1108 U8CPU b = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 0) & 0xFF, tableB);
1109 return SkPack888ToRGB16(r, g, b);
1110}
1111template<bool APPLY_PREBLEND>
1112static void rgb_to_lcd16(const CGRGBPixel* SK_RESTRICT cgPixels, size_t cgRowBytes, const SkGlyph& glyph,
1113 const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) {
1114 const int width = glyph.fWidth;
1115 size_t dstRB = glyph.rowBytes();
1116 uint16_t* SK_RESTRICT dst = (uint16_t*)glyph.fImage;
1117
1118 for (int y = 0; y < glyph.fHeight; y++) {
1119 for (int i = 0; i < width; i++) {
1120 dst[i] = rgb_to_lcd16<APPLY_PREBLEND>(cgPixels[i], tableR, tableG, tableB);
1121 }
1122 cgPixels = (CGRGBPixel*)((char*)cgPixels + cgRowBytes);
1123 dst = (uint16_t*)((char*)dst + dstRB);
1124 }
1125}
1126
1127template<bool APPLY_PREBLEND>
1128static inline uint32_t rgb_to_lcd32(CGRGBPixel rgb, const uint8_t* tableR,
1129 const uint8_t* tableG,
1130 const uint8_t* tableB) {
1131 U8CPU r = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 16) & 0xFF, tableR);
1132 U8CPU g = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 8) & 0xFF, tableG);
1133 U8CPU b = sk_apply_lut_if<APPLY_PREBLEND>((rgb >> 0) & 0xFF, tableB);
1134 return SkPackARGB32(0xFF, r, g, b);
1135}
1136template<bool APPLY_PREBLEND>
1137static void rgb_to_lcd32(const CGRGBPixel* SK_RESTRICT cgPixels, size_t cgRowBytes, const SkGlyph& glyph,
1138 const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) {
1139 const int width = glyph.fWidth;
1140 size_t dstRB = glyph.rowBytes();
1141 uint32_t* SK_RESTRICT dst = (uint32_t*)glyph.fImage;
1142 for (int y = 0; y < glyph.fHeight; y++) {
1143 for (int i = 0; i < width; i++) {
1144 dst[i] = rgb_to_lcd32<APPLY_PREBLEND>(cgPixels[i], tableR, tableG, tableB);
1145 }
1146 cgPixels = (CGRGBPixel*)((char*)cgPixels + cgRowBytes);
1147 dst = (uint32_t*)((char*)dst + dstRB);
1148 }
1149}
1150
1151template <typename T> T* SkTAddByteOffset(T* ptr, size_t byteOffset) {
1152 return (T*)((char*)ptr + byteOffset);
1153}
1154
1155void SkScalerContext_Mac::generateImage(const SkGlyph& glyph) {
1156 CGGlyph cgGlyph = (CGGlyph) glyph.getGlyphID(fBaseGlyphCount);
1157
1158 // FIXME: lcd smoothed un-hinted rasterization unsupported.
1159 bool generateA8FromLCD = fRec.getHinting() != SkPaint::kNo_Hinting;
1160
1161 // Draw the glyph
1162 size_t cgRowBytes;
1163 CGRGBPixel* cgPixels = fOffscreen.getCG(*this, glyph, cgGlyph, &cgRowBytes, generateA8FromLCD);
1164 if (cgPixels == NULL) {
1165 return;
1166 }
1167
1168 //TODO: see if drawing black on white and inverting is faster (at least in
1169 //lcd case) as core graphics appears to have special case code for drawing
1170 //black text.
1171
1172 // Fix the glyph
1173 const bool isLCD = isLCDFormat(glyph.fMaskFormat);
1174 if (isLCD || (glyph.fMaskFormat == SkMask::kA8_Format && supports_LCD() && generateA8FromLCD)) {
1175 const uint8_t* table = getInverseGammaTableCoreGraphicSmoothing();
1176
1177 //Note that the following cannot really be integrated into the
1178 //pre-blend, since we may not be applying the pre-blend; when we aren't
1179 //applying the pre-blend it means that a filter wants linear anyway.
1180 //Other code may also be applying the pre-blend, so we'd need another
1181 //one with this and one without.
1182 CGRGBPixel* addr = cgPixels;
1183 for (int y = 0; y < glyph.fHeight; ++y) {
1184 for (int x = 0; x < glyph.fWidth; ++x) {
1185 int r = (addr[x] >> 16) & 0xFF;
1186 int g = (addr[x] >> 8) & 0xFF;
1187 int b = (addr[x] >> 0) & 0xFF;
1188 addr[x] = (table[r] << 16) | (table[g] << 8) | table[b];
1189 }
1190 addr = SkTAddByteOffset(addr, cgRowBytes);
1191 }
1192 }
1193
1194 // Convert glyph to mask
1195 switch (glyph.fMaskFormat) {
1196 case SkMask::kLCD32_Format: {
1197 if (fPreBlend.isApplicable()) {
1198 rgb_to_lcd32<true>(cgPixels, cgRowBytes, glyph,
1199 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1200 } else {
1201 rgb_to_lcd32<false>(cgPixels, cgRowBytes, glyph,
1202 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1203 }
1204 } break;
1205 case SkMask::kLCD16_Format: {
1206 if (fPreBlend.isApplicable()) {
1207 rgb_to_lcd16<true>(cgPixels, cgRowBytes, glyph,
1208 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1209 } else {
1210 rgb_to_lcd16<false>(cgPixels, cgRowBytes, glyph,
1211 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1212 }
1213 } break;
1214 case SkMask::kA8_Format: {
1215 if (fPreBlend.isApplicable()) {
1216 rgb_to_a8<true>(cgPixels, cgRowBytes, glyph, fPreBlend.fG);
1217 } else {
1218 rgb_to_a8<false>(cgPixels, cgRowBytes, glyph, fPreBlend.fG);
1219 }
1220 } break;
1221 case SkMask::kBW_Format: {
1222 const int width = glyph.fWidth;
1223 size_t dstRB = glyph.rowBytes();
1224 uint8_t* dst = (uint8_t*)glyph.fImage;
1225 for (int y = 0; y < glyph.fHeight; y++) {
1226 cgpixels_to_bits(dst, cgPixels, width);
1227 cgPixels = (CGRGBPixel*)((char*)cgPixels + cgRowBytes);
1228 dst += dstRB;
1229 }
1230 } break;
1231 default:
1232 SkDEBUGFAIL("unexpected mask format");
1233 break;
1234 }
1235}
1236
1237/*
1238 * Our subpixel resolution is only 2 bits in each direction, so a scale of 4
1239 * seems sufficient, and possibly even correct, to allow the hinted outline
1240 * to be subpixel positioned.
1241 */
1242#define kScaleForSubPixelPositionHinting (4.0f)
1243
1244void SkScalerContext_Mac::generatePath(const SkGlyph& glyph, SkPath* path) {
1245 CTFontRef font = fCTFont;
1246 SkScalar scaleX = SK_Scalar1;
1247 SkScalar scaleY = SK_Scalar1;
1248
1249 /*
1250 * For subpixel positioning, we want to return an unhinted outline, so it
1251 * can be positioned nicely at fractional offsets. However, we special-case
1252 * if the baseline of the (horizontal) text is axis-aligned. In those cases
1253 * we want to retain hinting in the direction orthogonal to the baseline.
1254 * e.g. for horizontal baseline, we want to retain hinting in Y.
1255 * The way we remove hinting is to scale the font by some value (4) in that
1256 * direction, ask for the path, and then scale the path back down.
1257 */
1258 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
1259 SkMatrix m;
1260 fRec.getSingleMatrix(&m);
1261
1262 // start out by assuming that we want no hining in X and Y
1263 scaleX = scaleY = SkFloatToScalar(kScaleForSubPixelPositionHinting);
1264 // now see if we need to restore hinting for axis-aligned baselines
1265 switch (SkComputeAxisAlignmentForHText(m)) {
1266 case kX_SkAxisAlignment:
1267 scaleY = SK_Scalar1; // want hinting in the Y direction
1268 break;
1269 case kY_SkAxisAlignment:
1270 scaleX = SK_Scalar1; // want hinting in the X direction
1271 break;
1272 default:
1273 break;
1274 }
1275
1276 CGAffineTransform xform = MatrixToCGAffineTransform(m, scaleX, scaleY);
1277 // need to release font when we're done
1278 font = CTFontCreateCopyWithAttributes(fCTFont, 1, &xform, NULL);
1279 }
1280
1281 CGGlyph cgGlyph = (CGGlyph)glyph.getGlyphID(fBaseGlyphCount);
1282 AutoCFRelease<CGPathRef> cgPath(CTFontCreatePathForGlyph(font, cgGlyph, NULL));
1283
1284 path->reset();
1285 if (cgPath != NULL) {
1286 CGPathApply(cgPath, path, SkScalerContext_Mac::CTPathElement);
1287 }
1288
1289 if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
1290 SkMatrix m;
1291 m.setScale(SkScalarInvert(scaleX), SkScalarInvert(scaleY));
1292 path->transform(m);
1293 // balance the call to CTFontCreateCopyWithAttributes
1294 CFSafeRelease(font);
1295 }
1296 if (fRec.fFlags & SkScalerContext::kVertical_Flag) {
1297 SkIPoint offset;
1298 getVerticalOffset(cgGlyph, &offset);
1299 path->offset(SkIntToScalar(offset.fX), SkIntToScalar(offset.fY));
1300 }
1301}
1302
1303void SkScalerContext_Mac::generateFontMetrics(SkPaint::FontMetrics* mx,
1304 SkPaint::FontMetrics* my) {
1305 CGRect theBounds = CTFontGetBoundingBox(fCTFont);
1306
1307 SkPaint::FontMetrics theMetrics;
1308 theMetrics.fTop = CGToScalar(-CGRectGetMaxY_inline(theBounds));
1309 theMetrics.fAscent = CGToScalar(-CTFontGetAscent(fCTFont));
1310 theMetrics.fDescent = CGToScalar( CTFontGetDescent(fCTFont));
1311 theMetrics.fBottom = CGToScalar(-CGRectGetMinY_inline(theBounds));
1312 theMetrics.fLeading = CGToScalar( CTFontGetLeading(fCTFont));
1313 theMetrics.fAvgCharWidth = CGToScalar( CGRectGetWidth_inline(theBounds));
1314 theMetrics.fXMin = CGToScalar( CGRectGetMinX_inline(theBounds));
1315 theMetrics.fXMax = CGToScalar( CGRectGetMaxX_inline(theBounds));
1316 theMetrics.fXHeight = CGToScalar( CTFontGetXHeight(fCTFont));
1317
1318 if (mx != NULL) {
1319 *mx = theMetrics;
1320 }
1321 if (my != NULL) {
1322 *my = theMetrics;
1323 }
1324}
1325
1326void SkScalerContext_Mac::CTPathElement(void *info, const CGPathElement *element) {
1327 SkPath* skPath = (SkPath*)info;
1328
1329 // Process the path element
1330 switch (element->type) {
1331 case kCGPathElementMoveToPoint:
1332 skPath->moveTo(element->points[0].x, -element->points[0].y);
1333 break;
1334
1335 case kCGPathElementAddLineToPoint:
1336 skPath->lineTo(element->points[0].x, -element->points[0].y);
1337 break;
1338
1339 case kCGPathElementAddQuadCurveToPoint:
1340 skPath->quadTo(element->points[0].x, -element->points[0].y,
1341 element->points[1].x, -element->points[1].y);
1342 break;
1343
1344 case kCGPathElementAddCurveToPoint:
1345 skPath->cubicTo(element->points[0].x, -element->points[0].y,
1346 element->points[1].x, -element->points[1].y,
1347 element->points[2].x, -element->points[2].y);
1348 break;
1349
1350 case kCGPathElementCloseSubpath:
1351 skPath->close();
1352 break;
1353
1354 default:
1355 SkDEBUGFAIL("Unknown path element!");
1356 break;
1357 }
1358}
1359
1360
1361///////////////////////////////////////////////////////////////////////////////
1362
1363// Returns NULL on failure
1364// Call must still manage its ownership of provider
1365static SkTypeface* create_from_dataProvider(CGDataProviderRef provider) {
1366 AutoCFRelease<CGFontRef> cg(CGFontCreateWithDataProvider(provider));
1367 if (NULL == cg) {
1368 return NULL;
1369 }
1370 CTFontRef ct = CTFontCreateWithGraphicsFont(cg, 0, NULL, NULL);
1371 return cg ? SkCreateTypefaceFromCTFont(ct) : NULL;
1372}
1373
1374SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) {
1375 AutoCFRelease<CGDataProviderRef> provider(SkCreateDataProviderFromStream(stream));
1376 if (NULL == provider) {
1377 return NULL;
1378 }
1379 return create_from_dataProvider(provider);
1380}
1381
1382SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) {
1383 AutoCFRelease<CGDataProviderRef> provider(CGDataProviderCreateWithFilename(path));
1384 if (NULL == provider) {
1385 return NULL;
1386 }
1387 return create_from_dataProvider(provider);
1388}
1389
1390// Web fonts added to the the CTFont registry do not return their character set.
1391// Iterate through the font in this case. The existing caller caches the result,
1392// so the performance impact isn't too bad.
1393static void populate_glyph_to_unicode_slow(CTFontRef ctFont, CFIndex glyphCount,
1394 SkTDArray<SkUnichar>* glyphToUnicode) {
1395 glyphToUnicode->setCount(glyphCount);
1396 SkUnichar* out = glyphToUnicode->begin();
1397 sk_bzero(out, glyphCount * sizeof(SkUnichar));
1398 UniChar unichar = 0;
1399 while (glyphCount > 0) {
1400 CGGlyph glyph;
1401 if (CTFontGetGlyphsForCharacters(ctFont, &unichar, &glyph, 1)) {
1402 out[glyph] = unichar;
1403 --glyphCount;
1404 }
1405 if (++unichar == 0) {
1406 break;
1407 }
1408 }
1409}
1410
1411// Construct Glyph to Unicode table.
1412// Unicode code points that require conjugate pairs in utf16 are not
1413// supported.
1414static void populate_glyph_to_unicode(CTFontRef ctFont, CFIndex glyphCount,
1415 SkTDArray<SkUnichar>* glyphToUnicode) {
1416 AutoCFRelease<CFCharacterSetRef> charSet(CTFontCopyCharacterSet(ctFont));
1417 if (!charSet) {
1418 populate_glyph_to_unicode_slow(ctFont, glyphCount, glyphToUnicode);
1419 return;
1420 }
1421
1422 AutoCFRelease<CFDataRef> bitmap(CFCharacterSetCreateBitmapRepresentation(kCFAllocatorDefault,
1423 charSet));
1424 if (!bitmap) {
1425 return;
1426 }
1427 CFIndex length = CFDataGetLength(bitmap);
1428 if (!length) {
1429 return;
1430 }
1431 if (length > 8192) {
1432 // TODO: Add support for Unicode above 0xFFFF
1433 // Consider only the BMP portion of the Unicode character points.
1434 // The bitmap may contain other planes, up to plane 16.
1435 // See http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFCharacterSetRef/Reference/reference.html
1436 length = 8192;
1437 }
1438 const UInt8* bits = CFDataGetBytePtr(bitmap);
1439 glyphToUnicode->setCount(glyphCount);
1440 SkUnichar* out = glyphToUnicode->begin();
1441 sk_bzero(out, glyphCount * sizeof(SkUnichar));
1442 for (int i = 0; i < length; i++) {
1443 int mask = bits[i];
1444 if (!mask) {
1445 continue;
1446 }
1447 for (int j = 0; j < 8; j++) {
1448 CGGlyph glyph;
1449 UniChar unichar = static_cast<UniChar>((i << 3) + j);
1450 if (mask & (1 << j) && CTFontGetGlyphsForCharacters(ctFont, &unichar, &glyph, 1)) {
1451 out[glyph] = unichar;
1452 }
1453 }
1454 }
1455}
1456
1457static bool getWidthAdvance(CTFontRef ctFont, int gId, int16_t* data) {
1458 CGSize advance;
1459 advance.width = 0;
1460 CGGlyph glyph = gId;
1461 CTFontGetAdvancesForGlyphs(ctFont, kCTFontHorizontalOrientation, &glyph, &advance, 1);
1462 *data = sk_float_round2int(advance.width);
1463 return true;
1464}
1465
1466// we might move this into our CGUtils...
1467static void CFStringToSkString(CFStringRef src, SkString* dst) {
1468 // Reserve enough room for the worst-case string,
1469 // plus 1 byte for the trailing null.
1470 CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(src),
1471 kCFStringEncodingUTF8) + 1;
1472 dst->resize(length);
1473 CFStringGetCString(src, dst->writable_str(), length, kCFStringEncodingUTF8);
1474 // Resize to the actual UTF-8 length used, stripping the null character.
1475 dst->resize(strlen(dst->c_str()));
1476}
1477
reed@google.com2689f612013-03-20 20:01:47 +00001478SkAdvancedTypefaceMetrics* SkTypeface_Mac::onGetAdvancedTypefaceMetrics(
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001479 SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
1480 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +00001481 uint32_t glyphIDsCount) const {
1482
1483 CTFontRef originalCTFont = fFontRef.get();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001484 AutoCFRelease<CTFontRef> ctFont(CTFontCreateCopyWithAttributes(
1485 originalCTFont, CTFontGetUnitsPerEm(originalCTFont), NULL, NULL));
1486 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
1487
1488 {
1489 AutoCFRelease<CFStringRef> fontName(CTFontCopyPostScriptName(ctFont));
1490 CFStringToSkString(fontName, &info->fFontName);
1491 }
1492
1493 info->fMultiMaster = false;
1494 CFIndex glyphCount = CTFontGetGlyphCount(ctFont);
1495 info->fLastGlyphID = SkToU16(glyphCount - 1);
1496 info->fEmSize = CTFontGetUnitsPerEm(ctFont);
1497
1498 if (perGlyphInfo & SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo) {
1499 populate_glyph_to_unicode(ctFont, glyphCount, &info->fGlyphToUnicode);
1500 }
1501
1502 info->fStyle = 0;
1503
1504 // If it's not a truetype font, mark it as 'other'. Assume that TrueType
1505 // fonts always have both glyf and loca tables. At the least, this is what
1506 // sfntly needs to subset the font. CTFontCopyAttribute() does not always
1507 // succeed in determining this directly.
reed@google.com2689f612013-03-20 20:01:47 +00001508 if (!this->getTableSize('glyf') || !this->getTableSize('loca')) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001509 info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
1510 info->fItalicAngle = 0;
1511 info->fAscent = 0;
1512 info->fDescent = 0;
1513 info->fStemV = 0;
1514 info->fCapHeight = 0;
1515 info->fBBox = SkIRect::MakeEmpty();
1516 return info;
1517 }
1518
1519 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
1520 CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(ctFont);
1521 if (symbolicTraits & kCTFontMonoSpaceTrait) {
1522 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
1523 }
1524 if (symbolicTraits & kCTFontItalicTrait) {
1525 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
1526 }
1527 CTFontStylisticClass stylisticClass = symbolicTraits & kCTFontClassMaskTrait;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001528 if (stylisticClass >= kCTFontOldStyleSerifsClass && stylisticClass <= kCTFontSlabSerifsClass) {
1529 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
1530 } else if (stylisticClass & kCTFontScriptsClass) {
1531 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
1532 }
1533 info->fItalicAngle = (int16_t) CTFontGetSlantAngle(ctFont);
1534 info->fAscent = (int16_t) CTFontGetAscent(ctFont);
1535 info->fDescent = (int16_t) CTFontGetDescent(ctFont);
1536 info->fCapHeight = (int16_t) CTFontGetCapHeight(ctFont);
1537 CGRect bbox = CTFontGetBoundingBox(ctFont);
1538
1539 SkRect r;
1540 r.set( CGToScalar(CGRectGetMinX_inline(bbox)), // Left
1541 CGToScalar(CGRectGetMaxY_inline(bbox)), // Top
1542 CGToScalar(CGRectGetMaxX_inline(bbox)), // Right
1543 CGToScalar(CGRectGetMinY_inline(bbox))); // Bottom
1544
1545 r.roundOut(&(info->fBBox));
1546
1547 // Figure out a good guess for StemV - Min width of i, I, !, 1.
1548 // This probably isn't very good with an italic font.
1549 int16_t min_width = SHRT_MAX;
1550 info->fStemV = 0;
1551 static const UniChar stem_chars[] = {'i', 'I', '!', '1'};
1552 const size_t count = sizeof(stem_chars) / sizeof(stem_chars[0]);
1553 CGGlyph glyphs[count];
1554 CGRect boundingRects[count];
1555 if (CTFontGetGlyphsForCharacters(ctFont, stem_chars, glyphs, count)) {
1556 CTFontGetBoundingRectsForGlyphs(ctFont, kCTFontHorizontalOrientation,
1557 glyphs, boundingRects, count);
1558 for (size_t i = 0; i < count; i++) {
1559 int16_t width = (int16_t) boundingRects[i].size.width;
1560 if (width > 0 && width < min_width) {
1561 min_width = width;
1562 info->fStemV = min_width;
1563 }
1564 }
1565 }
1566
1567 if (false) { // TODO: haven't figured out how to know if font is embeddable
1568 // (information is in the OS/2 table)
1569 info->fType = SkAdvancedTypefaceMetrics::kNotEmbeddable_Font;
1570 } else if (perGlyphInfo & SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo) {
1571 if (info->fStyle & SkAdvancedTypefaceMetrics::kFixedPitch_Style) {
1572 skia_advanced_typeface_metrics_utils::appendRange(&info->fGlyphWidths, 0);
1573 info->fGlyphWidths->fAdvance.append(1, &min_width);
1574 skia_advanced_typeface_metrics_utils::finishRange(info->fGlyphWidths.get(), 0,
1575 SkAdvancedTypefaceMetrics::WidthRange::kDefault);
1576 } else {
1577 info->fGlyphWidths.reset(
1578 skia_advanced_typeface_metrics_utils::getAdvanceData(ctFont.get(),
1579 glyphCount,
1580 glyphIDs,
1581 glyphIDsCount,
1582 &getWidthAdvance));
1583 }
1584 }
1585 return info;
1586}
1587
1588///////////////////////////////////////////////////////////////////////////////
1589
1590static SK_SFNT_ULONG get_font_type_tag(SkFontID uniqueID) {
1591 CTFontRef ctFont = GetFontRefFromFontID(uniqueID);
1592 AutoCFRelease<CFNumberRef> fontFormatRef(
1593 static_cast<CFNumberRef>(CTFontCopyAttribute(ctFont, kCTFontFormatAttribute)));
1594 if (!fontFormatRef) {
1595 return 0;
1596 }
1597
1598 SInt32 fontFormatValue;
1599 if (!CFNumberGetValue(fontFormatRef, kCFNumberSInt32Type, &fontFormatValue)) {
1600 return 0;
1601 }
1602
1603 switch (fontFormatValue) {
1604 case kCTFontFormatOpenTypePostScript:
1605 return SkSFNTHeader::fontType_OpenTypeCFF::TAG;
1606 case kCTFontFormatOpenTypeTrueType:
1607 return SkSFNTHeader::fontType_WindowsTrueType::TAG;
1608 case kCTFontFormatTrueType:
1609 return SkSFNTHeader::fontType_MacTrueType::TAG;
1610 case kCTFontFormatPostScript:
1611 return SkSFNTHeader::fontType_PostScript::TAG;
1612 case kCTFontFormatBitmap:
1613 return SkSFNTHeader::fontType_MacTrueType::TAG;
1614 case kCTFontFormatUnrecognized:
1615 default:
1616 //CT seems to be unreliable in being able to obtain the type,
1617 //even if all we want is the first four bytes of the font resource.
1618 //Just the presence of the FontForge 'FFTM' table seems to throw it off.
1619 return SkSFNTHeader::fontType_WindowsTrueType::TAG;
1620 }
1621}
1622
1623SkStream* SkFontHost::OpenStream(SkFontID uniqueID) {
1624 SK_SFNT_ULONG fontType = get_font_type_tag(uniqueID);
1625 if (0 == fontType) {
1626 return NULL;
1627 }
1628
1629 // get table tags
1630 int numTables = CountTables(uniqueID);
1631 SkTDArray<SkFontTableTag> tableTags;
1632 tableTags.setCount(numTables);
1633 GetTableTags(uniqueID, tableTags.begin());
1634
1635 // calc total size for font, save sizes
1636 SkTDArray<size_t> tableSizes;
1637 size_t totalSize = sizeof(SkSFNTHeader) + sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
1638 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
1639 size_t tableSize = GetTableSize(uniqueID, tableTags[tableIndex]);
1640 totalSize += (tableSize + 3) & ~3;
1641 *tableSizes.append() = tableSize;
1642 }
1643
1644 // reserve memory for stream, and zero it (tables must be zero padded)
1645 SkMemoryStream* stream = new SkMemoryStream(totalSize);
1646 char* dataStart = (char*)stream->getMemoryBase();
1647 sk_bzero(dataStart, totalSize);
1648 char* dataPtr = dataStart;
1649
1650 // compute font header entries
1651 uint16_t entrySelector = 0;
1652 uint16_t searchRange = 1;
1653 while (searchRange < numTables >> 1) {
1654 entrySelector++;
1655 searchRange <<= 1;
1656 }
1657 searchRange <<= 4;
1658 uint16_t rangeShift = (numTables << 4) - searchRange;
1659
1660 // write font header
1661 SkSFNTHeader* header = (SkSFNTHeader*)dataPtr;
1662 header->fontType = fontType;
1663 header->numTables = SkEndian_SwapBE16(numTables);
1664 header->searchRange = SkEndian_SwapBE16(searchRange);
1665 header->entrySelector = SkEndian_SwapBE16(entrySelector);
1666 header->rangeShift = SkEndian_SwapBE16(rangeShift);
1667 dataPtr += sizeof(SkSFNTHeader);
1668
1669 // write tables
1670 SkSFNTHeader::TableDirectoryEntry* entry = (SkSFNTHeader::TableDirectoryEntry*)dataPtr;
1671 dataPtr += sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
1672 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
1673 size_t tableSize = tableSizes[tableIndex];
1674 GetTableData(uniqueID, tableTags[tableIndex], 0, tableSize, dataPtr);
1675 entry->tag = SkEndian_SwapBE32(tableTags[tableIndex]);
1676 entry->checksum = SkEndian_SwapBE32(SkOTUtils::CalcTableChecksum((SK_OT_ULONG*)dataPtr,
1677 tableSize));
1678 entry->offset = SkEndian_SwapBE32(dataPtr - dataStart);
1679 entry->logicalLength = SkEndian_SwapBE32(tableSize);
1680
1681 dataPtr += (tableSize + 3) & ~3;
1682 ++entry;
1683 }
1684
1685 return stream;
1686}
1687
1688size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length, int32_t* index) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001689 return 0;
1690}
1691
1692///////////////////////////////////////////////////////////////////////////////
1693
1694#include "SkStream.h"
1695
1696void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
1697 SkFontDescriptor desc;
1698 face->onGetFontDescriptor(&desc);
1699
1700 desc.serialize(stream);
1701
1702 // by convention, we also write out the actual sfnt data, preceeded by
1703 // a packed-length. For now we skip that, so we just write the zero.
1704 stream->writePackedUInt(0);
1705}
1706
1707SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
1708 SkFontDescriptor desc(stream);
1709
1710 // by convention, Serialize will have also written the actual sfnt data.
1711 // for now, we just want to skip it.
1712 size_t size = stream->readPackedUInt();
1713 stream->skip(size);
1714
1715 return SkFontHost::CreateTypeface(NULL, desc.getFamilyName(), desc.getStyle());
1716}
1717
1718///////////////////////////////////////////////////////////////////////////////
1719
1720// DEPRECATED
reed@google.com0da48612013-03-19 16:06:52 +00001721SkTypeface* SkFontHost::NextLogicalTypeface(SkFontID currFontID, SkFontID origFontID) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001722 SkTypeface* face = GetDefaultFace();
reed@google.com0da48612013-03-19 16:06:52 +00001723 if (face->uniqueID() == currFontID) {
1724 face = NULL;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001725 }
reed@google.com0da48612013-03-19 16:06:52 +00001726 return SkSafeRef(face);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001727}
1728
1729// DEPRECATED
1730int SkFontHost::CountTables(SkFontID fontID) {
1731 SkTypeface* face = SkTypefaceCache::FindByID(fontID);
1732 return face ? face->onGetTableTags(NULL) : 0;
1733}
1734
1735// DEPRECATED
1736int SkFontHost::GetTableTags(SkFontID fontID, SkFontTableTag tags[]) {
1737 SkTypeface* face = SkTypefaceCache::FindByID(fontID);
1738 return face ? face->onGetTableTags(tags) : 0;
1739}
1740
1741// DEPRECATED
1742size_t SkFontHost::GetTableSize(SkFontID fontID, SkFontTableTag tag) {
1743 SkTypeface* face = SkTypefaceCache::FindByID(fontID);
1744 return face ? face->onGetTableData(tag, 0, ~0U, NULL) : 0;
1745}
1746
1747// DEPRECATED
1748size_t SkFontHost::GetTableData(SkFontID fontID, SkFontTableTag tag,
1749 size_t offset, size_t length, void* dst) {
1750 SkTypeface* face = SkTypefaceCache::FindByID(fontID);
1751 return face ? face->onGetTableData(tag, offset, length, dst) : 0;
1752}
1753
1754///////////////////////////////////////////////////////////////////////////////
1755///////////////////////////////////////////////////////////////////////////////
1756
1757int SkTypeface_Mac::onGetUPEM() const {
1758 AutoCFRelease<CGFontRef> cgFont(CTFontCopyGraphicsFont(fFontRef, NULL));
1759 return CGFontGetUnitsPerEm(cgFont);
1760}
1761
1762// If, as is the case with web fonts, the CTFont data isn't available,
1763// the CGFont data may work. While the CGFont may always provide the
1764// right result, leave the CTFont code path to minimize disruption.
1765static CFDataRef copyTableFromFont(CTFontRef ctFont, SkFontTableTag tag) {
1766 CFDataRef data = CTFontCopyTable(ctFont, (CTFontTableTag) tag,
1767 kCTFontTableOptionNoOptions);
1768 if (NULL == data) {
1769 AutoCFRelease<CGFontRef> cgFont(CTFontCopyGraphicsFont(ctFont, NULL));
1770 data = CGFontCopyTableForTag(cgFont, tag);
1771 }
1772 return data;
1773}
1774
1775int SkTypeface_Mac::onGetTableTags(SkFontTableTag tags[]) const {
1776 AutoCFRelease<CFArrayRef> cfArray(CTFontCopyAvailableTables(fFontRef,
1777 kCTFontTableOptionNoOptions));
1778 if (NULL == cfArray) {
1779 return 0;
1780 }
1781 int count = CFArrayGetCount(cfArray);
1782 if (tags) {
1783 for (int i = 0; i < count; ++i) {
1784 uintptr_t fontTag = reinterpret_cast<uintptr_t>(CFArrayGetValueAtIndex(cfArray, i));
1785 tags[i] = static_cast<SkFontTableTag>(fontTag);
1786 }
1787 }
1788 return count;
1789}
1790
1791size_t SkTypeface_Mac::onGetTableData(SkFontTableTag tag, size_t offset,
1792 size_t length, void* dstData) const {
1793 AutoCFRelease<CFDataRef> srcData(copyTableFromFont(fFontRef, tag));
1794 if (NULL == srcData) {
1795 return 0;
1796 }
1797
1798 size_t srcSize = CFDataGetLength(srcData);
1799 if (offset >= srcSize) {
1800 return 0;
1801 }
1802 if (length > srcSize - offset) {
1803 length = srcSize - offset;
1804 }
1805 if (dstData) {
1806 memcpy(dstData, CFDataGetBytePtr(srcData) + offset, length);
1807 }
1808 return length;
1809}
1810
1811SkScalerContext* SkTypeface_Mac::onCreateScalerContext(const SkDescriptor* desc) const {
reed@google.com0da48612013-03-19 16:06:52 +00001812 return new SkScalerContext_Mac(const_cast<SkTypeface_Mac*>(this), desc);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001813}
1814
1815void SkTypeface_Mac::onFilterRec(SkScalerContextRec* rec) const {
1816 unsigned flagsWeDontSupport = SkScalerContext::kDevKernText_Flag |
1817 SkScalerContext::kAutohinting_Flag;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001818
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001819 rec->fFlags &= ~flagsWeDontSupport;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001820
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001821 bool lcdSupport = supports_LCD();
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001822
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001823 // Only two levels of hinting are supported.
1824 // kNo_Hinting means avoid CoreGraphics outline dilation.
1825 // kNormal_Hinting means CoreGraphics outline dilation is allowed.
1826 // If there is no lcd support, hinting (dilation) cannot be supported.
1827 SkPaint::Hinting hinting = rec->getHinting();
1828 if (SkPaint::kSlight_Hinting == hinting || !lcdSupport) {
1829 hinting = SkPaint::kNo_Hinting;
1830 } else if (SkPaint::kFull_Hinting == hinting) {
1831 hinting = SkPaint::kNormal_Hinting;
1832 }
1833 rec->setHinting(hinting);
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001834
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001835 // FIXME: lcd smoothed un-hinted rasterization unsupported.
1836 // Tracked by http://code.google.com/p/skia/issues/detail?id=915 .
1837 // There is no current means to honor a request for unhinted lcd,
1838 // so arbitrarilly ignore the hinting request and honor lcd.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001839
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001840 // Hinting and smoothing should be orthogonal, but currently they are not.
1841 // CoreGraphics has no API to influence hinting. However, its lcd smoothed
1842 // output is drawn from auto-dilated outlines (the amount of which is
1843 // determined by AppleFontSmoothing). Its regular anti-aliased output is
1844 // drawn from un-dilated outlines.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001845
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001846 // The behavior of Skia is as follows:
1847 // [AA][no-hint]: generate AA using CoreGraphic's AA output.
1848 // [AA][yes-hint]: use CoreGraphic's LCD output and reduce it to a single
1849 // channel. This matches [LCD][yes-hint] in weight.
1850 // [LCD][no-hint]: curently unable to honor, and must pick which to respect.
1851 // Currenly side with LCD, effectively ignoring the hinting setting.
1852 // [LCD][yes-hint]: generate LCD using CoreGraphic's LCD output.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001853
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001854 if (isLCDFormat(rec->fMaskFormat)) {
1855 if (lcdSupport) {
1856 //CoreGraphics creates 555 masks for smoothed text anyway.
1857 rec->fMaskFormat = SkMask::kLCD16_Format;
1858 rec->setHinting(SkPaint::kNormal_Hinting);
1859 } else {
1860 rec->fMaskFormat = SkMask::kA8_Format;
1861 }
1862 }
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001863
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001864 // Unhinted A8 masks (those not derived from LCD masks) must respect SK_GAMMA_APPLY_TO_A8.
1865 // All other masks can use regular gamma.
1866 if (SkMask::kA8_Format == rec->fMaskFormat && SkPaint::kNo_Hinting == hinting) {
1867#ifndef SK_GAMMA_APPLY_TO_A8
1868 rec->ignorePreBlend();
reed@android.comfeda2f92010-05-19 13:47:05 +00001869#endif
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001870 } else {
1871 //CoreGraphics dialates smoothed text as needed.
1872 rec->setContrast(0);
1873 }
1874}
1875
1876// we take ownership of the ref
1877static const char* get_str(CFStringRef ref, SkString* str) {
1878 CFStringToSkString(ref, str);
1879 CFSafeRelease(ref);
1880 return str->c_str();
1881}
1882
1883void SkTypeface_Mac::onGetFontDescriptor(SkFontDescriptor* desc) const {
1884 this->INHERITED::onGetFontDescriptor(desc);
1885 SkString tmpStr;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00001886
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001887 desc->setFamilyName(get_str(CTFontCopyFamilyName(fFontRef), &tmpStr));
1888 desc->setFullName(get_str(CTFontCopyFullName(fFontRef), &tmpStr));
1889 desc->setPostscriptName(get_str(CTFontCopyPostScriptName(fFontRef), &tmpStr));
1890}