blob: a9b8ccd91ce0af72391faa4ab1b1538bd4955833 [file] [log] [blame]
reed@android.com0680d6c2008-12-19 19:46:15 +00001/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00002 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
mtkleinde9e7a72015-03-11 12:01:25 -07008#include "SkTypes.h" // Keep this before any #ifdef ...
mtklein1ee76512015-11-02 10:20:27 -08009#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
mtkleinde9e7a72015-03-11 12:01:25 -070010
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000011#ifdef SK_BUILD_FOR_MAC
12#import <ApplicationServices/ApplicationServices.h>
13#endif
reed@android.com0680d6c2008-12-19 19:46:15 +000014
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000015#ifdef SK_BUILD_FOR_IOS
16#include <CoreText/CoreText.h>
reed@google.com3dcbd462013-03-27 13:56:34 +000017#include <CoreText/CTFontManager.h>
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000018#include <CoreGraphics/CoreGraphics.h>
19#include <CoreFoundation/CoreFoundation.h>
20#endif
21
reed39a9a502015-05-12 09:50:04 -070022#include "SkAdvancedTypefaceMetrics.h"
Hal Canary95e3c052017-01-11 12:44:43 -050023#include "SkAutoMalloc.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000024#include "SkCGUtils.h"
25#include "SkColorPriv.h"
26#include "SkDescriptor.h"
27#include "SkEndian.h"
jvanverth02802f62015-07-02 06:42:49 -070028#include "SkFloatingPoint.h"
mtklein1b249332015-07-07 12:21:21 -070029#include "SkFontDescriptor.h"
30#include "SkFontMgr.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000031#include "SkGlyph.h"
bungemanf93d7112016-09-16 06:24:20 -070032#include "SkMakeUnique.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000033#include "SkMaskGamma.h"
halcanary4dbbd042016-06-07 17:21:10 -070034#include "SkMathPriv.h"
mtklein1b249332015-07-07 12:21:21 -070035#include "SkMutex.h"
bungeman4ec46aa2017-02-15 17:49:12 -050036#include "SkOTTable_OS_2.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000037#include "SkOTUtils.h"
mtkleinffa4a922016-05-05 16:05:56 -070038#include "SkOnce.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000039#include "SkPaint.h"
40#include "SkPath.h"
mtklein1b249332015-07-07 12:21:21 -070041#include "SkSFNTHeader.h"
jvanverth02802f62015-07-02 06:42:49 -070042#include "SkStream.h"
mtklein1b249332015-07-07 12:21:21 -070043#include "SkString.h"
bungemane280d062016-03-24 11:27:05 -070044#include "SkTemplates.h"
mtklein1b249332015-07-07 12:21:21 -070045#include "SkTypefaceCache.h"
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000046#include "SkTypeface_mac.h"
47#include "SkUtils.h"
reed@google.comf77b35d2013-05-02 20:39:44 +000048
reedd0f41732015-07-10 12:08:38 -070049// Experimental code to use a global lock whenever we access CG, to see if this reduces
50// crashes in Chrome
51#define USE_GLOBAL_MUTEX_FOR_CG_ACCESS
52
53#ifdef USE_GLOBAL_MUTEX_FOR_CG_ACCESS
reed086eea92016-05-04 17:12:46 -070054 SK_DECLARE_STATIC_MUTEX(gCGMutex);
reedd0f41732015-07-10 12:08:38 -070055 #define AUTO_CG_LOCK() SkAutoMutexAcquire amc(gCGMutex)
56#else
57 #define AUTO_CG_LOCK()
58#endif
59
bungeman3b4b66c2015-01-08 08:33:44 -080060// Set to make glyph bounding boxes visible.
61#define SK_SHOW_TEXT_BLIT_COVERAGE 0
62
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000063class SkScalerContext_Mac;
64
bungemanc292b5f2016-12-20 12:04:29 -050065struct CFSafeRelease {
66 void operator()(CFTypeRef cfTypeRef) {
67 if (cfTypeRef) {
68 CFRelease(cfTypeRef);
69 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000070 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000071};
bungemanc292b5f2016-12-20 12:04:29 -050072template <typename CFRef> using UniqueCFRef =
73 std::unique_ptr<skstd::remove_pointer_t<CFRef>, CFSafeRelease>;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000074
bungemanc292b5f2016-12-20 12:04:29 -050075static UniqueCFRef<CFStringRef> make_CFString(const char str[]) {
76 return UniqueCFRef<CFStringRef>(CFStringCreateWithCString(nullptr, str, kCFStringEncodingUTF8));
reed@google.com964988f2013-03-29 14:57:22 +000077}
78
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000079// inline versions of these rect helpers
80
81static bool CGRectIsEmpty_inline(const CGRect& rect) {
82 return rect.size.width <= 0 || rect.size.height <= 0;
83}
84
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +000085static CGFloat CGRectGetMinX_inline(const CGRect& rect) {
86 return rect.origin.x;
87}
88
89static CGFloat CGRectGetMaxX_inline(const CGRect& rect) {
90 return rect.origin.x + rect.size.width;
91}
92
93static CGFloat CGRectGetMinY_inline(const CGRect& rect) {
94 return rect.origin.y;
95}
96
97static CGFloat CGRectGetMaxY_inline(const CGRect& rect) {
98 return rect.origin.y + rect.size.height;
99}
100
101static CGFloat CGRectGetWidth_inline(const CGRect& rect) {
102 return rect.size.width;
103}
104
105///////////////////////////////////////////////////////////////////////////////
106
107static void sk_memset_rect32(uint32_t* ptr, uint32_t value,
reed@google.com7fa2a652014-01-27 13:42:58 +0000108 int width, int height, size_t rowBytes) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000109 SkASSERT(width);
110 SkASSERT(width * sizeof(uint32_t) <= rowBytes);
111
112 if (width >= 32) {
113 while (height) {
114 sk_memset32(ptr, value, width);
115 ptr = (uint32_t*)((char*)ptr + rowBytes);
116 height -= 1;
117 }
118 return;
119 }
120
121 rowBytes -= width * sizeof(uint32_t);
122
123 if (width >= 8) {
124 while (height) {
125 int w = width;
126 do {
127 *ptr++ = value; *ptr++ = value;
128 *ptr++ = value; *ptr++ = value;
129 *ptr++ = value; *ptr++ = value;
130 *ptr++ = value; *ptr++ = value;
131 w -= 8;
132 } while (w >= 8);
133 while (--w >= 0) {
134 *ptr++ = value;
135 }
136 ptr = (uint32_t*)((char*)ptr + rowBytes);
137 height -= 1;
138 }
139 } else {
140 while (height) {
141 int w = width;
142 do {
143 *ptr++ = value;
144 } while (--w > 0);
145 ptr = (uint32_t*)((char*)ptr + rowBytes);
146 height -= 1;
147 }
148 }
149}
150
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000151typedef uint32_t CGRGBPixel;
152
153static unsigned CGRGBPixel_getAlpha(CGRGBPixel pixel) {
154 return pixel & 0xFF;
155}
156
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000157static CGFloat ScalarToCG(SkScalar scalar) {
158 if (sizeof(CGFloat) == sizeof(float)) {
159 return SkScalarToFloat(scalar);
160 } else {
161 SkASSERT(sizeof(CGFloat) == sizeof(double));
162 return (CGFloat) SkScalarToDouble(scalar);
163 }
164}
165
166static SkScalar CGToScalar(CGFloat cgFloat) {
167 if (sizeof(CGFloat) == sizeof(float)) {
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700168 return SkFloatToScalar(cgFloat);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000169 } else {
170 SkASSERT(sizeof(CGFloat) == sizeof(double));
171 return SkDoubleToScalar(cgFloat);
172 }
173}
174
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700175static float CGToFloat(CGFloat cgFloat) {
176 if (sizeof(CGFloat) == sizeof(float)) {
177 return cgFloat;
178 } else {
179 SkASSERT(sizeof(CGFloat) == sizeof(double));
180 return static_cast<float>(cgFloat);
181 }
182}
183
bungemanc292b5f2016-12-20 12:04:29 -0500184static CGAffineTransform MatrixToCGAffineTransform(const SkMatrix& matrix) {
185 return CGAffineTransformMake( ScalarToCG(matrix[SkMatrix::kMScaleX]),
186 -ScalarToCG(matrix[SkMatrix::kMSkewY] ),
187 -ScalarToCG(matrix[SkMatrix::kMSkewX] ),
188 ScalarToCG(matrix[SkMatrix::kMScaleY]),
189 ScalarToCG(matrix[SkMatrix::kMTransX]),
190 ScalarToCG(matrix[SkMatrix::kMTransY]));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000191}
192
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000193///////////////////////////////////////////////////////////////////////////////
194
195#define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000196
197/**
198 * There does not appear to be a publicly accessable API for determining if lcd
199 * font smoothing will be applied if we request it. The main issue is that if
200 * smoothing is applied a gamma of 2.0 will be used, if not a gamma of 1.0.
201 */
202static bool supports_LCD() {
203 static int gSupportsLCD = -1;
204 if (gSupportsLCD >= 0) {
205 return (bool) gSupportsLCD;
206 }
207 uint32_t rgb = 0;
bungemanc292b5f2016-12-20 12:04:29 -0500208 UniqueCFRef<CGColorSpaceRef> colorspace(CGColorSpaceCreateDeviceRGB());
209 UniqueCFRef<CGContextRef> cgContext(
210 CGBitmapContextCreate(&rgb, 1, 1, 8, 4, colorspace.get(), BITMAP_INFO_RGB));
211 UniqueCFRef<CTFontRef> ctFont(CTFontCreateWithName(CFSTR("Helvetica"), 16, nullptr));
212 CGContextSetShouldSmoothFonts(cgContext.get(), true);
213 CGContextSetShouldAntialias(cgContext.get(), true);
214 CGContextSetTextDrawingMode(cgContext.get(), kCGTextFill);
215 CGContextSetGrayFillColor(cgContext.get(), 1, 1);
ccameronf8ee5b42016-10-04 15:02:02 -0700216 CGPoint point = CGPointMake(-1, 0);
217 static const UniChar pipeChar = '|';
218 CGGlyph pipeGlyph;
bungemanc292b5f2016-12-20 12:04:29 -0500219 CTFontGetGlyphsForCharacters(ctFont.get(), &pipeChar, &pipeGlyph, 1);
220 CTFontDrawGlyphs(ctFont.get(), &pipeGlyph, &point, 1, cgContext.get());
ccameronf8ee5b42016-10-04 15:02:02 -0700221
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000222 uint32_t r = (rgb >> 16) & 0xFF;
223 uint32_t g = (rgb >> 8) & 0xFF;
224 uint32_t b = (rgb >> 0) & 0xFF;
225 gSupportsLCD = (r != g || r != b);
226 return (bool) gSupportsLCD;
227}
228
229class Offscreen {
230public:
bungeman34902632014-12-10 21:43:27 -0800231 Offscreen()
halcanary96fcdcc2015-08-27 07:41:13 -0700232 : fRGBSpace(nullptr)
233 , fCG(nullptr)
bungeman34902632014-12-10 21:43:27 -0800234 , fDoAA(false)
235 , fDoLCD(false)
236 {
237 fSize.set(0, 0);
238 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000239
240 CGRGBPixel* getCG(const SkScalerContext_Mac& context, const SkGlyph& glyph,
bungemanc292b5f2016-12-20 12:04:29 -0500241 CGGlyph glyphID, size_t* rowBytesPtr, bool generateA8FromLCD);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000242
243private:
244 enum {
245 kSize = 32 * 32 * sizeof(CGRGBPixel)
246 };
247 SkAutoSMalloc<kSize> fImageStorage;
bungemanc292b5f2016-12-20 12:04:29 -0500248 UniqueCFRef<CGColorSpaceRef> fRGBSpace;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000249
250 // cached state
bungemanc292b5f2016-12-20 12:04:29 -0500251 UniqueCFRef<CGContextRef> fCG;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000252 SkISize fSize;
253 bool fDoAA;
254 bool fDoLCD;
255
256 static int RoundSize(int dimension) {
257 return SkNextPow2(dimension);
258 }
259};
260
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000261///////////////////////////////////////////////////////////////////////////////
262
bungeman6e45bda2016-07-25 15:11:49 -0700263static bool find_dict_CGFloat(CFDictionaryRef dict, CFStringRef name, CGFloat* value) {
bungemana4c4a2d2014-10-20 13:33:19 -0700264 CFNumberRef num;
265 return CFDictionaryGetValueIfPresent(dict, name, (const void**)&num)
bungemanc292b5f2016-12-20 12:04:29 -0500266 && CFNumberIsFloatType(num)
267 && CFNumberGetValue(num, kCFNumberCGFloatType, value);
bungemana4c4a2d2014-10-20 13:33:19 -0700268}
269
bungeman6e45bda2016-07-25 15:11:49 -0700270template <typename S, typename D, typename C> struct LinearInterpolater {
271 struct Mapping {
272 S src_val;
273 D dst_val;
274 };
275 constexpr LinearInterpolater(Mapping const mapping[], int mappingCount)
276 : fMapping(mapping), fMappingCount(mappingCount) {}
277
278 static D map(S value, S src_min, S src_max, D dst_min, D dst_max) {
279 SkASSERT(src_min < src_max);
280 SkASSERT(dst_min <= dst_max);
281 return C()(dst_min + (((value - src_min) * (dst_max - dst_min)) / (src_max - src_min)));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000282 }
bungeman6e45bda2016-07-25 15:11:49 -0700283
bungemanf1ef1fa2017-02-09 14:23:46 -0500284 D map(S val) const {
bungeman6e45bda2016-07-25 15:11:49 -0700285 // -Inf to [0]
286 if (val < fMapping[0].src_val) {
287 return fMapping[0].dst_val;
288 }
289
290 // Linear from [i] to [i+1]
291 for (int i = 0; i < fMappingCount - 1; ++i) {
292 if (val < fMapping[i+1].src_val) {
293 return map(val, fMapping[i].src_val, fMapping[i+1].src_val,
294 fMapping[i].dst_val, fMapping[i+1].dst_val);
295 }
296 }
297
298 // From [n] to +Inf
299 // if (fcweight < Inf)
300 return fMapping[fMappingCount - 1].dst_val;
301 }
302
303 Mapping const * fMapping;
304 int fMappingCount;
305};
306
307struct RoundCGFloatToInt {
308 int operator()(CGFloat s) { return s + 0.5; }
309};
bungemanf1ef1fa2017-02-09 14:23:46 -0500310struct CGFloatIdentity {
311 CGFloat operator()(CGFloat s) { return s; }
312};
313
314/** Convert the [0, 1000] CSS weight to [-1, 1] CTFontDescriptor weight (for system fonts).
315 *
316 * The -1 to 1 weights reported by CTFontDescriptors have different mappings depending on if the
317 * CTFont is native or created from a CGDataProvider.
318 */
319static CGFloat fontstyle_to_ct_weight(int fontstyleWeight) {
320 using Interpolator = LinearInterpolater<int, CGFloat, CGFloatIdentity>;
321
322 // Note that Mac supports the old OS2 version A so 0 through 10 are as if multiplied by 100.
323 // However, on this end we can't tell, so this is ignored.
324
325 /** This mapping for native fonts is determined by running the following in an .mm file
326 * #include <AppKit/AppKit>
327 * printf("{ 100, % #.2f },\n", NSFontWeightUltraLight);
328 * printf("{ 200, % #.2f },\n", NSFontWeightThin);
329 * printf("{ 300, % #.2f },\n", NSFontWeightLight);
330 * printf("{ 400, % #.2f },\n", NSFontWeightRegular);
331 * printf("{ 500, % #.2f },\n", NSFontWeightMedium);
332 * printf("{ 600, % #.2f },\n", NSFontWeightSemibold);
333 * printf("{ 700, % #.2f },\n", NSFontWeightBold);
334 * printf("{ 800, % #.2f },\n", NSFontWeightHeavy);
335 * printf("{ 900, % #.2f },\n", NSFontWeightBlack);
336 */
337 static constexpr Interpolator::Mapping nativeWeightMappings[] = {
338 { 0, -1.00 },
339 { 100, -0.80 },
340 { 200, -0.60 },
341 { 300, -0.40 },
342 { 400, 0.00 },
343 { 500, 0.23 },
344 { 600, 0.30 },
345 { 700, 0.40 },
346 { 800, 0.56 },
347 { 900, 0.62 },
348 { 1000, 1.00 },
349 };
350 static constexpr Interpolator nativeInterpolator(
351 nativeWeightMappings, SK_ARRAY_COUNT(nativeWeightMappings));
352
353 return nativeInterpolator.map(fontstyleWeight);
354}
355
bungeman6e45bda2016-07-25 15:11:49 -0700356
bungeman2873c762017-01-13 11:40:21 -0500357/** Convert the [-1, 1] CTFontDescriptor weight to [0, 1000] CSS weight.
358 *
359 * The -1 to 1 weights reported by CTFontDescriptors have different mappings depending on if the
360 * CTFont is native or created from a CGDataProvider.
361 */
362static int ct_weight_to_fontstyle(CGFloat cgWeight, bool fromDataProvider) {
bungeman6e45bda2016-07-25 15:11:49 -0700363 using Interpolator = LinearInterpolater<CGFloat, int, RoundCGFloatToInt>;
364
bungeman6e45bda2016-07-25 15:11:49 -0700365 // Note that Mac supports the old OS2 version A so 0 through 10 are as if multiplied by 100.
bungeman2873c762017-01-13 11:40:21 -0500366 // However, on this end we can't tell, so this is ignored.
367
368 /** This mapping for CGDataProvider created fonts is determined by creating font data with every
369 * weight, creating a CTFont, and asking the CTFont for its weight. See the TypefaceStyle test
370 * in tests/TypefaceTest.cpp for the code used to determine these values.
371 */
372 static constexpr Interpolator::Mapping dataProviderWeightMappings[] = {
bungeman6e45bda2016-07-25 15:11:49 -0700373 { -1.00, 0 },
374 { -0.70, 100 },
375 { -0.50, 200 },
376 { -0.23, 300 },
377 { 0.00, 400 },
378 { 0.20, 500 },
379 { 0.30, 600 },
380 { 0.40, 700 },
381 { 0.60, 800 },
382 { 0.80, 900 },
383 { 1.00, 1000 },
384 };
bungeman2873c762017-01-13 11:40:21 -0500385 static constexpr Interpolator dataProviderInterpolator(
386 dataProviderWeightMappings, SK_ARRAY_COUNT(dataProviderWeightMappings));
387
388 /** This mapping for native fonts is determined by running the following in an .mm file
389 * #include <AppKit/AppKit>
390 * printf("{ % #.2f, 100 },\n", NSFontWeightUltraLight);
391 * printf("{ % #.2f, 200 },\n", NSFontWeightThin);
392 * printf("{ % #.2f, 300 },\n", NSFontWeightLight);
393 * printf("{ % #.2f, 400 },\n", NSFontWeightRegular);
394 * printf("{ % #.2f, 500 },\n", NSFontWeightMedium);
395 * printf("{ % #.2f, 600 },\n", NSFontWeightSemibold);
396 * printf("{ % #.2f, 700 },\n", NSFontWeightBold);
397 * printf("{ % #.2f, 800 },\n", NSFontWeightHeavy);
398 * printf("{ % #.2f, 900 },\n", NSFontWeightBlack);
399 */
400 static constexpr Interpolator::Mapping nativeWeightMappings[] = {
401 { -1.00, 0 },
402 { -0.80, 100 },
403 { -0.60, 200 },
404 { -0.40, 300 },
405 { 0.00, 400 },
406 { 0.23, 500 },
407 { 0.30, 600 },
408 { 0.40, 700 },
409 { 0.56, 800 },
410 { 0.62, 900 },
411 { 1.00, 1000 },
412 };
413 static constexpr Interpolator nativeInterpolator(
414 nativeWeightMappings, SK_ARRAY_COUNT(nativeWeightMappings));
415
416 return fromDataProvider ? dataProviderInterpolator.map(cgWeight)
417 : nativeInterpolator.map(cgWeight);
bungemana4c4a2d2014-10-20 13:33:19 -0700418}
419
bungemanf1ef1fa2017-02-09 14:23:46 -0500420/** Convert the [0, 10] CSS weight to [-1, 1] CTFontDescriptor width. */
421static int fontstyle_to_ct_width(int fontstyleWidth) {
422 using Interpolator = LinearInterpolater<int, CGFloat, CGFloatIdentity>;
423
424 // Values determined by creating font data with every width, creating a CTFont,
425 // and asking the CTFont for its width. See TypefaceStyle test for basics.
426 static constexpr Interpolator::Mapping widthMappings[] = {
427 { 0, -0.5 },
428 { 10, 0.5 },
429 };
430 static constexpr Interpolator interpolator(widthMappings, SK_ARRAY_COUNT(widthMappings));
431 return interpolator.map(fontstyleWidth);
432}
433
434/** Convert the [-1, 1] CTFontDescriptor width to [0, 10] CSS weight. */
bungeman6e45bda2016-07-25 15:11:49 -0700435static int ct_width_to_fontstyle(CGFloat cgWidth) {
436 using Interpolator = LinearInterpolater<CGFloat, int, RoundCGFloatToInt>;
437
438 // Values determined by creating font data with every width, creating a CTFont,
439 // and asking the CTFont for its width. See TypefaceStyle test for basics.
440 static constexpr Interpolator::Mapping widthMappings[] = {
441 { -0.5, 0 },
442 { 0.5, 10 },
443 };
bungeman2873c762017-01-13 11:40:21 -0500444 static constexpr Interpolator interpolator(widthMappings, SK_ARRAY_COUNT(widthMappings));
445 return interpolator.map(cgWidth);
bungemana4c4a2d2014-10-20 13:33:19 -0700446}
447
bungeman2873c762017-01-13 11:40:21 -0500448static SkFontStyle fontstyle_from_descriptor(CTFontDescriptorRef desc, bool fromDataProvider) {
bungemanc292b5f2016-12-20 12:04:29 -0500449 UniqueCFRef<CFTypeRef> fontTraits(CTFontDescriptorCopyAttribute(desc, kCTFontTraitsAttribute));
450 if (!fontTraits || CFDictionaryGetTypeID() != CFGetTypeID(fontTraits.get())) {
bungemana4c4a2d2014-10-20 13:33:19 -0700451 return SkFontStyle();
452 }
bungemanc292b5f2016-12-20 12:04:29 -0500453 UniqueCFRef<CFDictionaryRef> fontTraitsDict(static_cast<CFDictionaryRef>(fontTraits.release()));
bungemana4c4a2d2014-10-20 13:33:19 -0700454
bungeman6e45bda2016-07-25 15:11:49 -0700455 CGFloat weight, width, slant;
bungemanc292b5f2016-12-20 12:04:29 -0500456 if (!find_dict_CGFloat(fontTraitsDict.get(), kCTFontWeightTrait, &weight)) {
bungeman336fdf22014-11-10 07:48:55 -0800457 weight = 0;
bungemana4c4a2d2014-10-20 13:33:19 -0700458 }
bungemanc292b5f2016-12-20 12:04:29 -0500459 if (!find_dict_CGFloat(fontTraitsDict.get(), kCTFontWidthTrait, &width)) {
bungemana4c4a2d2014-10-20 13:33:19 -0700460 width = 0;
461 }
bungemanc292b5f2016-12-20 12:04:29 -0500462 if (!find_dict_CGFloat(fontTraitsDict.get(), kCTFontSlantTrait, &slant)) {
bungeman336fdf22014-11-10 07:48:55 -0800463 slant = 0;
bungemana4c4a2d2014-10-20 13:33:19 -0700464 }
465
bungeman2873c762017-01-13 11:40:21 -0500466 return SkFontStyle(ct_weight_to_fontstyle(weight, fromDataProvider),
bungeman6e45bda2016-07-25 15:11:49 -0700467 ct_width_to_fontstyle(width),
bungemana4c4a2d2014-10-20 13:33:19 -0700468 slant ? SkFontStyle::kItalic_Slant
bungemanb4bb7d82016-04-27 10:21:04 -0700469 : SkFontStyle::kUpright_Slant);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000470}
471
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000472class SkTypeface_Mac : public SkTypeface {
473public:
bungemanc292b5f2016-12-20 12:04:29 -0500474 SkTypeface_Mac(UniqueCFRef<CTFontRef> fontRef, UniqueCFRef<CFTypeRef> resourceRef,
bungeman78884012015-06-08 13:39:12 -0700475 const SkFontStyle& fs, bool isFixedPitch,
bungeman53d5c6e2016-04-08 07:22:29 -0700476 bool isLocalStream)
bungemane3aea102016-07-13 05:16:58 -0700477 : SkTypeface(fs, isFixedPitch)
bungemanc292b5f2016-12-20 12:04:29 -0500478 , fFontRef(std::move(fontRef))
479 , fOriginatingCFTypeRef(std::move(resourceRef))
480 , fHasColorGlyphs(
481 SkToBool(CTFontGetSymbolicTraits(fFontRef.get()) & kCTFontColorGlyphsTrait))
caseq26337e92014-06-30 12:14:52 -0700482 , fIsLocalStream(isLocalStream)
reed@google.comce8b3de2013-03-26 19:30:16 +0000483 {
bungemanc292b5f2016-12-20 12:04:29 -0500484 SkASSERT(fFontRef);
reed@google.comce8b3de2013-03-26 19:30:16 +0000485 }
skia.committer@gmail.com37cbc7f2013-03-27 07:01:04 +0000486
bungemanc292b5f2016-12-20 12:04:29 -0500487 UniqueCFRef<CTFontRef> fFontRef;
488 UniqueCFRef<CFTypeRef> fOriginatingCFTypeRef;
bungemane3bea5c2015-04-07 07:34:36 -0700489 const bool fHasColorGlyphs;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000490
491protected:
mtklein36352bf2015-03-25 18:17:31 -0700492 int onGetUPEM() const override;
493 SkStreamAsset* onOpenStream(int* ttcIndex) const override;
bungemanf93d7112016-09-16 06:24:20 -0700494 std::unique_ptr<SkFontData> onMakeFontData() const override;
Ben Wagnerfc497342017-02-24 11:15:26 -0500495 int onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
496 int coordinateCount) const override;
mtklein36352bf2015-03-25 18:17:31 -0700497 void onGetFamilyName(SkString* familyName) const override;
498 SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override;
499 int onGetTableTags(SkFontTableTag tags[]) const override;
bungemanc292b5f2016-12-20 12:04:29 -0500500 size_t onGetTableData(SkFontTableTag, size_t offset, size_t length, void* data) const override;
reeda9322c22016-04-12 06:47:05 -0700501 SkScalerContext* onCreateScalerContext(const SkScalerContextEffects&,
502 const SkDescriptor*) const override;
mtklein36352bf2015-03-25 18:17:31 -0700503 void onFilterRec(SkScalerContextRec*) const override;
504 void onGetFontDescriptor(SkFontDescriptor*, bool*) const override;
bungemanc292b5f2016-12-20 12:04:29 -0500505 SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics(
506 PerGlyphInfo, const uint32_t* glyphIDs, uint32_t glyphIDsCount) const override;
507 int onCharsToGlyphs(const void* chars, Encoding,
508 uint16_t glyphs[], int glyphCount) const override;
mtklein36352bf2015-03-25 18:17:31 -0700509 int onCountGlyphs() const override;
skia.committer@gmail.comc1641fc2013-03-21 07:01:39 +0000510
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000511private:
caseq26337e92014-06-30 12:14:52 -0700512 bool fIsLocalStream;
reed@google.comce8b3de2013-03-26 19:30:16 +0000513
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000514 typedef SkTypeface INHERITED;
515};
516
bungeman82a455f2016-04-14 08:04:45 -0700517static bool find_by_CTFontRef(SkTypeface* cached, void* context) {
bungeman64fb51d2015-05-04 12:03:50 -0700518 CTFontRef self = (CTFontRef)context;
bungemanc292b5f2016-12-20 12:04:29 -0500519 CTFontRef other = ((SkTypeface_Mac*)cached)->fFontRef.get();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000520
bungeman64fb51d2015-05-04 12:03:50 -0700521 return CFEqual(self, other);
522}
523
bungemanc292b5f2016-12-20 12:04:29 -0500524/** Creates a typeface, searching the cache if isLocalStream is false. */
525static SkTypeface* create_from_CTFontRef(UniqueCFRef<CTFontRef> font,
526 UniqueCFRef<CFTypeRef> resource,
527 bool isLocalStream) {
528 SkASSERT(font);
bungemanbea97482016-08-24 08:29:50 -0700529
530 if (!isLocalStream) {
531 SkTypeface* face = SkTypefaceCache::FindByProcAndRef(find_by_CTFontRef, (void*)font.get());
532 if (face) {
533 return face;
534 }
535 }
536
bungemanc292b5f2016-12-20 12:04:29 -0500537 UniqueCFRef<CTFontDescriptorRef> desc(CTFontCopyFontDescriptor(font.get()));
bungeman2873c762017-01-13 11:40:21 -0500538 SkFontStyle style = fontstyle_from_descriptor(desc.get(), isLocalStream);
bungemanc292b5f2016-12-20 12:04:29 -0500539 CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font.get());
bungemanbea97482016-08-24 08:29:50 -0700540 bool isFixedPitch = SkToBool(traits & kCTFontMonoSpaceTrait);
541
bungemanc292b5f2016-12-20 12:04:29 -0500542 SkTypeface* face = new SkTypeface_Mac(std::move(font), std::move(resource),
bungemanbea97482016-08-24 08:29:50 -0700543 style, isFixedPitch, isLocalStream);
544 if (!isLocalStream) {
545 SkTypefaceCache::Add(face);
546 }
547 return face;
548}
549
550/** Creates a typeface from a descriptor, searching the cache. */
551static SkTypeface* create_from_desc(CTFontDescriptorRef desc) {
bungemanc292b5f2016-12-20 12:04:29 -0500552 UniqueCFRef<CTFontRef> ctFont(CTFontCreateWithFontDescriptor(desc, 0, nullptr));
bungemanbea97482016-08-24 08:29:50 -0700553 if (!ctFont) {
554 return nullptr;
555 }
556
bungemanc292b5f2016-12-20 12:04:29 -0500557 return create_from_CTFontRef(std::move(ctFont), nullptr, false);
bungemanbea97482016-08-24 08:29:50 -0700558}
559
bungemanc292b5f2016-12-20 12:04:29 -0500560static UniqueCFRef<CTFontDescriptorRef> create_descriptor(const char familyName[],
561 const SkFontStyle& style) {
bungemanc292b5f2016-12-20 12:04:29 -0500562 UniqueCFRef<CFMutableDictionaryRef> cfAttributes(
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000563 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
564 &kCFTypeDictionaryKeyCallBacks,
565 &kCFTypeDictionaryValueCallBacks));
566
bungemanc292b5f2016-12-20 12:04:29 -0500567 UniqueCFRef<CFMutableDictionaryRef> cfTraits(
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000568 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
569 &kCFTypeDictionaryKeyCallBacks,
570 &kCFTypeDictionaryValueCallBacks));
571
bungeman83f1f442017-02-06 13:21:33 -0500572 if (!cfAttributes || !cfTraits) {
halcanary96fcdcc2015-08-27 07:41:13 -0700573 return nullptr;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000574 }
575
bungemanf1ef1fa2017-02-09 14:23:46 -0500576 // CTFontTraits (symbolic)
bungeman83f1f442017-02-06 13:21:33 -0500577 CTFontSymbolicTraits ctFontTraits = 0;
578 if (style.weight() >= SkFontStyle::kBold_Weight) {
579 ctFontTraits |= kCTFontBoldTrait;
580 }
581 if (style.slant() != SkFontStyle::kUpright_Slant) {
582 ctFontTraits |= kCTFontItalicTrait;
583 }
584 UniqueCFRef<CFNumberRef> cfFontTraits(
585 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &ctFontTraits));
586 if (cfFontTraits) {
587 CFDictionaryAddValue(cfTraits.get(), kCTFontSymbolicTrait, cfFontTraits.get());
bungeman83f1f442017-02-06 13:21:33 -0500588 }
bungemanf1ef1fa2017-02-09 14:23:46 -0500589 // CTFontTraits (weight)
590 CGFloat ctWeight = fontstyle_to_ct_weight(style.weight());
591 UniqueCFRef<CFNumberRef> cfFontWeight(
592 CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWeight));
593 if (cfFontWeight) {
594 CFDictionaryAddValue(cfTraits.get(), kCTFontWeightTrait, cfFontWeight.get());
595 }
596 // CTFontTraits (width)
597 CGFloat ctWidth = fontstyle_to_ct_width(style.weight());
598 UniqueCFRef<CFNumberRef> cfFontWidth(
599 CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWidth));
600 if (cfFontWidth) {
601 CFDictionaryAddValue(cfTraits.get(), kCTFontWidthTrait, cfFontWidth.get());
602 }
603 // CTFontTraits (slant)
604 CGFloat ctSlant = style.slant() == SkFontStyle::kUpright_Slant ? 0 : 1;
605 UniqueCFRef<CFNumberRef> cfFontSlant(
606 CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctSlant));
607 if (cfFontSlant) {
608 CFDictionaryAddValue(cfTraits.get(), kCTFontSlantTrait, cfFontSlant.get());
609 }
610 // CTFontTraits
611 CFDictionaryAddValue(cfAttributes.get(), kCTFontTraitsAttribute, cfTraits.get());
bungeman83f1f442017-02-06 13:21:33 -0500612
613 // CTFontFamilyName
614 if (familyName) {
615 UniqueCFRef<CFStringRef> cfFontName = make_CFString(familyName);
616 if (cfFontName) {
617 CFDictionaryAddValue(cfAttributes.get(), kCTFontFamilyNameAttribute, cfFontName.get());
618 }
619 }
bungeman64fb51d2015-05-04 12:03:50 -0700620
bungemanc292b5f2016-12-20 12:04:29 -0500621 return UniqueCFRef<CTFontDescriptorRef>(
622 CTFontDescriptorCreateWithAttributes(cfAttributes.get()));
bungemanbea97482016-08-24 08:29:50 -0700623}
624
625/** Creates a typeface from a name, searching the cache. */
626static SkTypeface* create_from_name(const char familyName[], const SkFontStyle& style) {
bungemanc292b5f2016-12-20 12:04:29 -0500627 UniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style);
bungemanbea97482016-08-24 08:29:50 -0700628 if (!desc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700629 return nullptr;
bungeman64fb51d2015-05-04 12:03:50 -0700630 }
bungemanc292b5f2016-12-20 12:04:29 -0500631 return create_from_desc(desc.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000632}
633
634///////////////////////////////////////////////////////////////////////////////
635
636extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);
637CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face) {
638 const SkTypeface_Mac* macface = (const SkTypeface_Mac*)face;
halcanary96fcdcc2015-08-27 07:41:13 -0700639 return macface ? macface->fFontRef.get() : nullptr;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000640}
641
642/* This function is visible on the outside. It first searches the cache, and if
643 * not found, returns a new entry (after adding it to the cache).
644 */
bungemanc292b5f2016-12-20 12:04:29 -0500645SkTypeface* SkCreateTypefaceFromCTFont(CTFontRef font, CFTypeRef resource) {
646 CFRetain(font);
647 if (resource) {
648 CFRetain(resource);
bungeman53d5c6e2016-04-08 07:22:29 -0700649 }
bungemanc292b5f2016-12-20 12:04:29 -0500650 return create_from_CTFontRef(UniqueCFRef<CTFontRef>(font),
651 UniqueCFRef<CFTypeRef>(resource),
652 false);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000653}
654
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000655static const char* map_css_names(const char* name) {
656 static const struct {
657 const char* fFrom; // name the caller specified
658 const char* fTo; // "canonical" name we map to
659 } gPairs[] = {
660 { "sans-serif", "Helvetica" },
661 { "serif", "Times" },
662 { "monospace", "Courier" }
663 };
664
665 for (size_t i = 0; i < SK_ARRAY_COUNT(gPairs); i++) {
666 if (strcmp(name, gPairs[i].fFrom) == 0) {
667 return gPairs[i].fTo;
668 }
669 }
670 return name; // no change
671}
672
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000673///////////////////////////////////////////////////////////////////////////////
674
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000675class SkScalerContext_Mac : public SkScalerContext {
676public:
bungeman7cfd46a2016-10-20 16:06:52 -0400677 SkScalerContext_Mac(sk_sp<SkTypeface_Mac>, const SkScalerContextEffects&, const SkDescriptor*);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000678
679protected:
mtklein36352bf2015-03-25 18:17:31 -0700680 unsigned generateGlyphCount(void) override;
681 uint16_t generateCharToGlyph(SkUnichar uni) override;
682 void generateAdvance(SkGlyph* glyph) override;
683 void generateMetrics(SkGlyph* glyph) override;
684 void generateImage(const SkGlyph& glyph) override;
Ben Wagner6e9ac122016-11-11 14:31:06 -0500685 void generatePath(SkGlyphID glyph, SkPath* path) override;
mtklein36352bf2015-03-25 18:17:31 -0700686 void generateFontMetrics(SkPaint::FontMetrics*) override;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000687
688private:
689 static void CTPathElement(void *info, const CGPathElement *element);
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000690
bungeman@google.comcefd9812013-05-15 15:07:32 +0000691 /** Returns the offset from the horizontal origin to the vertical origin in SkGlyph units. */
692 void getVerticalOffset(CGGlyph glyphID, SkPoint* offset) const;
bungeman@google.comcefd9812013-05-15 15:07:32 +0000693
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000694 Offscreen fOffscreen;
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000695
bungeman3b4b66c2015-01-08 08:33:44 -0800696 /** Unrotated variant of fCTFont.
697 *
698 * In 10.10.1 CTFontGetAdvancesForGlyphs applies the font transform to the width of the
699 * advances, but always sets the height to 0. This font is used to get the advances of the
700 * unrotated glyph, and then the rotation is applied separately.
bungeman@google.comcefd9812013-05-15 15:07:32 +0000701 *
702 * CT vertical metrics are pre-rotated (in em space, before transform) 90deg clock-wise.
bungeman18ec7b92017-02-09 17:15:59 -0500703 * This makes kCTFontOrientationDefault dangerous, because the metrics from
704 * kCTFontOrientationHorizontal are in a different space from kCTFontOrientationVertical.
705 * With kCTFontOrientationVertical the advances must be unrotated.
bungemanef27ce32015-10-29 09:30:32 -0700706 *
707 * Sometimes, creating a copy of a CTFont with the same size but different trasform will select
708 * different underlying font data. As a result, avoid ever creating more than one CTFont per
709 * SkScalerContext to ensure that only one CTFont is used.
710 *
711 * As a result of the above (and other constraints) this font contains the size, but not the
712 * transform. The transform must always be applied separately.
bungeman@google.comcefd9812013-05-15 15:07:32 +0000713 */
bungemanc292b5f2016-12-20 12:04:29 -0500714 UniqueCFRef<CTFontRef> fCTFont;
bungemanef27ce32015-10-29 09:30:32 -0700715
716 /** The transform without the font size. */
717 CGAffineTransform fTransform;
718 CGAffineTransform fInvTransform;
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000719
bungemanc292b5f2016-12-20 12:04:29 -0500720 UniqueCFRef<CGFontRef> fCGFont;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000721 uint16_t fGlyphCount;
bungeman@google.comcefd9812013-05-15 15:07:32 +0000722 const bool fDoSubPosition;
723 const bool fVertical;
724
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000725 friend class Offscreen;
reed@google.com0da48612013-03-19 16:06:52 +0000726
727 typedef SkScalerContext INHERITED;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000728};
729
bungeman7cbeaae2015-09-22 09:54:56 -0700730// CTFontCreateCopyWithAttributes or CTFontCreateCopyWithSymbolicTraits cannot be used on 10.10
bungeman05846312015-09-23 12:51:28 -0700731// and later, as they will return different underlying fonts depending on the size requested.
732// It is not possible to use descriptors with CTFontCreateWithFontDescriptor, since that does not
733// work with non-system fonts. As a result, create the strike specific CTFonts from the underlying
734// CGFont.
bungemanc292b5f2016-12-20 12:04:29 -0500735static UniqueCFRef<CTFontRef> ctfont_create_exact_copy(CTFontRef baseFont, CGFloat textSize,
736 const CGAffineTransform* transform)
bungeman7cbeaae2015-09-22 09:54:56 -0700737{
bungemanc292b5f2016-12-20 12:04:29 -0500738 UniqueCFRef<CGFontRef> baseCGFont(CTFontCopyGraphicsFont(baseFont, nullptr));
bungeman7cbeaae2015-09-22 09:54:56 -0700739
bungeman05846312015-09-23 12:51:28 -0700740 // The last parameter (CTFontDescriptorRef attributes) *must* be nullptr.
741 // If non-nullptr then with fonts with variation axes, the copy will fail in
742 // CGFontVariationFromDictCallback when it assumes kCGFontVariationAxisName is CFNumberRef
743 // which it quite obviously is not.
bungeman7cbeaae2015-09-22 09:54:56 -0700744
bungeman05846312015-09-23 12:51:28 -0700745 // Because we cannot setup the CTFont descriptor to match, the same restriction applies here
746 // as other uses of CTFontCreateWithGraphicsFont which is that such CTFonts should not escape
747 // the scaler context, since they aren't 'normal'.
bungemanc292b5f2016-12-20 12:04:29 -0500748 return UniqueCFRef<CTFontRef>(
749 CTFontCreateWithGraphicsFont(baseCGFont.get(), textSize, transform, nullptr));
bungeman7cbeaae2015-09-22 09:54:56 -0700750}
751
bungeman7cfd46a2016-10-20 16:06:52 -0400752SkScalerContext_Mac::SkScalerContext_Mac(sk_sp<SkTypeface_Mac> typeface,
reeda9322c22016-04-12 06:47:05 -0700753 const SkScalerContextEffects& effects,
reed@google.com0da48612013-03-19 16:06:52 +0000754 const SkDescriptor* desc)
bungeman7cfd46a2016-10-20 16:06:52 -0400755 : INHERITED(std::move(typeface), effects, desc)
bungeman@google.comcefd9812013-05-15 15:07:32 +0000756 , fDoSubPosition(SkToBool(fRec.fFlags & kSubpixelPositioning_Flag))
757 , fVertical(SkToBool(fRec.fFlags & kVertical_Flag))
758
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000759{
reedd0f41732015-07-10 12:08:38 -0700760 AUTO_CG_LOCK();
761
bungeman7cfd46a2016-10-20 16:06:52 -0400762 CTFontRef ctFont = static_cast<SkTypeface_Mac*>(this->getTypeface())->fFontRef.get();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000763 CFIndex numGlyphs = CTFontGetGlyphCount(ctFont);
bungeman@google.comcefd9812013-05-15 15:07:32 +0000764 SkASSERT(numGlyphs >= 1 && numGlyphs <= 0xFFFF);
765 fGlyphCount = SkToU16(numGlyphs);
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000766
bungeman34902632014-12-10 21:43:27 -0800767 // CT on (at least) 10.9 will size color glyphs down from the requested size, but not up.
768 // As a result, it is necessary to know the actual device size and request that.
769 SkVector scale;
bungemanbe2284d2014-11-25 08:08:09 -0800770 SkMatrix skTransform;
bungemane55131c2016-08-24 12:01:31 -0700771 bool invertible = fRec.computeMatrices(SkScalerContextRec::kVertical_PreMatrixScale,
bungeman4ec46aa2017-02-15 17:49:12 -0500772 &scale, &skTransform, nullptr, nullptr, nullptr);
bungemanaae30912015-03-02 13:43:26 -0800773 fTransform = MatrixToCGAffineTransform(skTransform);
bungeman1f0e78d2016-08-23 13:19:01 -0700774 // CGAffineTransformInvert documents that if the transform is non-invertible it will return the
775 // passed transform unchanged. It does so, but then also prints a message to stdout. Avoid this.
bungemane55131c2016-08-24 12:01:31 -0700776 if (invertible) {
bungeman1f0e78d2016-08-23 13:19:01 -0700777 fInvTransform = CGAffineTransformInvert(fTransform);
778 } else {
779 fInvTransform = fTransform;
780 }
bungeman@google.comcefd9812013-05-15 15:07:32 +0000781
bungemanbe2284d2014-11-25 08:08:09 -0800782 // The transform contains everything except the requested text size.
783 // Some properties, like 'trak', are based on the text size (before applying the matrix).
bungeman34902632014-12-10 21:43:27 -0800784 CGFloat textSize = ScalarToCG(scale.y());
bungemanc292b5f2016-12-20 12:04:29 -0500785 fCTFont = ctfont_create_exact_copy(ctFont, textSize, nullptr);
786 fCGFont.reset(CTFontCopyGraphicsFont(fCTFont.get(), nullptr));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000787}
788
789CGRGBPixel* Offscreen::getCG(const SkScalerContext_Mac& context, const SkGlyph& glyph,
790 CGGlyph glyphID, size_t* rowBytesPtr,
mtkleinbbd40182015-09-08 08:19:33 -0700791 bool generateA8FromLCD) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000792 if (!fRGBSpace) {
793 //It doesn't appear to matter what color space is specified.
794 //Regular blends and antialiased text are always (s*a + d*(1-a))
795 //and smoothed text is always g=2.0.
bungemane194c492014-07-16 13:46:06 -0700796 fRGBSpace.reset(CGColorSpaceCreateDeviceRGB());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000797 }
798
799 // default to kBW_Format
800 bool doAA = false;
801 bool doLCD = false;
802
803 if (SkMask::kBW_Format != glyph.fMaskFormat) {
804 doLCD = true;
805 doAA = true;
806 }
807
808 // FIXME: lcd smoothed un-hinted rasterization unsupported.
809 if (!generateA8FromLCD && SkMask::kA8_Format == glyph.fMaskFormat) {
810 doLCD = false;
811 doAA = true;
812 }
813
bungeman34902632014-12-10 21:43:27 -0800814 // If this font might have color glyphs, disable LCD as there's no way to support it.
815 // CoreText doesn't tell us which format it ended up using, so we can't detect it.
bungemane280d062016-03-24 11:27:05 -0700816 // A8 will end up black on transparent, but TODO: we can detect gray and set to A8.
bungeman34902632014-12-10 21:43:27 -0800817 if (SkMask::kARGB32_Format == glyph.fMaskFormat) {
818 doLCD = false;
819 }
820
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000821 size_t rowBytes = fSize.fWidth * sizeof(CGRGBPixel);
822 if (!fCG || fSize.fWidth < glyph.fWidth || fSize.fHeight < glyph.fHeight) {
823 if (fSize.fWidth < glyph.fWidth) {
824 fSize.fWidth = RoundSize(glyph.fWidth);
825 }
826 if (fSize.fHeight < glyph.fHeight) {
827 fSize.fHeight = RoundSize(glyph.fHeight);
828 }
829
830 rowBytes = fSize.fWidth * sizeof(CGRGBPixel);
831 void* image = fImageStorage.reset(rowBytes * fSize.fHeight);
bungeman34902632014-12-10 21:43:27 -0800832 const CGImageAlphaInfo alpha = (SkMask::kARGB32_Format == glyph.fMaskFormat)
833 ? kCGImageAlphaPremultipliedFirst
834 : kCGImageAlphaNoneSkipFirst;
835 const CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host | alpha;
bungemane194c492014-07-16 13:46:06 -0700836 fCG.reset(CGBitmapContextCreate(image, fSize.fWidth, fSize.fHeight, 8,
bungemanc292b5f2016-12-20 12:04:29 -0500837 rowBytes, fRGBSpace.get(), bitmapInfo));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000838
bungeman34902632014-12-10 21:43:27 -0800839 // Skia handles quantization and subpixel positioning,
840 // so disable quantization and enabe subpixel positioning in CG.
bungemanc292b5f2016-12-20 12:04:29 -0500841 CGContextSetAllowsFontSubpixelQuantization(fCG.get(), false);
842 CGContextSetShouldSubpixelQuantizeFonts(fCG.get(), false);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000843
bungeman@google.comcefd9812013-05-15 15:07:32 +0000844 // Because CG always draws from the horizontal baseline,
845 // if there is a non-integral translation from the horizontal origin to the vertical origin,
846 // then CG cannot draw the glyph in the correct location without subpixel positioning.
bungemanc292b5f2016-12-20 12:04:29 -0500847 CGContextSetAllowsFontSubpixelPositioning(fCG.get(), true);
848 CGContextSetShouldSubpixelPositionFonts(fCG.get(), true);
bungeman34902632014-12-10 21:43:27 -0800849
bungemanc292b5f2016-12-20 12:04:29 -0500850 CGContextSetTextDrawingMode(fCG.get(), kCGTextFill);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000851
bungemane280d062016-03-24 11:27:05 -0700852 // Draw black on white to create mask. (Special path exists to speed this up in CG.)
bungemanc292b5f2016-12-20 12:04:29 -0500853 CGContextSetGrayFillColor(fCG.get(), 0.0f, 1.0f);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000854
855 // force our checks below to happen
856 fDoAA = !doAA;
857 fDoLCD = !doLCD;
bungeman34902632014-12-10 21:43:27 -0800858
bungemanc292b5f2016-12-20 12:04:29 -0500859 CGContextSetTextMatrix(fCG.get(), context.fTransform);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000860 }
861
862 if (fDoAA != doAA) {
bungemanc292b5f2016-12-20 12:04:29 -0500863 CGContextSetShouldAntialias(fCG.get(), doAA);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000864 fDoAA = doAA;
865 }
866 if (fDoLCD != doLCD) {
bungemanc292b5f2016-12-20 12:04:29 -0500867 CGContextSetShouldSmoothFonts(fCG.get(), doLCD);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000868 fDoLCD = doLCD;
869 }
870
871 CGRGBPixel* image = (CGRGBPixel*)fImageStorage.get();
872 // skip rows based on the glyph's height
873 image += (fSize.fHeight - glyph.fHeight) * fSize.fWidth;
874
bungemane280d062016-03-24 11:27:05 -0700875 // Erase to white (or transparent black if it's a color glyph, to not composite against white).
876 uint32_t bgColor = (SkMask::kARGB32_Format != glyph.fMaskFormat) ? 0xFFFFFFFF : 0x00000000;
877 sk_memset_rect32(image, bgColor, glyph.fWidth, glyph.fHeight, rowBytes);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000878
879 float subX = 0;
880 float subY = 0;
881 if (context.fDoSubPosition) {
882 subX = SkFixedToFloat(glyph.getSubXFixed());
883 subY = SkFixedToFloat(glyph.getSubYFixed());
884 }
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000885
bungeman34902632014-12-10 21:43:27 -0800886 // CoreText and CoreGraphics always draw using the horizontal baseline origin.
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000887 if (context.fVertical) {
bungeman@google.comcefd9812013-05-15 15:07:32 +0000888 SkPoint offset;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000889 context.getVerticalOffset(glyphID, &offset);
890 subX += offset.fX;
891 subY += offset.fY;
892 }
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000893
bungeman34902632014-12-10 21:43:27 -0800894 CGPoint point = CGPointMake(-glyph.fLeft + subX, glyph.fTop + glyph.fHeight - subY);
bungemanaae30912015-03-02 13:43:26 -0800895 // Prior to 10.10, CTFontDrawGlyphs acted like CGContextShowGlyphsAtPositions and took
896 // 'positions' which are in text space. The glyph location (in device space) must be
897 // mapped into text space, so that CG can convert it back into device space.
Hal Canary55325b72017-01-03 10:36:17 -0500898 // In 10.10.1, this is handled directly in CTFontDrawGlyphs.
bungeman1b5f25c2015-06-08 14:32:24 -0700899 //
bungemanaae30912015-03-02 13:43:26 -0800900 // However, in 10.10.2 color glyphs no longer rotate based on the font transform.
901 // So always make the font transform identity and place the transform on the context.
902 point = CGPointApplyAffineTransform(point, context.fInvTransform);
903
bungemanc292b5f2016-12-20 12:04:29 -0500904 CTFontDrawGlyphs(context.fCTFont.get(), &glyphID, &point, 1, fCG.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000905
906 SkASSERT(rowBytesPtr);
907 *rowBytesPtr = rowBytes;
908 return image;
909}
910
bungeman@google.comcefd9812013-05-15 15:07:32 +0000911void SkScalerContext_Mac::getVerticalOffset(CGGlyph glyphID, SkPoint* offset) const {
bungemanc2ba75b2016-12-14 16:53:00 -0500912 // CTFontGetVerticalTranslationsForGlyphs produces cgVertOffset in CG units (pixels, y up).
bungeman@google.comcefd9812013-05-15 15:07:32 +0000913 CGSize cgVertOffset;
bungemanc292b5f2016-12-20 12:04:29 -0500914 CTFontGetVerticalTranslationsForGlyphs(fCTFont.get(), &glyphID, &cgVertOffset, 1);
bungemanef27ce32015-10-29 09:30:32 -0700915 cgVertOffset = CGSizeApplyAffineTransform(cgVertOffset, fTransform);
916 SkPoint skVertOffset = { CGToScalar(cgVertOffset.width), CGToScalar(cgVertOffset.height) };
917 // From CG units (pixels, y up) to SkGlyph units (pixels, y down).
918 skVertOffset.fY = -skVertOffset.fY;
bungeman@google.comcefd9812013-05-15 15:07:32 +0000919 *offset = skVertOffset;
920}
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000921
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000922unsigned SkScalerContext_Mac::generateGlyphCount(void) {
923 return fGlyphCount;
924}
925
926uint16_t SkScalerContext_Mac::generateCharToGlyph(SkUnichar uni) {
reedd0f41732015-07-10 12:08:38 -0700927 AUTO_CG_LOCK();
928
bungeman@google.comfb1663a2013-10-24 22:32:43 +0000929 CGGlyph cgGlyph[2];
bungeman@google.com72b8cb22013-10-25 17:49:08 +0000930 UniChar theChar[2]; // UniChar is a UTF-16 16-bit code unit.
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000931
932 // Get the glyph
bungeman@google.comfb1663a2013-10-24 22:32:43 +0000933 size_t numUniChar = SkUTF16_FromUnichar(uni, theChar);
934 SkASSERT(sizeof(CGGlyph) <= sizeof(uint16_t));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000935
bungeman@google.com72b8cb22013-10-25 17:49:08 +0000936 // Undocumented behavior of CTFontGetGlyphsForCharacters with non-bmp code points:
937 // When a surrogate pair is detected, the glyph index used is the index of the high surrogate.
938 // It is documented that if a mapping is unavailable, the glyph will be set to 0.
bungemanc292b5f2016-12-20 12:04:29 -0500939 CTFontGetGlyphsForCharacters(fCTFont.get(), theChar, cgGlyph, numUniChar);
bungeman@google.comfb1663a2013-10-24 22:32:43 +0000940 return cgGlyph[0];
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000941}
942
943void SkScalerContext_Mac::generateAdvance(SkGlyph* glyph) {
944 this->generateMetrics(glyph);
945}
946
bungeman@google.comcefd9812013-05-15 15:07:32 +0000947void SkScalerContext_Mac::generateMetrics(SkGlyph* glyph) {
reedd0f41732015-07-10 12:08:38 -0700948 AUTO_CG_LOCK();
949
djsollen1b277042014-08-06 06:58:06 -0700950 const CGGlyph cgGlyph = (CGGlyph) glyph->getGlyphID();
bungeman@google.comcefd9812013-05-15 15:07:32 +0000951 glyph->zeroMetrics();
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000952
bungeman@google.comcefd9812013-05-15 15:07:32 +0000953 // The following block produces cgAdvance in CG units (pixels, y up).
954 CGSize cgAdvance;
955 if (fVertical) {
bungeman18ec7b92017-02-09 17:15:59 -0500956 CTFontGetAdvancesForGlyphs(fCTFont.get(), kCTFontOrientationVertical,
bungeman@google.comcefd9812013-05-15 15:07:32 +0000957 &cgGlyph, &cgAdvance, 1);
bungeman3b4b66c2015-01-08 08:33:44 -0800958 // Vertical advances are returned as widths instead of heights.
959 SkTSwap(cgAdvance.height, cgAdvance.width);
960 cgAdvance.height = -cgAdvance.height;
bungeman@google.comcefd9812013-05-15 15:07:32 +0000961 } else {
bungeman18ec7b92017-02-09 17:15:59 -0500962 CTFontGetAdvancesForGlyphs(fCTFont.get(), kCTFontOrientationHorizontal,
bungeman@google.comcefd9812013-05-15 15:07:32 +0000963 &cgGlyph, &cgAdvance, 1);
964 }
bungemanef27ce32015-10-29 09:30:32 -0700965 cgAdvance = CGSizeApplyAffineTransform(cgAdvance, fTransform);
benjaminwagner6b3eacb2016-03-24 19:07:58 -0700966 glyph->fAdvanceX = CGToFloat(cgAdvance.width);
967 glyph->fAdvanceY = -CGToFloat(cgAdvance.height);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +0000968
bungeman@google.comcefd9812013-05-15 15:07:32 +0000969 // The following produces skBounds in SkGlyph units (pixels, y down),
970 // or returns early if skBounds would be empty.
971 SkRect skBounds;
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000972
bungemanc2ba75b2016-12-14 16:53:00 -0500973 // Glyphs are always drawn from the horizontal origin. The caller must manually use the result
974 // of CTFontGetVerticalTranslationsForGlyphs to calculate where to draw the glyph for vertical
975 // glyphs. As a result, always get the horizontal bounds of a glyph and translate it if the
976 // glyph is vertical. This avoids any diagreement between the various means of retrieving
977 // vertical metrics.
bungeman@google.comcefd9812013-05-15 15:07:32 +0000978 {
bungeman@google.comcefd9812013-05-15 15:07:32 +0000979 // CTFontGetBoundingRectsForGlyphs produces cgBounds in CG units (pixels, y up).
980 CGRect cgBounds;
bungeman18ec7b92017-02-09 17:15:59 -0500981 CTFontGetBoundingRectsForGlyphs(fCTFont.get(), kCTFontOrientationHorizontal,
bungeman@google.comcefd9812013-05-15 15:07:32 +0000982 &cgGlyph, &cgBounds, 1);
bungemanef27ce32015-10-29 09:30:32 -0700983 cgBounds = CGRectApplyAffineTransform(cgBounds, fTransform);
skia.committer@gmail.com539f3642013-05-16 07:01:00 +0000984
bungeman@google.comcefd9812013-05-15 15:07:32 +0000985 // BUG?
986 // 0x200B (zero-advance space) seems to return a huge (garbage) bounds, when
987 // it should be empty. So, if we see a zero-advance, we check if it has an
988 // empty path or not, and if so, we jam the bounds to 0. Hopefully a zero-advance
989 // is rare, so we won't incur a big performance cost for this extra check.
990 if (0 == cgAdvance.width && 0 == cgAdvance.height) {
bungemanc292b5f2016-12-20 12:04:29 -0500991 UniqueCFRef<CGPathRef> path(CTFontCreatePathForGlyph(fCTFont.get(), cgGlyph, nullptr));
992 if (!path || CGPathIsEmpty(path.get())) {
bungeman@google.comcefd9812013-05-15 15:07:32 +0000993 return;
994 }
995 }
996
997 if (CGRectIsEmpty_inline(cgBounds)) {
998 return;
999 }
1000
1001 // Convert cgBounds to SkGlyph units (pixels, y down).
1002 skBounds = SkRect::MakeXYWH(cgBounds.origin.x, -cgBounds.origin.y - cgBounds.size.height,
1003 cgBounds.size.width, cgBounds.size.height);
1004 }
1005
1006 if (fVertical) {
bungemanc2ba75b2016-12-14 16:53:00 -05001007 // Due to possible vertical bounds bugs and simplicity, skBounds is the horizontal bounds.
bungeman@google.comcefd9812013-05-15 15:07:32 +00001008 // Convert these horizontal bounds into vertical bounds.
1009 SkPoint offset;
bungemanc2ba75b2016-12-14 16:53:00 -05001010 this->getVerticalOffset(cgGlyph, &offset);
bungeman@google.comcefd9812013-05-15 15:07:32 +00001011 skBounds.offset(offset);
1012 }
skia.committer@gmail.com539f3642013-05-16 07:01:00 +00001013
bungeman@google.comcefd9812013-05-15 15:07:32 +00001014 // Currently the bounds are based on being rendered at (0,0).
1015 // The top left must not move, since that is the base from which subpixel positioning is offset.
1016 if (fDoSubPosition) {
1017 skBounds.fRight += SkFixedToFloat(glyph->getSubXFixed());
1018 skBounds.fBottom += SkFixedToFloat(glyph->getSubYFixed());
1019 }
skia.committer@gmail.com539f3642013-05-16 07:01:00 +00001020
bungeman@google.comcefd9812013-05-15 15:07:32 +00001021 SkIRect skIBounds;
1022 skBounds.roundOut(&skIBounds);
1023 // Expand the bounds by 1 pixel, to give CG room for anti-aliasing.
1024 // Note that this outset is to allow room for LCD smoothed glyphs. However, the correct outset
1025 // is not currently known, as CG dilates the outlines by some percentage.
1026 // Note that if this context is A8 and not back-forming from LCD, there is no need to outset.
1027 skIBounds.outset(1, 1);
1028 glyph->fLeft = SkToS16(skIBounds.fLeft);
1029 glyph->fTop = SkToS16(skIBounds.fTop);
1030 glyph->fWidth = SkToU16(skIBounds.width());
1031 glyph->fHeight = SkToU16(skIBounds.height());
bungeman@google.comcefd9812013-05-15 15:07:32 +00001032}
1033
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001034#include "SkColorPriv.h"
1035
bungemane280d062016-03-24 11:27:05 -07001036static void build_power_table(uint8_t table[]) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001037 for (int i = 0; i < 256; i++) {
1038 float x = i / 255.f;
bungemane280d062016-03-24 11:27:05 -07001039 int xx = SkScalarRoundToInt(x * x * 255);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001040 table[i] = SkToU8(xx);
1041 }
1042}
1043
1044/**
1045 * This will invert the gamma applied by CoreGraphics, so we can get linear
1046 * values.
1047 *
1048 * CoreGraphics obscurely defaults to 2.0 as the smoothing gamma value.
1049 * The color space used does not appear to affect this choice.
1050 */
1051static const uint8_t* getInverseGammaTableCoreGraphicSmoothing() {
1052 static bool gInited;
1053 static uint8_t gTableCoreGraphicsSmoothing[256];
1054 if (!gInited) {
bungemane280d062016-03-24 11:27:05 -07001055 build_power_table(gTableCoreGraphicsSmoothing);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001056 gInited = true;
1057 }
1058 return gTableCoreGraphicsSmoothing;
1059}
1060
1061static void cgpixels_to_bits(uint8_t dst[], const CGRGBPixel src[], int count) {
1062 while (count > 0) {
1063 uint8_t mask = 0;
1064 for (int i = 7; i >= 0; --i) {
bungemane280d062016-03-24 11:27:05 -07001065 mask |= ((CGRGBPixel_getAlpha(*src++) >> 7) ^ 0x1) << i;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001066 if (0 == --count) {
1067 break;
1068 }
1069 }
1070 *dst++ = mask;
1071 }
1072}
1073
1074template<bool APPLY_PREBLEND>
1075static inline uint8_t rgb_to_a8(CGRGBPixel rgb, const uint8_t* table8) {
bungemane280d062016-03-24 11:27:05 -07001076 U8CPU r = 0xFF - ((rgb >> 16) & 0xFF);
1077 U8CPU g = 0xFF - ((rgb >> 8) & 0xFF);
1078 U8CPU b = 0xFF - ((rgb >> 0) & 0xFF);
bungeman3b4b66c2015-01-08 08:33:44 -08001079 U8CPU lum = sk_apply_lut_if<APPLY_PREBLEND>(SkComputeLuminance(r, g, b), table8);
1080#if SK_SHOW_TEXT_BLIT_COVERAGE
1081 lum = SkTMax(lum, (U8CPU)0x30);
1082#endif
1083 return lum;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001084}
1085template<bool APPLY_PREBLEND>
1086static void rgb_to_a8(const CGRGBPixel* SK_RESTRICT cgPixels, size_t cgRowBytes,
1087 const SkGlyph& glyph, const uint8_t* table8) {
1088 const int width = glyph.fWidth;
1089 size_t dstRB = glyph.rowBytes();
1090 uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage;
1091
1092 for (int y = 0; y < glyph.fHeight; y++) {
1093 for (int i = 0; i < width; ++i) {
1094 dst[i] = rgb_to_a8<APPLY_PREBLEND>(cgPixels[i], table8);
1095 }
bungemanc292b5f2016-12-20 12:04:29 -05001096 cgPixels = SkTAddOffset<const CGRGBPixel>(cgPixels, cgRowBytes);
1097 dst = SkTAddOffset<uint8_t>(dst, dstRB);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001098 }
1099}
1100
1101template<bool APPLY_PREBLEND>
1102static inline uint16_t rgb_to_lcd16(CGRGBPixel rgb, const uint8_t* tableR,
1103 const uint8_t* tableG,
1104 const uint8_t* tableB) {
bungemane280d062016-03-24 11:27:05 -07001105 U8CPU r = sk_apply_lut_if<APPLY_PREBLEND>(0xFF - ((rgb >> 16) & 0xFF), tableR);
1106 U8CPU g = sk_apply_lut_if<APPLY_PREBLEND>(0xFF - ((rgb >> 8) & 0xFF), tableG);
1107 U8CPU b = sk_apply_lut_if<APPLY_PREBLEND>(0xFF - ((rgb >> 0) & 0xFF), tableB);
bungeman3b4b66c2015-01-08 08:33:44 -08001108#if SK_SHOW_TEXT_BLIT_COVERAGE
1109 r = SkTMax(r, (U8CPU)0x30);
1110 g = SkTMax(g, (U8CPU)0x30);
1111 b = SkTMax(b, (U8CPU)0x30);
1112#endif
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001113 return SkPack888ToRGB16(r, g, b);
1114}
1115template<bool APPLY_PREBLEND>
1116static void rgb_to_lcd16(const CGRGBPixel* SK_RESTRICT cgPixels, size_t cgRowBytes, const SkGlyph& glyph,
1117 const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) {
1118 const int width = glyph.fWidth;
1119 size_t dstRB = glyph.rowBytes();
1120 uint16_t* SK_RESTRICT dst = (uint16_t*)glyph.fImage;
1121
1122 for (int y = 0; y < glyph.fHeight; y++) {
1123 for (int i = 0; i < width; i++) {
1124 dst[i] = rgb_to_lcd16<APPLY_PREBLEND>(cgPixels[i], tableR, tableG, tableB);
1125 }
bungemanc292b5f2016-12-20 12:04:29 -05001126 cgPixels = SkTAddOffset<const CGRGBPixel>(cgPixels, cgRowBytes);
1127 dst = SkTAddOffset<uint16_t>(dst, dstRB);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001128 }
1129}
1130
bungeman34902632014-12-10 21:43:27 -08001131static SkPMColor cgpixels_to_pmcolor(CGRGBPixel rgb) {
1132 U8CPU a = (rgb >> 24) & 0xFF;
reed@google.comf77b35d2013-05-02 20:39:44 +00001133 U8CPU r = (rgb >> 16) & 0xFF;
1134 U8CPU g = (rgb >> 8) & 0xFF;
1135 U8CPU b = (rgb >> 0) & 0xFF;
bungeman3b4b66c2015-01-08 08:33:44 -08001136#if SK_SHOW_TEXT_BLIT_COVERAGE
1137 a = SkTMax(a, (U8CPU)0x30);
1138#endif
bungeman34902632014-12-10 21:43:27 -08001139 return SkPackARGB32(a, r, g, b);
reed@google.comf77b35d2013-05-02 20:39:44 +00001140}
reed@google.comf77b35d2013-05-02 20:39:44 +00001141
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001142void SkScalerContext_Mac::generateImage(const SkGlyph& glyph) {
bungemanc292b5f2016-12-20 12:04:29 -05001143 CGGlyph cgGlyph = SkTo<CGGlyph>(glyph.getGlyphID());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001144
1145 // FIXME: lcd smoothed un-hinted rasterization unsupported.
1146 bool generateA8FromLCD = fRec.getHinting() != SkPaint::kNo_Hinting;
1147
1148 // Draw the glyph
1149 size_t cgRowBytes;
1150 CGRGBPixel* cgPixels = fOffscreen.getCG(*this, glyph, cgGlyph, &cgRowBytes, generateA8FromLCD);
halcanary96fcdcc2015-08-27 07:41:13 -07001151 if (cgPixels == nullptr) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001152 return;
1153 }
1154
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001155 // Fix the glyph
bungemanc292b5f2016-12-20 12:04:29 -05001156 if ((glyph.fMaskFormat == SkMask::kLCD16_Format) ||
1157 (glyph.fMaskFormat == SkMask::kA8_Format && supports_LCD() && generateA8FromLCD))
1158 {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001159 const uint8_t* table = getInverseGammaTableCoreGraphicSmoothing();
1160
1161 //Note that the following cannot really be integrated into the
1162 //pre-blend, since we may not be applying the pre-blend; when we aren't
1163 //applying the pre-blend it means that a filter wants linear anyway.
1164 //Other code may also be applying the pre-blend, so we'd need another
1165 //one with this and one without.
1166 CGRGBPixel* addr = cgPixels;
1167 for (int y = 0; y < glyph.fHeight; ++y) {
1168 for (int x = 0; x < glyph.fWidth; ++x) {
1169 int r = (addr[x] >> 16) & 0xFF;
1170 int g = (addr[x] >> 8) & 0xFF;
1171 int b = (addr[x] >> 0) & 0xFF;
1172 addr[x] = (table[r] << 16) | (table[g] << 8) | table[b];
1173 }
bungemane280d062016-03-24 11:27:05 -07001174 addr = SkTAddOffset<CGRGBPixel>(addr, cgRowBytes);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001175 }
1176 }
1177
1178 // Convert glyph to mask
1179 switch (glyph.fMaskFormat) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001180 case SkMask::kLCD16_Format: {
1181 if (fPreBlend.isApplicable()) {
1182 rgb_to_lcd16<true>(cgPixels, cgRowBytes, glyph,
1183 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1184 } else {
1185 rgb_to_lcd16<false>(cgPixels, cgRowBytes, glyph,
1186 fPreBlend.fR, fPreBlend.fG, fPreBlend.fB);
1187 }
1188 } break;
1189 case SkMask::kA8_Format: {
1190 if (fPreBlend.isApplicable()) {
1191 rgb_to_a8<true>(cgPixels, cgRowBytes, glyph, fPreBlend.fG);
1192 } else {
1193 rgb_to_a8<false>(cgPixels, cgRowBytes, glyph, fPreBlend.fG);
1194 }
1195 } break;
1196 case SkMask::kBW_Format: {
1197 const int width = glyph.fWidth;
1198 size_t dstRB = glyph.rowBytes();
1199 uint8_t* dst = (uint8_t*)glyph.fImage;
1200 for (int y = 0; y < glyph.fHeight; y++) {
1201 cgpixels_to_bits(dst, cgPixels, width);
bungemanc292b5f2016-12-20 12:04:29 -05001202 cgPixels = SkTAddOffset<CGRGBPixel>(cgPixels, cgRowBytes);
1203 dst = SkTAddOffset<uint8_t>(dst, dstRB);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001204 }
1205 } break;
reed@google.comf77b35d2013-05-02 20:39:44 +00001206 case SkMask::kARGB32_Format: {
1207 const int width = glyph.fWidth;
1208 size_t dstRB = glyph.rowBytes();
1209 SkPMColor* dst = (SkPMColor*)glyph.fImage;
1210 for (int y = 0; y < glyph.fHeight; y++) {
1211 for (int x = 0; x < width; ++x) {
bungeman34902632014-12-10 21:43:27 -08001212 dst[x] = cgpixels_to_pmcolor(cgPixels[x]);
reed@google.comf77b35d2013-05-02 20:39:44 +00001213 }
bungemanc292b5f2016-12-20 12:04:29 -05001214 cgPixels = SkTAddOffset<CGRGBPixel>(cgPixels, cgRowBytes);
1215 dst = SkTAddOffset<SkPMColor>(dst, dstRB);
reed@google.comf77b35d2013-05-02 20:39:44 +00001216 }
1217 } break;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001218 default:
1219 SkDEBUGFAIL("unexpected mask format");
1220 break;
1221 }
1222}
1223
1224/*
1225 * Our subpixel resolution is only 2 bits in each direction, so a scale of 4
1226 * seems sufficient, and possibly even correct, to allow the hinted outline
1227 * to be subpixel positioned.
1228 */
1229#define kScaleForSubPixelPositionHinting (4.0f)
1230
Ben Wagner6e9ac122016-11-11 14:31:06 -05001231void SkScalerContext_Mac::generatePath(SkGlyphID glyph, SkPath* path) {
reedd0f41732015-07-10 12:08:38 -07001232 AUTO_CG_LOCK();
1233
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001234 SkScalar scaleX = SK_Scalar1;
1235 SkScalar scaleY = SK_Scalar1;
1236
bungemanef27ce32015-10-29 09:30:32 -07001237 CGAffineTransform xform = fTransform;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001238 /*
1239 * For subpixel positioning, we want to return an unhinted outline, so it
1240 * can be positioned nicely at fractional offsets. However, we special-case
1241 * if the baseline of the (horizontal) text is axis-aligned. In those cases
1242 * we want to retain hinting in the direction orthogonal to the baseline.
1243 * e.g. for horizontal baseline, we want to retain hinting in Y.
1244 * The way we remove hinting is to scale the font by some value (4) in that
1245 * direction, ask for the path, and then scale the path back down.
1246 */
bungeman7cbeaae2015-09-22 09:54:56 -07001247 if (fDoSubPosition) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001248 // start out by assuming that we want no hining in X and Y
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +00001249 scaleX = scaleY = kScaleForSubPixelPositionHinting;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001250 // now see if we need to restore hinting for axis-aligned baselines
bungeman27876bc2016-02-29 11:22:55 -08001251 switch (this->computeAxisAlignmentForHText()) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001252 case kX_SkAxisAlignment:
1253 scaleY = SK_Scalar1; // want hinting in the Y direction
1254 break;
1255 case kY_SkAxisAlignment:
1256 scaleX = SK_Scalar1; // want hinting in the X direction
1257 break;
1258 default:
1259 break;
1260 }
1261
bungemanef27ce32015-10-29 09:30:32 -07001262 CGAffineTransform scale(CGAffineTransformMakeScale(ScalarToCG(scaleX), ScalarToCG(scaleY)));
1263 xform = CGAffineTransformConcat(fTransform, scale);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001264 }
1265
Ben Wagner6e9ac122016-11-11 14:31:06 -05001266 CGGlyph cgGlyph = SkTo<CGGlyph>(glyph);
bungemanc292b5f2016-12-20 12:04:29 -05001267 UniqueCFRef<CGPathRef> cgPath(CTFontCreatePathForGlyph(fCTFont.get(), cgGlyph, &xform));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001268
1269 path->reset();
halcanary96fcdcc2015-08-27 07:41:13 -07001270 if (cgPath != nullptr) {
bungemanc292b5f2016-12-20 12:04:29 -05001271 CGPathApply(cgPath.get(), path, SkScalerContext_Mac::CTPathElement);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001272 }
1273
bungeman@google.comcefd9812013-05-15 15:07:32 +00001274 if (fDoSubPosition) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001275 SkMatrix m;
1276 m.setScale(SkScalarInvert(scaleX), SkScalarInvert(scaleY));
1277 path->transform(m);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001278 }
bungeman@google.comcefd9812013-05-15 15:07:32 +00001279 if (fVertical) {
bungeman@google.comcefd9812013-05-15 15:07:32 +00001280 SkPoint offset;
1281 getVerticalOffset(cgGlyph, &offset);
1282 path->offset(offset.fX, offset.fY);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001283 }
1284}
1285
bungeman41078062014-07-07 08:16:37 -07001286void SkScalerContext_Mac::generateFontMetrics(SkPaint::FontMetrics* metrics) {
halcanary96fcdcc2015-08-27 07:41:13 -07001287 if (nullptr == metrics) {
bungeman41078062014-07-07 08:16:37 -07001288 return;
1289 }
1290
reedd0f41732015-07-10 12:08:38 -07001291 AUTO_CG_LOCK();
1292
bungemanc292b5f2016-12-20 12:04:29 -05001293 CGRect theBounds = CTFontGetBoundingBox(fCTFont.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001294
bungeman41078062014-07-07 08:16:37 -07001295 metrics->fTop = CGToScalar(-CGRectGetMaxY_inline(theBounds));
bungemanc292b5f2016-12-20 12:04:29 -05001296 metrics->fAscent = CGToScalar(-CTFontGetAscent(fCTFont.get()));
1297 metrics->fDescent = CGToScalar( CTFontGetDescent(fCTFont.get()));
bungeman41078062014-07-07 08:16:37 -07001298 metrics->fBottom = CGToScalar(-CGRectGetMinY_inline(theBounds));
bungemanc292b5f2016-12-20 12:04:29 -05001299 metrics->fLeading = CGToScalar( CTFontGetLeading(fCTFont.get()));
bungeman41078062014-07-07 08:16:37 -07001300 metrics->fAvgCharWidth = CGToScalar( CGRectGetWidth_inline(theBounds));
1301 metrics->fXMin = CGToScalar( CGRectGetMinX_inline(theBounds));
1302 metrics->fXMax = CGToScalar( CGRectGetMaxX_inline(theBounds));
bungeman6bd8d1c2015-06-09 08:40:51 -07001303 metrics->fMaxCharWidth = metrics->fXMax - metrics->fXMin;
bungemanc292b5f2016-12-20 12:04:29 -05001304 metrics->fXHeight = CGToScalar( CTFontGetXHeight(fCTFont.get()));
1305 metrics->fCapHeight = CGToScalar( CTFontGetCapHeight(fCTFont.get()));
1306 metrics->fUnderlineThickness = CGToScalar( CTFontGetUnderlineThickness(fCTFont.get()));
1307 metrics->fUnderlinePosition = -CGToScalar( CTFontGetUnderlinePosition(fCTFont.get()));
commit-bot@chromium.org0bc406d2014-03-01 20:12:26 +00001308
bungeman41078062014-07-07 08:16:37 -07001309 metrics->fFlags |= SkPaint::FontMetrics::kUnderlineThinknessIsValid_Flag;
1310 metrics->fFlags |= SkPaint::FontMetrics::kUnderlinePositionIsValid_Flag;
bungeman4ec46aa2017-02-15 17:49:12 -05001311
1312 // See https://bugs.chromium.org/p/skia/issues/detail?id=6203
1313 // At least on 10.12.3 with memory based fonts the x-height is always 0.6666 of the ascent and
1314 // the cap-height is always 0.8888 of the ascent. It appears that the values from the 'OS/2'
1315 // table are read, but then overwritten if the font is not a system font. As a result, if there
1316 // is a valid 'OS/2' table available use the values from the table if they aren't too strange.
1317 struct OS2HeightMetrics {
1318 SK_OT_SHORT sxHeight;
1319 SK_OT_SHORT sCapHeight;
1320 } heights;
1321 size_t bytesRead = this->getTypeface()->getTableData(
1322 SkTEndian_SwapBE32(SkOTTableOS2::TAG), offsetof(SkOTTableOS2, version.v2.sxHeight),
1323 sizeof(heights), &heights);
1324 if (bytesRead == sizeof(heights)) {
1325 // 'fontSize' is correct because the entire resolved size is set by the constructor.
1326 CGFloat fontSize = CTFontGetSize(this->fCTFont.get());
1327 unsigned upem = CTFontGetUnitsPerEm(this->fCTFont.get());
1328 unsigned maxSaneHeight = upem * 2;
1329 uint16_t xHeight = SkEndian_SwapBE16(heights.sxHeight);
1330 if (xHeight && xHeight < maxSaneHeight) {
1331 metrics->fXHeight = CGToScalar(xHeight * fontSize / upem);
1332 }
1333 uint16_t capHeight = SkEndian_SwapBE16(heights.sCapHeight);
1334 if (capHeight && capHeight < maxSaneHeight) {
1335 metrics->fCapHeight = CGToScalar(capHeight * fontSize / upem);
1336 }
1337 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001338}
1339
1340void SkScalerContext_Mac::CTPathElement(void *info, const CGPathElement *element) {
1341 SkPath* skPath = (SkPath*)info;
1342
1343 // Process the path element
1344 switch (element->type) {
1345 case kCGPathElementMoveToPoint:
1346 skPath->moveTo(element->points[0].x, -element->points[0].y);
1347 break;
1348
1349 case kCGPathElementAddLineToPoint:
1350 skPath->lineTo(element->points[0].x, -element->points[0].y);
1351 break;
1352
1353 case kCGPathElementAddQuadCurveToPoint:
1354 skPath->quadTo(element->points[0].x, -element->points[0].y,
1355 element->points[1].x, -element->points[1].y);
1356 break;
1357
1358 case kCGPathElementAddCurveToPoint:
1359 skPath->cubicTo(element->points[0].x, -element->points[0].y,
1360 element->points[1].x, -element->points[1].y,
1361 element->points[2].x, -element->points[2].y);
1362 break;
1363
1364 case kCGPathElementCloseSubpath:
1365 skPath->close();
1366 break;
1367
1368 default:
1369 SkDEBUGFAIL("Unknown path element!");
1370 break;
1371 }
1372}
1373
1374
1375///////////////////////////////////////////////////////////////////////////////
1376
halcanary96fcdcc2015-08-27 07:41:13 -07001377// Returns nullptr on failure
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001378// Call must still manage its ownership of provider
Ben Wagnerfc497342017-02-24 11:15:26 -05001379static SkTypeface* create_from_dataProvider(UniqueCFRef<CGDataProviderRef> provider, int ttcIndex) {
1380 if (ttcIndex != 0) {
1381 return nullptr;
1382 }
bungemanc292b5f2016-12-20 12:04:29 -05001383 UniqueCFRef<CGFontRef> cg(CGFontCreateWithDataProvider(provider.get()));
1384 if (!cg) {
halcanary96fcdcc2015-08-27 07:41:13 -07001385 return nullptr;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001386 }
bungemanc292b5f2016-12-20 12:04:29 -05001387 UniqueCFRef<CTFontRef> ct(CTFontCreateWithGraphicsFont(cg.get(), 0, nullptr, nullptr));
1388 if (!ct) {
1389 return nullptr;
1390 }
1391 return create_from_CTFontRef(std::move(ct), nullptr, true);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001392}
1393
bungemanc292b5f2016-12-20 12:04:29 -05001394// Web fonts added to the CTFont registry do not return their character set.
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001395// Iterate through the font in this case. The existing caller caches the result,
1396// so the performance impact isn't too bad.
1397static void populate_glyph_to_unicode_slow(CTFontRef ctFont, CFIndex glyphCount,
1398 SkTDArray<SkUnichar>* glyphToUnicode) {
reed@google.com7fa2a652014-01-27 13:42:58 +00001399 glyphToUnicode->setCount(SkToInt(glyphCount));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001400 SkUnichar* out = glyphToUnicode->begin();
1401 sk_bzero(out, glyphCount * sizeof(SkUnichar));
1402 UniChar unichar = 0;
1403 while (glyphCount > 0) {
1404 CGGlyph glyph;
1405 if (CTFontGetGlyphsForCharacters(ctFont, &unichar, &glyph, 1)) {
1406 out[glyph] = unichar;
1407 --glyphCount;
1408 }
1409 if (++unichar == 0) {
1410 break;
1411 }
1412 }
1413}
1414
1415// Construct Glyph to Unicode table.
1416// Unicode code points that require conjugate pairs in utf16 are not
1417// supported.
1418static void populate_glyph_to_unicode(CTFontRef ctFont, CFIndex glyphCount,
1419 SkTDArray<SkUnichar>* glyphToUnicode) {
bungemanc292b5f2016-12-20 12:04:29 -05001420 UniqueCFRef<CFCharacterSetRef> charSet(CTFontCopyCharacterSet(ctFont));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001421 if (!charSet) {
1422 populate_glyph_to_unicode_slow(ctFont, glyphCount, glyphToUnicode);
1423 return;
1424 }
1425
bungemanc292b5f2016-12-20 12:04:29 -05001426 UniqueCFRef<CFDataRef> bitmap(CFCharacterSetCreateBitmapRepresentation(nullptr, charSet.get()));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001427 if (!bitmap) {
1428 return;
1429 }
bungemanc292b5f2016-12-20 12:04:29 -05001430 CFIndex length = CFDataGetLength(bitmap.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001431 if (!length) {
1432 return;
1433 }
1434 if (length > 8192) {
1435 // TODO: Add support for Unicode above 0xFFFF
1436 // Consider only the BMP portion of the Unicode character points.
1437 // The bitmap may contain other planes, up to plane 16.
1438 // See http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFCharacterSetRef/Reference/reference.html
1439 length = 8192;
1440 }
bungemanc292b5f2016-12-20 12:04:29 -05001441 const UInt8* bits = CFDataGetBytePtr(bitmap.get());
reed@google.com7fa2a652014-01-27 13:42:58 +00001442 glyphToUnicode->setCount(SkToInt(glyphCount));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001443 SkUnichar* out = glyphToUnicode->begin();
1444 sk_bzero(out, glyphCount * sizeof(SkUnichar));
1445 for (int i = 0; i < length; i++) {
1446 int mask = bits[i];
1447 if (!mask) {
1448 continue;
1449 }
1450 for (int j = 0; j < 8; j++) {
1451 CGGlyph glyph;
1452 UniChar unichar = static_cast<UniChar>((i << 3) + j);
1453 if (mask & (1 << j) && CTFontGetGlyphsForCharacters(ctFont, &unichar, &glyph, 1)) {
1454 out[glyph] = unichar;
1455 }
1456 }
1457 }
1458}
1459
halcanary96fcdcc2015-08-27 07:41:13 -07001460/** Assumes src and dst are not nullptr. */
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001461static void CFStringToSkString(CFStringRef src, SkString* dst) {
1462 // Reserve enough room for the worst-case string,
1463 // plus 1 byte for the trailing null.
1464 CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(src),
1465 kCFStringEncodingUTF8) + 1;
1466 dst->resize(length);
1467 CFStringGetCString(src, dst->writable_str(), length, kCFStringEncodingUTF8);
1468 // Resize to the actual UTF-8 length used, stripping the null character.
1469 dst->resize(strlen(dst->c_str()));
1470}
1471
reed@google.com2689f612013-03-20 20:01:47 +00001472SkAdvancedTypefaceMetrics* SkTypeface_Mac::onGetAdvancedTypefaceMetrics(
reed39a9a502015-05-12 09:50:04 -07001473 PerGlyphInfo perGlyphInfo,
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001474 const uint32_t* glyphIDs,
reed@google.com2689f612013-03-20 20:01:47 +00001475 uint32_t glyphIDsCount) const {
1476
reedd0f41732015-07-10 12:08:38 -07001477 AUTO_CG_LOCK();
1478
bungemanc292b5f2016-12-20 12:04:29 -05001479 UniqueCFRef<CTFontRef> ctFont =
1480 ctfont_create_exact_copy(fFontRef.get(), CTFontGetUnitsPerEm(fFontRef.get()), nullptr);
bungeman7cbeaae2015-09-22 09:54:56 -07001481
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001482 SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics;
1483
1484 {
bungemanc292b5f2016-12-20 12:04:29 -05001485 UniqueCFRef<CFStringRef> fontName(CTFontCopyPostScriptName(ctFont.get()));
bungeman256b3512014-07-02 07:57:59 -07001486 if (fontName.get()) {
bungemanc292b5f2016-12-20 12:04:29 -05001487 CFStringToSkString(fontName.get(), &info->fFontName);
bungeman256b3512014-07-02 07:57:59 -07001488 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001489 }
1490
Ben Wagnerc6639052017-03-02 13:31:16 -05001491 // In 10.10 and earlier, CTFontCopyVariationAxes and CTFontCopyVariation do not work when
1492 // applied to fonts which started life with CGFontCreateWithDataProvider (they simply always
1493 // return nullptr). As a result, we are limited to CGFontCopyVariationAxes and
1494 // CGFontCopyVariations here until support for 10.10 and earlier is removed.
1495 UniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(ctFont.get(), nullptr));
1496 if (cgFont) {
1497 UniqueCFRef<CFArrayRef> cgAxes(CGFontCopyVariationAxes(cgFont.get()));
1498 if (cgAxes && CFArrayGetCount(cgAxes.get()) > 0) {
1499 info->fFlags |= SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag;
1500 }
1501 }
1502
bungemanc292b5f2016-12-20 12:04:29 -05001503 CFIndex glyphCount = CTFontGetGlyphCount(ctFont.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001504
reed39a9a502015-05-12 09:50:04 -07001505 if (perGlyphInfo & kToUnicode_PerGlyphInfo) {
bungemanc292b5f2016-12-20 12:04:29 -05001506 populate_glyph_to_unicode(ctFont.get(), glyphCount, &info->fGlyphToUnicode);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001507 }
1508
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001509 // If it's not a truetype font, mark it as 'other'. Assume that TrueType
1510 // fonts always have both glyf and loca tables. At the least, this is what
1511 // sfntly needs to subset the font. CTFontCopyAttribute() does not always
1512 // succeed in determining this directly.
reed@google.com2689f612013-03-20 20:01:47 +00001513 if (!this->getTableSize('glyf') || !this->getTableSize('loca')) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001514 return info;
1515 }
1516
1517 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
bungemanc292b5f2016-12-20 12:04:29 -05001518 CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(ctFont.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001519 if (symbolicTraits & kCTFontMonoSpaceTrait) {
1520 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
1521 }
1522 if (symbolicTraits & kCTFontItalicTrait) {
1523 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
1524 }
1525 CTFontStylisticClass stylisticClass = symbolicTraits & kCTFontClassMaskTrait;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001526 if (stylisticClass >= kCTFontOldStyleSerifsClass && stylisticClass <= kCTFontSlabSerifsClass) {
1527 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
1528 } else if (stylisticClass & kCTFontScriptsClass) {
1529 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
1530 }
bungemanc292b5f2016-12-20 12:04:29 -05001531 info->fItalicAngle = (int16_t) CTFontGetSlantAngle(ctFont.get());
1532 info->fAscent = (int16_t) CTFontGetAscent(ctFont.get());
1533 info->fDescent = (int16_t) CTFontGetDescent(ctFont.get());
1534 info->fCapHeight = (int16_t) CTFontGetCapHeight(ctFont.get());
1535 CGRect bbox = CTFontGetBoundingBox(ctFont.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001536
1537 SkRect r;
1538 r.set( CGToScalar(CGRectGetMinX_inline(bbox)), // Left
1539 CGToScalar(CGRectGetMaxY_inline(bbox)), // Top
1540 CGToScalar(CGRectGetMaxX_inline(bbox)), // Right
1541 CGToScalar(CGRectGetMinY_inline(bbox))); // Bottom
1542
1543 r.roundOut(&(info->fBBox));
1544
1545 // Figure out a good guess for StemV - Min width of i, I, !, 1.
1546 // This probably isn't very good with an italic font.
1547 int16_t min_width = SHRT_MAX;
1548 info->fStemV = 0;
1549 static const UniChar stem_chars[] = {'i', 'I', '!', '1'};
1550 const size_t count = sizeof(stem_chars) / sizeof(stem_chars[0]);
1551 CGGlyph glyphs[count];
1552 CGRect boundingRects[count];
bungemanc292b5f2016-12-20 12:04:29 -05001553 if (CTFontGetGlyphsForCharacters(ctFont.get(), stem_chars, glyphs, count)) {
bungeman18ec7b92017-02-09 17:15:59 -05001554 CTFontGetBoundingRectsForGlyphs(ctFont.get(), kCTFontOrientationHorizontal,
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001555 glyphs, boundingRects, count);
1556 for (size_t i = 0; i < count; i++) {
1557 int16_t width = (int16_t) boundingRects[i].size.width;
1558 if (width > 0 && width < min_width) {
1559 min_width = width;
1560 info->fStemV = min_width;
1561 }
1562 }
1563 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001564 return info;
1565}
1566
1567///////////////////////////////////////////////////////////////////////////////
1568
reed@google.comcc9aad52013-03-21 19:28:10 +00001569static SK_SFNT_ULONG get_font_type_tag(const SkTypeface_Mac* typeface) {
1570 CTFontRef ctFont = typeface->fFontRef.get();
bungemanc292b5f2016-12-20 12:04:29 -05001571 UniqueCFRef<CFNumberRef> fontFormatRef(
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001572 static_cast<CFNumberRef>(CTFontCopyAttribute(ctFont, kCTFontFormatAttribute)));
1573 if (!fontFormatRef) {
1574 return 0;
1575 }
1576
1577 SInt32 fontFormatValue;
bungemanc292b5f2016-12-20 12:04:29 -05001578 if (!CFNumberGetValue(fontFormatRef.get(), kCFNumberSInt32Type, &fontFormatValue)) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001579 return 0;
1580 }
1581
1582 switch (fontFormatValue) {
1583 case kCTFontFormatOpenTypePostScript:
1584 return SkSFNTHeader::fontType_OpenTypeCFF::TAG;
1585 case kCTFontFormatOpenTypeTrueType:
1586 return SkSFNTHeader::fontType_WindowsTrueType::TAG;
1587 case kCTFontFormatTrueType:
1588 return SkSFNTHeader::fontType_MacTrueType::TAG;
1589 case kCTFontFormatPostScript:
1590 return SkSFNTHeader::fontType_PostScript::TAG;
1591 case kCTFontFormatBitmap:
1592 return SkSFNTHeader::fontType_MacTrueType::TAG;
1593 case kCTFontFormatUnrecognized:
1594 default:
1595 //CT seems to be unreliable in being able to obtain the type,
1596 //even if all we want is the first four bytes of the font resource.
1597 //Just the presence of the FontForge 'FFTM' table seems to throw it off.
1598 return SkSFNTHeader::fontType_WindowsTrueType::TAG;
1599 }
1600}
1601
bungeman5f213d92015-01-27 05:39:10 -08001602SkStreamAsset* SkTypeface_Mac::onOpenStream(int* ttcIndex) const {
reed@google.comcc9aad52013-03-21 19:28:10 +00001603 SK_SFNT_ULONG fontType = get_font_type_tag(this);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001604 if (0 == fontType) {
halcanary96fcdcc2015-08-27 07:41:13 -07001605 return nullptr;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001606 }
1607
1608 // get table tags
reed@google.comcc9aad52013-03-21 19:28:10 +00001609 int numTables = this->countTables();
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001610 SkTDArray<SkFontTableTag> tableTags;
1611 tableTags.setCount(numTables);
reed@google.comcc9aad52013-03-21 19:28:10 +00001612 this->getTableTags(tableTags.begin());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001613
1614 // calc total size for font, save sizes
1615 SkTDArray<size_t> tableSizes;
1616 size_t totalSize = sizeof(SkSFNTHeader) + sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
1617 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
reed@google.comcc9aad52013-03-21 19:28:10 +00001618 size_t tableSize = this->getTableSize(tableTags[tableIndex]);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001619 totalSize += (tableSize + 3) & ~3;
1620 *tableSizes.append() = tableSize;
1621 }
1622
1623 // reserve memory for stream, and zero it (tables must be zero padded)
1624 SkMemoryStream* stream = new SkMemoryStream(totalSize);
1625 char* dataStart = (char*)stream->getMemoryBase();
1626 sk_bzero(dataStart, totalSize);
1627 char* dataPtr = dataStart;
1628
1629 // compute font header entries
1630 uint16_t entrySelector = 0;
1631 uint16_t searchRange = 1;
1632 while (searchRange < numTables >> 1) {
1633 entrySelector++;
1634 searchRange <<= 1;
1635 }
1636 searchRange <<= 4;
1637 uint16_t rangeShift = (numTables << 4) - searchRange;
1638
1639 // write font header
1640 SkSFNTHeader* header = (SkSFNTHeader*)dataPtr;
1641 header->fontType = fontType;
1642 header->numTables = SkEndian_SwapBE16(numTables);
1643 header->searchRange = SkEndian_SwapBE16(searchRange);
1644 header->entrySelector = SkEndian_SwapBE16(entrySelector);
1645 header->rangeShift = SkEndian_SwapBE16(rangeShift);
1646 dataPtr += sizeof(SkSFNTHeader);
1647
1648 // write tables
1649 SkSFNTHeader::TableDirectoryEntry* entry = (SkSFNTHeader::TableDirectoryEntry*)dataPtr;
1650 dataPtr += sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
1651 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
1652 size_t tableSize = tableSizes[tableIndex];
reed@google.comcc9aad52013-03-21 19:28:10 +00001653 this->getTableData(tableTags[tableIndex], 0, tableSize, dataPtr);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001654 entry->tag = SkEndian_SwapBE32(tableTags[tableIndex]);
1655 entry->checksum = SkEndian_SwapBE32(SkOTUtils::CalcTableChecksum((SK_OT_ULONG*)dataPtr,
1656 tableSize));
reed@google.com7fa2a652014-01-27 13:42:58 +00001657 entry->offset = SkEndian_SwapBE32(SkToU32(dataPtr - dataStart));
1658 entry->logicalLength = SkEndian_SwapBE32(SkToU32(tableSize));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001659
1660 dataPtr += (tableSize + 3) & ~3;
1661 ++entry;
1662 }
1663
bungemanb3310c22015-03-02 09:05:36 -08001664 *ttcIndex = 0;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001665 return stream;
1666}
1667
bungeman41868fe2015-05-20 09:21:04 -07001668struct NonDefaultAxesContext {
1669 SkFixed* axisValue;
1670 CFArrayRef cgAxes;
1671};
1672static void set_non_default_axes(CFTypeRef key, CFTypeRef value, void* context) {
1673 NonDefaultAxesContext* self = static_cast<NonDefaultAxesContext*>(context);
1674
1675 if (CFGetTypeID(key) != CFStringGetTypeID() || CFGetTypeID(value) != CFNumberGetTypeID()) {
1676 return;
1677 }
1678
1679 // The key is a CFString which is a string from the 'name' table.
1680 // Search the cgAxes for an axis with this name, and use its index to store the value.
1681 CFIndex keyIndex = -1;
1682 CFStringRef keyString = static_cast<CFStringRef>(key);
1683 for (CFIndex i = 0; i < CFArrayGetCount(self->cgAxes); ++i) {
1684 CFTypeRef cgAxis = CFArrayGetValueAtIndex(self->cgAxes, i);
1685 if (CFGetTypeID(cgAxis) != CFDictionaryGetTypeID()) {
1686 continue;
1687 }
1688
1689 CFDictionaryRef cgAxisDict = static_cast<CFDictionaryRef>(cgAxis);
1690 CFTypeRef cgAxisName = CFDictionaryGetValue(cgAxisDict, kCGFontVariationAxisName);
1691 if (!cgAxisName || CFGetTypeID(cgAxisName) != CFStringGetTypeID()) {
1692 continue;
1693 }
1694 CFStringRef cgAxisNameString = static_cast<CFStringRef>(cgAxisName);
1695 if (CFStringCompare(keyString, cgAxisNameString, 0) == kCFCompareEqualTo) {
1696 keyIndex = i;
1697 break;
1698 }
1699 }
1700 if (keyIndex == -1) {
1701 return;
1702 }
1703
1704 CFNumberRef valueNumber = static_cast<CFNumberRef>(value);
1705 double valueDouble;
1706 if (!CFNumberGetValue(valueNumber, kCFNumberDoubleType, &valueDouble) ||
1707 valueDouble < SkFixedToDouble(SK_FixedMin) || SkFixedToDouble(SK_FixedMax) < valueDouble)
1708 {
1709 return;
1710 }
1711 self->axisValue[keyIndex] = SkDoubleToFixed(valueDouble);
1712}
Ben Wagnerfc497342017-02-24 11:15:26 -05001713static bool get_variations(CTFontRef ctFont, CFIndex* cgAxisCount,
bungeman41868fe2015-05-20 09:21:04 -07001714 SkAutoSTMalloc<4, SkFixed>* axisValues)
1715{
Ben Wagnerfc497342017-02-24 11:15:26 -05001716 // In 10.10 and earlier, CTFontCopyVariationAxes and CTFontCopyVariation do not work when
1717 // applied to fonts which started life with CGFontCreateWithDataProvider (they simply always
1718 // return nullptr). As a result, we are limited to CGFontCopyVariationAxes and
1719 // CGFontCopyVariations here until support for 10.10 and earlier is removed.
1720 UniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(ctFont, nullptr));
bungemanc292b5f2016-12-20 12:04:29 -05001721 if (!cgFont) {
bungeman41868fe2015-05-20 09:21:04 -07001722 return false;
1723 }
1724
bungemanc292b5f2016-12-20 12:04:29 -05001725 UniqueCFRef<CFDictionaryRef> cgVariations(CGFontCopyVariations(cgFont.get()));
1726 // If a font has no variations CGFontCopyVariations returns nullptr (instead of an empty dict).
1727 if (!cgVariations) {
1728 return false;
1729 }
1730
1731 UniqueCFRef<CFArrayRef> cgAxes(CGFontCopyVariationAxes(cgFont.get()));
1732 if (!cgAxes) {
1733 return false;
1734 }
1735 *cgAxisCount = CFArrayGetCount(cgAxes.get());
bungeman41868fe2015-05-20 09:21:04 -07001736 axisValues->reset(*cgAxisCount);
1737
1738 // Set all of the axes to their default values.
1739 // Fail if any default value cannot be determined.
1740 for (CFIndex i = 0; i < *cgAxisCount; ++i) {
bungemanc292b5f2016-12-20 12:04:29 -05001741 CFTypeRef cgAxis = CFArrayGetValueAtIndex(cgAxes.get(), i);
bungeman41868fe2015-05-20 09:21:04 -07001742 if (CFGetTypeID(cgAxis) != CFDictionaryGetTypeID()) {
1743 return false;
1744 }
1745
1746 CFDictionaryRef cgAxisDict = static_cast<CFDictionaryRef>(cgAxis);
1747 CFTypeRef axisDefaultValue = CFDictionaryGetValue(cgAxisDict,
1748 kCGFontVariationAxisDefaultValue);
1749 if (!axisDefaultValue || CFGetTypeID(axisDefaultValue) != CFNumberGetTypeID()) {
1750 return false;
1751 }
1752 CFNumberRef axisDefaultValueNumber = static_cast<CFNumberRef>(axisDefaultValue);
1753 double axisDefaultValueDouble;
1754 if (!CFNumberGetValue(axisDefaultValueNumber, kCFNumberDoubleType, &axisDefaultValueDouble))
1755 {
1756 return false;
1757 }
1758 if (axisDefaultValueDouble < SkFixedToDouble(SK_FixedMin) ||
1759 SkFixedToDouble(SK_FixedMax) < axisDefaultValueDouble)
1760 {
1761 return false;
1762 }
1763 (*axisValues)[(int)i] = SkDoubleToFixed(axisDefaultValueDouble);
1764 }
1765
1766 // Override the default values with the given font's stated axis values.
1767 NonDefaultAxesContext c = { axisValues->get(), cgAxes.get() };
bungemanc292b5f2016-12-20 12:04:29 -05001768 CFDictionaryApplyFunction(cgVariations.get(), set_non_default_axes, &c);
bungeman41868fe2015-05-20 09:21:04 -07001769
1770 return true;
1771}
bungemanf93d7112016-09-16 06:24:20 -07001772std::unique_ptr<SkFontData> SkTypeface_Mac::onMakeFontData() const {
bungeman41868fe2015-05-20 09:21:04 -07001773 int index;
bungemanf93d7112016-09-16 06:24:20 -07001774 std::unique_ptr<SkStreamAsset> stream(this->onOpenStream(&index));
bungeman41868fe2015-05-20 09:21:04 -07001775
1776 CFIndex cgAxisCount;
1777 SkAutoSTMalloc<4, SkFixed> axisValues;
bungemanc292b5f2016-12-20 12:04:29 -05001778 if (get_variations(fFontRef.get(), &cgAxisCount, &axisValues)) {
bungemanf93d7112016-09-16 06:24:20 -07001779 return skstd::make_unique<SkFontData>(std::move(stream), index,
1780 axisValues.get(), cgAxisCount);
bungeman41868fe2015-05-20 09:21:04 -07001781 }
bungemanf93d7112016-09-16 06:24:20 -07001782 return skstd::make_unique<SkFontData>(std::move(stream), index, nullptr, 0);
bungeman41868fe2015-05-20 09:21:04 -07001783}
1784
Ben Wagnerfc497342017-02-24 11:15:26 -05001785/** Creates a CT variation dictionary {tag, value} from a CG variation dictionary {name, value}. */
1786static UniqueCFRef<CFDictionaryRef> ct_variation_from_cg_variation(CFDictionaryRef cgVariations,
1787 CFArrayRef ctAxes) {
1788
1789 UniqueCFRef<CFMutableDictionaryRef> ctVariations(
1790 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
1791 &kCFTypeDictionaryKeyCallBacks,
1792 &kCFTypeDictionaryValueCallBacks));
1793
1794 CFIndex axisCount = CFArrayGetCount(ctAxes);
1795 for (CFIndex i = 0; i < axisCount; ++i) {
1796 CFTypeRef axisInfo = CFArrayGetValueAtIndex(ctAxes, i);
1797 if (CFDictionaryGetTypeID() != CFGetTypeID(axisInfo)) {
1798 return nullptr;
1799 }
1800 CFDictionaryRef axisInfoDict = static_cast<CFDictionaryRef>(axisInfo);
1801
1802 // The assumption is that values produced by kCTFontVariationAxisNameKey and
1803 // kCGFontVariationAxisName will always be equal.
1804 CFTypeRef axisName = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisNameKey);
1805 if (!axisName || CFGetTypeID(axisName) != CFStringGetTypeID()) {
1806 return nullptr;
1807 }
1808
1809 CFTypeRef axisValue = CFDictionaryGetValue(cgVariations, axisName);
1810 if (!axisValue || CFGetTypeID(axisValue) != CFNumberGetTypeID()) {
1811 return nullptr;
1812 }
1813
1814 CFTypeRef axisTag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
1815 if (!axisTag || CFGetTypeID(axisTag) != CFNumberGetTypeID()) {
1816 return nullptr;
1817 }
1818
1819 CFDictionaryAddValue(ctVariations.get(), axisTag, axisValue);
1820 }
1821 return std::move(ctVariations);
1822}
1823
1824int SkTypeface_Mac::onGetVariationDesignPosition(
1825 SkFontArguments::VariationPosition::Coordinate coordinates[], int coordinateCount) const
1826{
1827 // The CGFont variation data does not contain the tag.
1828
1829 // This call always returns nullptr on 10.10 and under for CGFontCreateWithDataProvider fonts.
1830 // When this happens, there is no API to provide the tag.
1831 UniqueCFRef<CFArrayRef> ctAxes(CTFontCopyVariationAxes(fFontRef.get()));
1832 if (!ctAxes) {
1833 return -1;
1834 }
1835 CFIndex axisCount = CFArrayGetCount(ctAxes.get());
1836 if (!coordinates || coordinateCount < axisCount) {
1837 return axisCount;
1838 }
1839
1840 // This call always returns nullptr on 10.11 and under for CGFontCreateWithDataProvider fonts.
1841 // When this happens, try converting the CG variation to a CT variation.
1842 // On 10.12 and later, this only returns non-default variations.
1843 UniqueCFRef<CFDictionaryRef> ctVariations(CTFontCopyVariation(fFontRef.get()));
1844 if (!ctVariations) {
1845 // When 10.11 and earlier are no longer supported, the following code can be replaced with
1846 // return -1 and ct_variation_from_cg_variation can be removed.
1847 UniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(fFontRef.get(), nullptr));
1848 if (!cgFont) {
1849 return -1;
1850 }
1851 UniqueCFRef<CFDictionaryRef> cgVariations(CGFontCopyVariations(cgFont.get()));
1852 if (!cgVariations) {
1853 return -1;
1854 }
1855 ctVariations = ct_variation_from_cg_variation(cgVariations.get(), ctAxes.get());
1856 if (!ctVariations) {
1857 return -1;
1858 }
1859 }
1860
1861 for (int i = 0; i < axisCount; ++i) {
1862 CFTypeRef axisInfo = CFArrayGetValueAtIndex(ctAxes.get(), i);
1863 if (CFDictionaryGetTypeID() != CFGetTypeID(axisInfo)) {
1864 return -1;
1865 }
1866 CFDictionaryRef axisInfoDict = static_cast<CFDictionaryRef>(axisInfo);
1867
1868 CFTypeRef tag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
1869 if (!tag || CFGetTypeID(tag) != CFNumberGetTypeID()) {
1870 return -1;
1871 }
1872 CFNumberRef tagNumber = static_cast<CFNumberRef>(tag);
1873 int64_t tagLong;
1874 if (!CFNumberGetValue(tagNumber, kCFNumberSInt64Type, &tagLong)) {
1875 return -1;
1876 }
1877 coordinates[i].axis = tagLong;
1878
1879 CGFloat variationCGFloat;
1880 CFTypeRef variationValue = CFDictionaryGetValue(ctVariations.get(), tagNumber);
1881 if (variationValue) {
1882 if (CFGetTypeID(variationValue) != CFNumberGetTypeID()) {
1883 return -1;
1884 }
1885 CFNumberRef variationNumber = static_cast<CFNumberRef>(variationValue);
1886 if (!CFNumberGetValue(variationNumber, kCFNumberCGFloatType, &variationCGFloat)) {
1887 return -1;
1888 }
1889 } else {
1890 CFTypeRef def = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisDefaultValueKey);
1891 if (!def || CFGetTypeID(def) != CFNumberGetTypeID()) {
1892 return -1;
1893 }
1894 CFNumberRef defNumber = static_cast<CFNumberRef>(def);
1895 if (!CFNumberGetValue(defNumber, kCFNumberCGFloatType, &variationCGFloat)) {
1896 return -1;
1897 }
1898 }
1899 coordinates[i].value = CGToScalar(variationCGFloat);
1900
1901 }
1902 return axisCount;
1903}
1904
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001905///////////////////////////////////////////////////////////////////////////////
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001906///////////////////////////////////////////////////////////////////////////////
1907
1908int SkTypeface_Mac::onGetUPEM() const {
bungemanc292b5f2016-12-20 12:04:29 -05001909 UniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(fFontRef.get(), nullptr));
1910 return CGFontGetUnitsPerEm(cgFont.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001911}
1912
bungeman@google.com839702b2013-08-07 17:09:22 +00001913SkTypeface::LocalizedStrings* SkTypeface_Mac::onCreateFamilyNameIterator() const {
bungeman@google.coma9802692013-08-07 02:45:25 +00001914 SkTypeface::LocalizedStrings* nameIter =
bungemanc292b5f2016-12-20 12:04:29 -05001915 SkOTUtils::LocalizedStrings_NameTable::CreateForFamilyNames(*this);
halcanary96fcdcc2015-08-27 07:41:13 -07001916 if (nullptr == nameIter) {
bungemanc292b5f2016-12-20 12:04:29 -05001917 CFStringRef cfLanguageRaw;
1918 UniqueCFRef<CFStringRef> cfFamilyName(
1919 CTFontCopyLocalizedName(fFontRef.get(), kCTFontFamilyNameKey, &cfLanguageRaw));
1920 UniqueCFRef<CFStringRef> cfLanguage(cfLanguageRaw);
bungeman@google.coma9802692013-08-07 02:45:25 +00001921
1922 SkString skLanguage;
1923 SkString skFamilyName;
bungemanc292b5f2016-12-20 12:04:29 -05001924 if (cfLanguage) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001925 CFStringToSkString(cfLanguage.get(), &skLanguage);
1926 } else {
1927 skLanguage = "und"; //undetermined
1928 }
bungemanc292b5f2016-12-20 12:04:29 -05001929 if (cfFamilyName) {
bungeman@google.coma9802692013-08-07 02:45:25 +00001930 CFStringToSkString(cfFamilyName.get(), &skFamilyName);
1931 }
1932
1933 nameIter = new SkOTUtils::LocalizedStrings_SingleName(skFamilyName, skLanguage);
1934 }
1935 return nameIter;
1936}
1937
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001938int SkTypeface_Mac::onGetTableTags(SkFontTableTag tags[]) const {
bungemanc292b5f2016-12-20 12:04:29 -05001939 UniqueCFRef<CFArrayRef> cfArray(
1940 CTFontCopyAvailableTables(fFontRef.get(), kCTFontTableOptionNoOptions));
1941 if (!cfArray) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001942 return 0;
1943 }
bungemanc292b5f2016-12-20 12:04:29 -05001944 int count = SkToInt(CFArrayGetCount(cfArray.get()));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001945 if (tags) {
1946 for (int i = 0; i < count; ++i) {
bungemanc292b5f2016-12-20 12:04:29 -05001947 uintptr_t fontTag = reinterpret_cast<uintptr_t>(
1948 CFArrayGetValueAtIndex(cfArray.get(), i));
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001949 tags[i] = static_cast<SkFontTableTag>(fontTag);
1950 }
1951 }
1952 return count;
1953}
1954
bungemanc292b5f2016-12-20 12:04:29 -05001955// If, as is the case with web fonts, the CTFont data isn't available,
1956// the CGFont data may work. While the CGFont may always provide the
1957// right result, leave the CTFont code path to minimize disruption.
1958static UniqueCFRef<CFDataRef> copy_table_from_font(CTFontRef ctFont, SkFontTableTag tag) {
1959 UniqueCFRef<CFDataRef> data(CTFontCopyTable(ctFont, (CTFontTableTag) tag,
1960 kCTFontTableOptionNoOptions));
1961 if (!data) {
1962 UniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(ctFont, nullptr));
1963 data.reset(CGFontCopyTableForTag(cgFont.get(), tag));
1964 }
1965 return data;
1966}
1967
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001968size_t SkTypeface_Mac::onGetTableData(SkFontTableTag tag, size_t offset,
1969 size_t length, void* dstData) const {
bungemanc292b5f2016-12-20 12:04:29 -05001970 UniqueCFRef<CFDataRef> srcData = copy_table_from_font(fFontRef.get(), tag);
1971 if (!srcData) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001972 return 0;
1973 }
1974
bungemanc292b5f2016-12-20 12:04:29 -05001975 size_t srcSize = CFDataGetLength(srcData.get());
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001976 if (offset >= srcSize) {
1977 return 0;
1978 }
1979 if (length > srcSize - offset) {
1980 length = srcSize - offset;
1981 }
1982 if (dstData) {
bungemanc292b5f2016-12-20 12:04:29 -05001983 memcpy(dstData, CFDataGetBytePtr(srcData.get()) + offset, length);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001984 }
1985 return length;
1986}
1987
reeda9322c22016-04-12 06:47:05 -07001988SkScalerContext* SkTypeface_Mac::onCreateScalerContext(const SkScalerContextEffects& effects,
1989 const SkDescriptor* desc) const {
bungeman7cfd46a2016-10-20 16:06:52 -04001990 return new SkScalerContext_Mac(sk_ref_sp(const_cast<SkTypeface_Mac*>(this)), effects, desc);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00001991}
1992
1993void SkTypeface_Mac::onFilterRec(SkScalerContextRec* rec) const {
commit-bot@chromium.orgc5fd4612013-05-06 22:23:08 +00001994 if (rec->fFlags & SkScalerContext::kLCD_BGROrder_Flag ||
1995 rec->fFlags & SkScalerContext::kLCD_Vertical_Flag)
1996 {
1997 rec->fMaskFormat = SkMask::kA8_Format;
1998 // Render the glyphs as close as possible to what was requested.
1999 // The above turns off subpixel rendering, but the user requested it.
2000 // Normal hinting will cause the A8 masks to be generated from CoreGraphics subpixel masks.
2001 // See comments below for more details.
2002 rec->setHinting(SkPaint::kNormal_Hinting);
2003 }
skia.committer@gmail.come944de72013-05-07 07:01:03 +00002004
commit-bot@chromium.orgc5fd4612013-05-06 22:23:08 +00002005 unsigned flagsWeDontSupport = SkScalerContext::kDevKernText_Flag |
bungeman@google.comf6f56872014-01-23 19:01:36 +00002006 SkScalerContext::kForceAutohinting_Flag |
commit-bot@chromium.orgc5fd4612013-05-06 22:23:08 +00002007 SkScalerContext::kLCD_BGROrder_Flag |
2008 SkScalerContext::kLCD_Vertical_Flag;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002009
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002010 rec->fFlags &= ~flagsWeDontSupport;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002011
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002012 bool lcdSupport = supports_LCD();
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002013
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002014 // Only two levels of hinting are supported.
2015 // kNo_Hinting means avoid CoreGraphics outline dilation.
2016 // kNormal_Hinting means CoreGraphics outline dilation is allowed.
2017 // If there is no lcd support, hinting (dilation) cannot be supported.
2018 SkPaint::Hinting hinting = rec->getHinting();
2019 if (SkPaint::kSlight_Hinting == hinting || !lcdSupport) {
2020 hinting = SkPaint::kNo_Hinting;
2021 } else if (SkPaint::kFull_Hinting == hinting) {
2022 hinting = SkPaint::kNormal_Hinting;
2023 }
2024 rec->setHinting(hinting);
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002025
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002026 // FIXME: lcd smoothed un-hinted rasterization unsupported.
2027 // Tracked by http://code.google.com/p/skia/issues/detail?id=915 .
2028 // There is no current means to honor a request for unhinted lcd,
2029 // so arbitrarilly ignore the hinting request and honor lcd.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002030
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002031 // Hinting and smoothing should be orthogonal, but currently they are not.
2032 // CoreGraphics has no API to influence hinting. However, its lcd smoothed
2033 // output is drawn from auto-dilated outlines (the amount of which is
2034 // determined by AppleFontSmoothing). Its regular anti-aliased output is
2035 // drawn from un-dilated outlines.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002036
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002037 // The behavior of Skia is as follows:
2038 // [AA][no-hint]: generate AA using CoreGraphic's AA output.
2039 // [AA][yes-hint]: use CoreGraphic's LCD output and reduce it to a single
2040 // channel. This matches [LCD][yes-hint] in weight.
2041 // [LCD][no-hint]: curently unable to honor, and must pick which to respect.
2042 // Currenly side with LCD, effectively ignoring the hinting setting.
2043 // [LCD][yes-hint]: generate LCD using CoreGraphic's LCD output.
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002044
bungemanc292b5f2016-12-20 12:04:29 -05002045 if (rec->fMaskFormat == SkMask::kLCD16_Format) {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002046 if (lcdSupport) {
2047 //CoreGraphics creates 555 masks for smoothed text anyway.
2048 rec->fMaskFormat = SkMask::kLCD16_Format;
2049 rec->setHinting(SkPaint::kNormal_Hinting);
2050 } else {
2051 rec->fMaskFormat = SkMask::kA8_Format;
2052 }
2053 }
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002054
bungeman34902632014-12-10 21:43:27 -08002055 // CoreText provides no information as to whether a glyph will be color or not.
2056 // Fonts may mix outlines and bitmaps, so information is needed on a glyph by glyph basis.
2057 // If a font contains an 'sbix' table, consider it to be a color font, and disable lcd.
bungeman98c251b2015-02-23 14:24:04 -08002058 if (fHasColorGlyphs) {
bungeman34902632014-12-10 21:43:27 -08002059 rec->fMaskFormat = SkMask::kARGB32_Format;
2060 }
2061
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002062 // Unhinted A8 masks (those not derived from LCD masks) must respect SK_GAMMA_APPLY_TO_A8.
2063 // All other masks can use regular gamma.
2064 if (SkMask::kA8_Format == rec->fMaskFormat && SkPaint::kNo_Hinting == hinting) {
2065#ifndef SK_GAMMA_APPLY_TO_A8
brianosmana1e8f8d2016-04-08 06:47:54 -07002066 // SRGBTODO: Is this correct? Do we want contrast boost?
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002067 rec->ignorePreBlend();
reed@android.comfeda2f92010-05-19 13:47:05 +00002068#endif
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002069 } else {
2070 //CoreGraphics dialates smoothed text as needed.
2071 rec->setContrast(0);
2072 }
2073}
2074
bungemanc292b5f2016-12-20 12:04:29 -05002075/** Takes ownership of the CFStringRef. */
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002076static const char* get_str(CFStringRef ref, SkString* str) {
halcanary96fcdcc2015-08-27 07:41:13 -07002077 if (nullptr == ref) {
2078 return nullptr;
bungeman256b3512014-07-02 07:57:59 -07002079 }
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002080 CFStringToSkString(ref, str);
bungemanc292b5f2016-12-20 12:04:29 -05002081 CFRelease(ref);
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002082 return str->c_str();
2083}
2084
bungemanb374d6a2014-09-17 07:48:59 -07002085void SkTypeface_Mac::onGetFamilyName(SkString* familyName) const {
bungemanc292b5f2016-12-20 12:04:29 -05002086 get_str(CTFontCopyFamilyName(fFontRef.get()), familyName);
bungemanb374d6a2014-09-17 07:48:59 -07002087}
2088
reed@google.com5526ede2013-03-25 13:03:37 +00002089void SkTypeface_Mac::onGetFontDescriptor(SkFontDescriptor* desc,
2090 bool* isLocalStream) const {
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002091 SkString tmpStr;
skia.committer@gmail.com0c23faf2013-03-03 07:16:29 +00002092
bungemanc292b5f2016-12-20 12:04:29 -05002093 desc->setFamilyName(get_str(CTFontCopyFamilyName(fFontRef.get()), &tmpStr));
2094 desc->setFullName(get_str(CTFontCopyFullName(fFontRef.get()), &tmpStr));
2095 desc->setPostscriptName(get_str(CTFontCopyPostScriptName(fFontRef.get()), &tmpStr));
bungemanb8113782016-07-25 16:54:59 -07002096 desc->setStyle(this->fontStyle());
caseq26337e92014-06-30 12:14:52 -07002097 *isLocalStream = fIsLocalStream;
mike@reedtribe.orgb103ed42013-03-03 03:50:09 +00002098}
reed@google.com5526ede2013-03-25 13:03:37 +00002099
reed@google.combcb42ae2013-07-02 13:56:39 +00002100int SkTypeface_Mac::onCharsToGlyphs(const void* chars, Encoding encoding,
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002101 uint16_t glyphs[], int glyphCount) const
2102{
2103 // Undocumented behavior of CTFontGetGlyphsForCharacters with non-bmp code points:
2104 // When a surrogate pair is detected, the glyph index used is the index of the high surrogate.
2105 // It is documented that if a mapping is unavailable, the glyph will be set to 0.
skia.committer@gmail.com0673efe2013-10-26 07:01:53 +00002106
reed@google.combcb42ae2013-07-02 13:56:39 +00002107 SkAutoSTMalloc<1024, UniChar> charStorage;
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002108 const UniChar* src; // UniChar is a UTF-16 16-bit code unit.
2109 int srcCount;
reed@google.combcb42ae2013-07-02 13:56:39 +00002110 switch (encoding) {
2111 case kUTF8_Encoding: {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002112 const char* utf8 = reinterpret_cast<const char*>(chars);
2113 UniChar* utf16 = charStorage.reset(2 * glyphCount);
2114 src = utf16;
reed@google.combcb42ae2013-07-02 13:56:39 +00002115 for (int i = 0; i < glyphCount; ++i) {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002116 SkUnichar uni = SkUTF8_NextUnichar(&utf8);
2117 utf16 += SkUTF16_FromUnichar(uni, utf16);
reed@google.combcb42ae2013-07-02 13:56:39 +00002118 }
reed@google.com7fa2a652014-01-27 13:42:58 +00002119 srcCount = SkToInt(utf16 - src);
reed@google.combcb42ae2013-07-02 13:56:39 +00002120 break;
2121 }
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002122 case kUTF16_Encoding: {
2123 src = reinterpret_cast<const UniChar*>(chars);
2124 int extra = 0;
reed@google.combcb42ae2013-07-02 13:56:39 +00002125 for (int i = 0; i < glyphCount; ++i) {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002126 if (SkUTF16_IsHighSurrogate(src[i + extra])) {
2127 ++extra;
2128 }
reed@google.combcb42ae2013-07-02 13:56:39 +00002129 }
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002130 srcCount = glyphCount + extra;
2131 break;
2132 }
2133 case kUTF32_Encoding: {
2134 const SkUnichar* utf32 = reinterpret_cast<const SkUnichar*>(chars);
2135 UniChar* utf16 = charStorage.reset(2 * glyphCount);
2136 src = utf16;
2137 for (int i = 0; i < glyphCount; ++i) {
2138 utf16 += SkUTF16_FromUnichar(utf32[i], utf16);
2139 }
reed@google.com7fa2a652014-01-27 13:42:58 +00002140 srcCount = SkToInt(utf16 - src);
reed@google.combcb42ae2013-07-02 13:56:39 +00002141 break;
2142 }
2143 }
2144
halcanary96fcdcc2015-08-27 07:41:13 -07002145 // If glyphs is nullptr, CT still needs glyph storage for finding the first failure.
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002146 // Also, if there are any non-bmp code points, the provided 'glyphs' storage will be inadequate.
reed@google.combcb42ae2013-07-02 13:56:39 +00002147 SkAutoSTMalloc<1024, uint16_t> glyphStorage;
2148 uint16_t* macGlyphs = glyphs;
halcanary96fcdcc2015-08-27 07:41:13 -07002149 if (nullptr == macGlyphs || srcCount > glyphCount) {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002150 macGlyphs = glyphStorage.reset(srcCount);
reed@google.combcb42ae2013-07-02 13:56:39 +00002151 }
2152
bungemanc292b5f2016-12-20 12:04:29 -05002153 bool allEncoded = CTFontGetGlyphsForCharacters(fFontRef.get(), src, macGlyphs, srcCount);
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002154
2155 // If there were any non-bmp, then copy and compact.
halcanary96fcdcc2015-08-27 07:41:13 -07002156 // If 'glyphs' is nullptr, then compact glyphStorage in-place.
2157 // If all are bmp and 'glyphs' is non-nullptr, 'glyphs' already contains the compact glyphs.
2158 // If some are non-bmp and 'glyphs' is non-nullptr, copy and compact into 'glyphs'.
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002159 uint16_t* compactedGlyphs = glyphs;
halcanary96fcdcc2015-08-27 07:41:13 -07002160 if (nullptr == compactedGlyphs) {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002161 compactedGlyphs = macGlyphs;
2162 }
2163 if (srcCount > glyphCount) {
2164 int extra = 0;
2165 for (int i = 0; i < glyphCount; ++i) {
bungeman7b09aab2014-09-24 11:04:41 -07002166 compactedGlyphs[i] = macGlyphs[i + extra];
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002167 if (SkUTF16_IsHighSurrogate(src[i + extra])) {
2168 ++extra;
2169 }
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002170 }
2171 }
2172
2173 if (allEncoded) {
reed@google.combcb42ae2013-07-02 13:56:39 +00002174 return glyphCount;
2175 }
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002176
2177 // If we got false, then we need to manually look for first failure.
reed@google.combcb42ae2013-07-02 13:56:39 +00002178 for (int i = 0; i < glyphCount; ++i) {
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002179 if (0 == compactedGlyphs[i]) {
reed@google.combcb42ae2013-07-02 13:56:39 +00002180 return i;
2181 }
2182 }
bungeman@google.com72b8cb22013-10-25 17:49:08 +00002183 // Odd to get here, as we expected CT to have returned true up front.
reed@google.combcb42ae2013-07-02 13:56:39 +00002184 return glyphCount;
2185}
2186
2187int SkTypeface_Mac::onCountGlyphs() const {
bungemanc292b5f2016-12-20 12:04:29 -05002188 return SkToInt(CTFontGetGlyphCount(fFontRef.get()));
reed@google.combcb42ae2013-07-02 13:56:39 +00002189}
2190
reed@google.com95625db2013-03-25 20:44:02 +00002191///////////////////////////////////////////////////////////////////////////////
2192///////////////////////////////////////////////////////////////////////////////
reed@google.com83787c52013-03-26 17:19:15 +00002193
2194static bool find_desc_str(CTFontDescriptorRef desc, CFStringRef name, SkString* value) {
bungemanc292b5f2016-12-20 12:04:29 -05002195 UniqueCFRef<CFStringRef> ref((CFStringRef)CTFontDescriptorCopyAttribute(desc, name));
2196 if (!ref) {
reed@google.com83787c52013-03-26 17:19:15 +00002197 return false;
2198 }
bungemanc292b5f2016-12-20 12:04:29 -05002199 CFStringToSkString(ref.get(), value);
reed@google.com83787c52013-03-26 17:19:15 +00002200 return true;
2201}
2202
reed@google.com95625db2013-03-25 20:44:02 +00002203#include "SkFontMgr.h"
2204
reed@google.com964988f2013-03-29 14:57:22 +00002205static inline int sqr(int value) {
2206 SkASSERT(SkAbs32(value) < 0x7FFF); // check for overflow
2207 return value * value;
2208}
2209
2210// We normalize each axis (weight, width, italic) to be base-900
2211static int compute_metric(const SkFontStyle& a, const SkFontStyle& b) {
2212 return sqr(a.weight() - b.weight()) +
2213 sqr((a.width() - b.width()) * 100) +
bungemanb4bb7d82016-04-27 10:21:04 -07002214 sqr((a.slant() != b.slant()) * 900);
reed@google.com964988f2013-03-29 14:57:22 +00002215}
2216
reed@google.com83787c52013-03-26 17:19:15 +00002217class SkFontStyleSet_Mac : public SkFontStyleSet {
reed@google.com95625db2013-03-25 20:44:02 +00002218public:
bungeman53d5c6e2016-04-08 07:22:29 -07002219 SkFontStyleSet_Mac(CTFontDescriptorRef desc)
halcanary96fcdcc2015-08-27 07:41:13 -07002220 : fArray(CTFontDescriptorCreateMatchingFontDescriptors(desc, nullptr))
bungemanc292b5f2016-12-20 12:04:29 -05002221 , fCount(0)
2222 {
2223 if (!fArray) {
2224 fArray.reset(CFArrayCreate(nullptr, nullptr, 0, nullptr));
reed@google.comdea7ee02013-03-28 14:12:10 +00002225 }
bungemanc292b5f2016-12-20 12:04:29 -05002226 fCount = SkToInt(CFArrayGetCount(fArray.get()));
reed@google.com83787c52013-03-26 17:19:15 +00002227 }
2228
mtklein36352bf2015-03-25 18:17:31 -07002229 int count() override {
reed@google.comdea7ee02013-03-28 14:12:10 +00002230 return fCount;
reed@google.com83787c52013-03-26 17:19:15 +00002231 }
2232
mtklein36352bf2015-03-25 18:17:31 -07002233 void getStyle(int index, SkFontStyle* style, SkString* name) override {
reed@google.comdea7ee02013-03-28 14:12:10 +00002234 SkASSERT((unsigned)index < (unsigned)fCount);
bungemanc292b5f2016-12-20 12:04:29 -05002235 CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index);
reed@google.com83787c52013-03-26 17:19:15 +00002236 if (style) {
bungeman2873c762017-01-13 11:40:21 -05002237 *style = fontstyle_from_descriptor(desc, false);
reed@google.com83787c52013-03-26 17:19:15 +00002238 }
2239 if (name) {
2240 if (!find_desc_str(desc, kCTFontStyleNameAttribute, name)) {
2241 name->reset();
2242 }
2243 }
2244 }
2245
mtklein36352bf2015-03-25 18:17:31 -07002246 SkTypeface* createTypeface(int index) override {
bungemanc292b5f2016-12-20 12:04:29 -05002247 SkASSERT((unsigned)index < (unsigned)CFArrayGetCount(fArray.get()));
2248 CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index);
skia.committer@gmail.com37cbc7f2013-03-27 07:01:04 +00002249
bungemanbea97482016-08-24 08:29:50 -07002250 return create_from_desc(desc);
reed@google.com83787c52013-03-26 17:19:15 +00002251 }
skia.committer@gmail.com37cbc7f2013-03-27 07:01:04 +00002252
mtklein36352bf2015-03-25 18:17:31 -07002253 SkTypeface* matchStyle(const SkFontStyle& pattern) override {
reed@google.com964988f2013-03-29 14:57:22 +00002254 if (0 == fCount) {
halcanary96fcdcc2015-08-27 07:41:13 -07002255 return nullptr;
reed@google.com964988f2013-03-29 14:57:22 +00002256 }
bungemanbea97482016-08-24 08:29:50 -07002257 return create_from_desc(findMatchingDesc(pattern));
reed@google.com964988f2013-03-29 14:57:22 +00002258 }
2259
reed@google.com83787c52013-03-26 17:19:15 +00002260private:
bungemanc292b5f2016-12-20 12:04:29 -05002261 UniqueCFRef<CFArrayRef> fArray;
2262 int fCount;
reed@google.com964988f2013-03-29 14:57:22 +00002263
2264 CTFontDescriptorRef findMatchingDesc(const SkFontStyle& pattern) const {
2265 int bestMetric = SK_MaxS32;
halcanary96fcdcc2015-08-27 07:41:13 -07002266 CTFontDescriptorRef bestDesc = nullptr;
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002267
reed@google.com964988f2013-03-29 14:57:22 +00002268 for (int i = 0; i < fCount; ++i) {
bungemanc292b5f2016-12-20 12:04:29 -05002269 CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), i);
bungeman2873c762017-01-13 11:40:21 -05002270 int metric = compute_metric(pattern, fontstyle_from_descriptor(desc, false));
reed@google.com964988f2013-03-29 14:57:22 +00002271 if (0 == metric) {
2272 return desc;
2273 }
2274 if (metric < bestMetric) {
2275 bestMetric = metric;
2276 bestDesc = desc;
2277 }
2278 }
2279 SkASSERT(bestDesc);
2280 return bestDesc;
2281 }
reed@google.com83787c52013-03-26 17:19:15 +00002282};
2283
2284class SkFontMgr_Mac : public SkFontMgr {
bungemanc292b5f2016-12-20 12:04:29 -05002285 UniqueCFRef<CFArrayRef> fNames;
2286 int fCount;
reed@google.com83787c52013-03-26 17:19:15 +00002287
bungemanc292b5f2016-12-20 12:04:29 -05002288 CFStringRef getFamilyNameAt(int index) const {
reed@google.com83787c52013-03-26 17:19:15 +00002289 SkASSERT((unsigned)index < (unsigned)fCount);
bungemanc292b5f2016-12-20 12:04:29 -05002290 return (CFStringRef)CFArrayGetValueAtIndex(fNames.get(), index);
reed@google.com83787c52013-03-26 17:19:15 +00002291 }
2292
reed@google.com964988f2013-03-29 14:57:22 +00002293 static SkFontStyleSet* CreateSet(CFStringRef cfFamilyName) {
bungemanc292b5f2016-12-20 12:04:29 -05002294 UniqueCFRef<CFMutableDictionaryRef> cfAttr(
reed@google.com964988f2013-03-29 14:57:22 +00002295 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
2296 &kCFTypeDictionaryKeyCallBacks,
2297 &kCFTypeDictionaryValueCallBacks));
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002298
bungemanc292b5f2016-12-20 12:04:29 -05002299 CFDictionaryAddValue(cfAttr.get(), kCTFontFamilyNameAttribute, cfFamilyName);
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002300
bungemanc292b5f2016-12-20 12:04:29 -05002301 UniqueCFRef<CTFontDescriptorRef> desc(
2302 CTFontDescriptorCreateWithAttributes(cfAttr.get()));
2303 return new SkFontStyleSet_Mac(desc.get());
2304 }
2305
2306 /** CTFontManagerCopyAvailableFontFamilyNames() is not always available, so we
2307 * provide a wrapper here that will return an empty array if need be.
2308 */
2309 static UniqueCFRef<CFArrayRef> CopyAvailableFontFamilyNames() {
2310#ifdef SK_BUILD_FOR_IOS
2311 return UniqueCFRef<CFArrayRef>(CFArrayCreate(nullptr, nullptr, 0, nullptr));
2312#else
2313 return UniqueCFRef<CFArrayRef>(CTFontManagerCopyAvailableFontFamilyNames());
2314#endif
reed@google.com964988f2013-03-29 14:57:22 +00002315 }
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002316
reed@google.com83787c52013-03-26 17:19:15 +00002317public:
commit-bot@chromium.org967dee32014-02-04 22:35:01 +00002318 SkFontMgr_Mac()
bungemanc292b5f2016-12-20 12:04:29 -05002319 : fNames(CopyAvailableFontFamilyNames())
2320 , fCount(fNames ? SkToInt(CFArrayGetCount(fNames.get())) : 0) {}
reed@google.com95625db2013-03-25 20:44:02 +00002321
2322protected:
mtklein36352bf2015-03-25 18:17:31 -07002323 int onCountFamilies() const override {
reed@google.com83787c52013-03-26 17:19:15 +00002324 return fCount;
reed@google.com95625db2013-03-25 20:44:02 +00002325 }
2326
mtklein36352bf2015-03-25 18:17:31 -07002327 void onGetFamilyName(int index, SkString* familyName) const override {
reed@google.com83787c52013-03-26 17:19:15 +00002328 if ((unsigned)index < (unsigned)fCount) {
bungemanc292b5f2016-12-20 12:04:29 -05002329 CFStringToSkString(this->getFamilyNameAt(index), familyName);
reed@google.com83787c52013-03-26 17:19:15 +00002330 } else {
2331 familyName->reset();
2332 }
reed@google.com95625db2013-03-25 20:44:02 +00002333 }
2334
mtklein36352bf2015-03-25 18:17:31 -07002335 SkFontStyleSet* onCreateStyleSet(int index) const override {
reed@google.com83787c52013-03-26 17:19:15 +00002336 if ((unsigned)index >= (unsigned)fCount) {
halcanary96fcdcc2015-08-27 07:41:13 -07002337 return nullptr;
reed@google.com83787c52013-03-26 17:19:15 +00002338 }
bungemanc292b5f2016-12-20 12:04:29 -05002339 return CreateSet(this->getFamilyNameAt(index));
reed@google.com95625db2013-03-25 20:44:02 +00002340 }
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002341
mtklein36352bf2015-03-25 18:17:31 -07002342 SkFontStyleSet* onMatchFamily(const char familyName[]) const override {
bungemanc292b5f2016-12-20 12:04:29 -05002343 UniqueCFRef<CFStringRef> cfName = make_CFString(familyName);
2344 return CreateSet(cfName.get());
reed@google.com964988f2013-03-29 14:57:22 +00002345 }
skia.committer@gmail.comd55846d2013-03-30 07:01:27 +00002346
bungemanc292b5f2016-12-20 12:04:29 -05002347 SkTypeface* onMatchFamilyStyle(const char familyName[],
2348 const SkFontStyle& fontStyle) const override {
Hal Canary67b39de2016-11-07 11:47:44 -05002349 sk_sp<SkFontStyleSet> sset(this->matchFamily(familyName));
bungeman5eff9e72016-01-21 08:18:42 -08002350 return sset->matchStyle(fontStyle);
reed@google.com95625db2013-03-25 20:44:02 +00002351 }
skia.committer@gmail.come60ed082013-03-26 07:01:04 +00002352
bungemanc292b5f2016-12-20 12:04:29 -05002353 SkTypeface* onMatchFamilyStyleCharacter(const char familyName[],
2354 const SkFontStyle& style,
2355 const char* bcp47[], int bcp47Count,
2356 SkUnichar character) const override {
2357 UniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style);
2358 UniqueCFRef<CTFontRef> currentFont(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr));
bungemanbea97482016-08-24 08:29:50 -07002359
2360 // kCFStringEncodingUTF32 is BE unless there is a BOM.
2361 // Since there is no machine endian option, explicitly state machine endian.
2362#ifdef SK_CPU_LENDIAN
2363 constexpr CFStringEncoding encoding = kCFStringEncodingUTF32LE;
2364#else
2365 constexpr CFStringEncoding encoding = kCFStringEncodingUTF32BE;
2366#endif
bungemanc292b5f2016-12-20 12:04:29 -05002367 UniqueCFRef<CFStringRef> string(CFStringCreateWithBytes(
bungemanbea97482016-08-24 08:29:50 -07002368 kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(&character), sizeof(character),
2369 encoding, false));
bungemanc292b5f2016-12-20 12:04:29 -05002370 CFRange range = CFRangeMake(0, CFStringGetLength(string.get())); // in UniChar units.
2371 UniqueCFRef<CTFontRef> fallbackFont(
2372 CTFontCreateForString(currentFont.get(), string.get(), range));
2373 return create_from_CTFontRef(std::move(fallbackFont), nullptr, false);
djsollen33068c12014-11-14 10:52:53 -08002374 }
2375
bungemanc292b5f2016-12-20 12:04:29 -05002376 SkTypeface* onMatchFaceStyle(const SkTypeface* familyMember,
2377 const SkFontStyle&) const override {
halcanary96fcdcc2015-08-27 07:41:13 -07002378 return nullptr;
reed@google.com95625db2013-03-25 20:44:02 +00002379 }
skia.committer@gmail.come60ed082013-03-26 07:01:04 +00002380
mtklein36352bf2015-03-25 18:17:31 -07002381 SkTypeface* onCreateFromData(SkData* data, int ttcIndex) const override {
bungemanc292b5f2016-12-20 12:04:29 -05002382 UniqueCFRef<CGDataProviderRef> pr(SkCreateDataProviderFromData(sk_ref_sp(data)));
2383 if (!pr) {
halcanary96fcdcc2015-08-27 07:41:13 -07002384 return nullptr;
reed@google.com95625db2013-03-25 20:44:02 +00002385 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002386 return create_from_dataProvider(std::move(pr), ttcIndex);
reed@google.com95625db2013-03-25 20:44:02 +00002387 }
2388
bungemanf93d7112016-09-16 06:24:20 -07002389 SkTypeface* onCreateFromStream(SkStreamAsset* bareStream, int ttcIndex) const override {
2390 std::unique_ptr<SkStreamAsset> stream(bareStream);
bungemanc292b5f2016-12-20 12:04:29 -05002391 UniqueCFRef<CGDataProviderRef> pr(SkCreateDataProviderFromStream(std::move(stream)));
2392 if (!pr) {
halcanary96fcdcc2015-08-27 07:41:13 -07002393 return nullptr;
reed@google.com95625db2013-03-25 20:44:02 +00002394 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002395 return create_from_dataProvider(std::move(pr), ttcIndex);
reed@google.com95625db2013-03-25 20:44:02 +00002396 }
2397
Ben Wagnerfc497342017-02-24 11:15:26 -05002398 /** Creates a dictionary suitable for setting the axes on a CGFont. */
2399 static UniqueCFRef<CFDictionaryRef> copy_axes(CGFontRef cg, const SkFontArguments& args) {
2400 // The CGFont variation data is keyed by name, but lacks the tag.
bungemanf6c71072016-01-21 14:17:47 -08002401 // The CTFont variation data is keyed by tag, and also has the name.
Ben Wagnerfc497342017-02-24 11:15:26 -05002402 // We would like to work with CTFont variations, but creating a CTFont font with
bungemanf6c71072016-01-21 14:17:47 -08002403 // CTFont variation dictionary runs into bugs. So use the CTFont variation data
2404 // to match names to tags to create the appropriate CGFont.
bungemanc292b5f2016-12-20 12:04:29 -05002405 UniqueCFRef<CTFontRef> ct(CTFontCreateWithGraphicsFont(cg, 0, nullptr, nullptr));
Ben Wagnerfc497342017-02-24 11:15:26 -05002406 // This call always returns nullptr on 10.10 and under.
2407 // When this happens, there is no API to provide the tag.
bungemanc292b5f2016-12-20 12:04:29 -05002408 UniqueCFRef<CFArrayRef> ctAxes(CTFontCopyVariationAxes(ct.get()));
Ben Wagnerfc497342017-02-24 11:15:26 -05002409 if (!ctAxes) {
bungemanf6c71072016-01-21 14:17:47 -08002410 return nullptr;
2411 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002412 CFIndex axisCount = CFArrayGetCount(ctAxes.get());
bungemanf6c71072016-01-21 14:17:47 -08002413
Ben Wagnerfc497342017-02-24 11:15:26 -05002414 const SkFontArguments::VariationPosition position = args.getVariationDesignPosition();
bungemanf6c71072016-01-21 14:17:47 -08002415
bungemanc292b5f2016-12-20 12:04:29 -05002416 UniqueCFRef<CFMutableDictionaryRef> dict(
2417 CFDictionaryCreateMutable(kCFAllocatorDefault, axisCount,
2418 &kCFTypeDictionaryKeyCallBacks,
2419 &kCFTypeDictionaryValueCallBacks));
2420
bungemanf6c71072016-01-21 14:17:47 -08002421 for (int i = 0; i < axisCount; ++i) {
Ben Wagnerfc497342017-02-24 11:15:26 -05002422 CFTypeRef axisInfo = CFArrayGetValueAtIndex(ctAxes.get(), i);
bungemanf6c71072016-01-21 14:17:47 -08002423 if (CFDictionaryGetTypeID() != CFGetTypeID(axisInfo)) {
2424 return nullptr;
2425 }
2426 CFDictionaryRef axisInfoDict = static_cast<CFDictionaryRef>(axisInfo);
2427
Ben Wagnerfc497342017-02-24 11:15:26 -05002428 // The assumption is that values produced by kCTFontVariationAxisNameKey and
2429 // kCGFontVariationAxisName will always be equal.
2430 // If they are ever not, seach the project history for "get_tag_for_name".
2431 CFTypeRef axisName = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisNameKey);
bungemanf6c71072016-01-21 14:17:47 -08002432 if (!axisName || CFGetTypeID(axisName) != CFStringGetTypeID()) {
2433 return nullptr;
2434 }
2435
Ben Wagnerfc497342017-02-24 11:15:26 -05002436 CFTypeRef tag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
2437 if (!tag || CFGetTypeID(tag) != CFNumberGetTypeID()) {
2438 return nullptr;
bungemanf6c71072016-01-21 14:17:47 -08002439 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002440 CFNumberRef tagNumber = static_cast<CFNumberRef>(tag);
bungemanf6c71072016-01-21 14:17:47 -08002441 int64_t tagLong;
2442 if (!CFNumberGetValue(tagNumber, kCFNumberSInt64Type, &tagLong)) {
2443 return nullptr;
2444 }
2445
2446 // The variation axes can be set to any value, but cg will effectively pin them.
2447 // Pin them here to normalize.
Ben Wagnerfc497342017-02-24 11:15:26 -05002448 CFTypeRef min = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMinimumValueKey);
2449 CFTypeRef max = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMaximumValueKey);
2450 CFTypeRef def = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisDefaultValueKey);
bungemanf6c71072016-01-21 14:17:47 -08002451 if (!min || CFGetTypeID(min) != CFNumberGetTypeID() ||
2452 !max || CFGetTypeID(max) != CFNumberGetTypeID() ||
2453 !def || CFGetTypeID(def) != CFNumberGetTypeID())
2454 {
2455 return nullptr;
2456 }
2457 CFNumberRef minNumber = static_cast<CFNumberRef>(min);
2458 CFNumberRef maxNumber = static_cast<CFNumberRef>(max);
2459 CFNumberRef defNumber = static_cast<CFNumberRef>(def);
2460 double minDouble;
2461 double maxDouble;
2462 double defDouble;
2463 if (!CFNumberGetValue(minNumber, kCFNumberDoubleType, &minDouble) ||
2464 !CFNumberGetValue(maxNumber, kCFNumberDoubleType, &maxDouble) ||
2465 !CFNumberGetValue(defNumber, kCFNumberDoubleType, &defDouble))
2466 {
2467 return nullptr;
2468 }
2469
2470 double value = defDouble;
Ben Wagnerfc497342017-02-24 11:15:26 -05002471 for (int j = 0; j < position.coordinateCount; ++j) {
2472 if (position.coordinates[j].axis == tagLong) {
2473 value = SkTPin(SkScalarToDouble(position.coordinates[j].value),
2474 minDouble, maxDouble);
bungemanf6c71072016-01-21 14:17:47 -08002475 break;
2476 }
2477 }
bungemanc292b5f2016-12-20 12:04:29 -05002478 UniqueCFRef<CFNumberRef> valueNumber(
2479 CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value));
2480 CFDictionaryAddValue(dict.get(), axisName, valueNumber.get());
bungemanf6c71072016-01-21 14:17:47 -08002481 }
bungemanc292b5f2016-12-20 12:04:29 -05002482 return std::move(dict);
bungemanf6c71072016-01-21 14:17:47 -08002483 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002484 SkTypeface* onCreateFromStream(SkStreamAsset* bs, const SkFontArguments& args) const override {
bungemanf93d7112016-09-16 06:24:20 -07002485 std::unique_ptr<SkStreamAsset> s(bs);
Ben Wagnerfc497342017-02-24 11:15:26 -05002486 if (args.getCollectionIndex() != 0) {
2487 return nullptr;
2488 }
bungemanc292b5f2016-12-20 12:04:29 -05002489 UniqueCFRef<CGDataProviderRef> provider(SkCreateDataProviderFromStream(std::move(s)));
2490 if (!provider) {
bungemanf6c71072016-01-21 14:17:47 -08002491 return nullptr;
2492 }
bungemanc292b5f2016-12-20 12:04:29 -05002493 UniqueCFRef<CGFontRef> cg(CGFontCreateWithDataProvider(provider.get()));
2494 if (!cg) {
bungemanf6c71072016-01-21 14:17:47 -08002495 return nullptr;
2496 }
2497
Ben Wagnerfc497342017-02-24 11:15:26 -05002498 UniqueCFRef<CFDictionaryRef> cgVariations = copy_axes(cg.get(), args);
bungemanf6c71072016-01-21 14:17:47 -08002499 // The CGFontRef returned by CGFontCreateCopyWithVariations when the passed CGFontRef was
2500 // created from a data provider does not appear to have any ownership of the underlying
2501 // data. The original CGFontRef must be kept alive until the copy will no longer be used.
bungemanc292b5f2016-12-20 12:04:29 -05002502 UniqueCFRef<CGFontRef> cgVariant;
bungemanf6c71072016-01-21 14:17:47 -08002503 if (cgVariations) {
bungemanc292b5f2016-12-20 12:04:29 -05002504 cgVariant.reset(CGFontCreateCopyWithVariations(cg.get(), cgVariations.get()));
bungemanf6c71072016-01-21 14:17:47 -08002505 } else {
mtklein18300a32016-03-16 13:53:35 -07002506 cgVariant.reset(cg.release());
bungemanf6c71072016-01-21 14:17:47 -08002507 }
2508
bungemanc292b5f2016-12-20 12:04:29 -05002509 UniqueCFRef<CTFontRef> ct(
2510 CTFontCreateWithGraphicsFont(cgVariant.get(), 0, nullptr, nullptr));
bungemanf6c71072016-01-21 14:17:47 -08002511 if (!ct) {
2512 return nullptr;
2513 }
bungemanc292b5f2016-12-20 12:04:29 -05002514 return create_from_CTFontRef(std::move(ct), std::move(cg), true);
bungemanf6c71072016-01-21 14:17:47 -08002515 }
2516
Ben Wagnerfc497342017-02-24 11:15:26 -05002517 /** Creates a dictionary suitable for setting the axes on a CGFont. */
bungemanc292b5f2016-12-20 12:04:29 -05002518 static UniqueCFRef<CFDictionaryRef> copy_axes(CGFontRef cg, SkFontData* fontData) {
2519 UniqueCFRef<CFArrayRef> cgAxes(CGFontCopyVariationAxes(cg));
bungeman41868fe2015-05-20 09:21:04 -07002520 if (!cgAxes) {
halcanary96fcdcc2015-08-27 07:41:13 -07002521 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002522 }
2523
bungemanc292b5f2016-12-20 12:04:29 -05002524 CFIndex axisCount = CFArrayGetCount(cgAxes.get());
bungeman41868fe2015-05-20 09:21:04 -07002525 if (0 == axisCount || axisCount != fontData->getAxisCount()) {
halcanary96fcdcc2015-08-27 07:41:13 -07002526 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002527 }
2528
bungemanc292b5f2016-12-20 12:04:29 -05002529 UniqueCFRef<CFMutableDictionaryRef> dict(
2530 CFDictionaryCreateMutable(kCFAllocatorDefault, axisCount,
2531 &kCFTypeDictionaryKeyCallBacks,
2532 &kCFTypeDictionaryValueCallBacks));
2533
bungeman41868fe2015-05-20 09:21:04 -07002534 for (int i = 0; i < fontData->getAxisCount(); ++i) {
bungemanc292b5f2016-12-20 12:04:29 -05002535 CFTypeRef axisInfo = CFArrayGetValueAtIndex(cgAxes.get(), i);
bungeman41868fe2015-05-20 09:21:04 -07002536 if (CFDictionaryGetTypeID() != CFGetTypeID(axisInfo)) {
halcanary96fcdcc2015-08-27 07:41:13 -07002537 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002538 }
2539 CFDictionaryRef axisInfoDict = static_cast<CFDictionaryRef>(axisInfo);
2540
2541 CFTypeRef axisName = CFDictionaryGetValue(axisInfoDict, kCGFontVariationAxisName);
2542 if (!axisName || CFGetTypeID(axisName) != CFStringGetTypeID()) {
halcanary96fcdcc2015-08-27 07:41:13 -07002543 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002544 }
2545
2546 // The variation axes can be set to any value, but cg will effectively pin them.
2547 // Pin them here to normalize.
2548 CFTypeRef min = CFDictionaryGetValue(axisInfoDict, kCGFontVariationAxisMinValue);
2549 CFTypeRef max = CFDictionaryGetValue(axisInfoDict, kCGFontVariationAxisMaxValue);
2550 if (!min || CFGetTypeID(min) != CFNumberGetTypeID() ||
2551 !max || CFGetTypeID(max) != CFNumberGetTypeID())
2552 {
halcanary96fcdcc2015-08-27 07:41:13 -07002553 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002554 }
2555 CFNumberRef minNumber = static_cast<CFNumberRef>(min);
2556 CFNumberRef maxNumber = static_cast<CFNumberRef>(max);
2557 double minDouble;
2558 double maxDouble;
2559 if (!CFNumberGetValue(minNumber, kCFNumberDoubleType, &minDouble) ||
2560 !CFNumberGetValue(maxNumber, kCFNumberDoubleType, &maxDouble))
2561 {
halcanary96fcdcc2015-08-27 07:41:13 -07002562 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002563 }
2564 double value = SkTPin(SkFixedToDouble(fontData->getAxis()[i]), minDouble, maxDouble);
bungemanc292b5f2016-12-20 12:04:29 -05002565 UniqueCFRef<CFNumberRef> valueNumber(
2566 CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value));
2567 CFDictionaryAddValue(dict.get(), axisName, valueNumber.get());
bungeman41868fe2015-05-20 09:21:04 -07002568 }
bungemanc292b5f2016-12-20 12:04:29 -05002569 return std::move(dict);
bungeman41868fe2015-05-20 09:21:04 -07002570 }
bungemanf93d7112016-09-16 06:24:20 -07002571 SkTypeface* onCreateFromFontData(std::unique_ptr<SkFontData> fontData) const override {
Ben Wagnerfc497342017-02-24 11:15:26 -05002572 if (fontData->getIndex() != 0) {
2573 return nullptr;
2574 }
bungemanc292b5f2016-12-20 12:04:29 -05002575 UniqueCFRef<CGDataProviderRef> provider(
bungemanf93d7112016-09-16 06:24:20 -07002576 SkCreateDataProviderFromStream(fontData->detachStream()));
bungemanc292b5f2016-12-20 12:04:29 -05002577 if (!provider) {
halcanary96fcdcc2015-08-27 07:41:13 -07002578 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002579 }
bungemanc292b5f2016-12-20 12:04:29 -05002580 UniqueCFRef<CGFontRef> cg(CGFontCreateWithDataProvider(provider.get()));
2581 if (!cg) {
halcanary96fcdcc2015-08-27 07:41:13 -07002582 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002583 }
2584
bungemanc292b5f2016-12-20 12:04:29 -05002585 UniqueCFRef<CFDictionaryRef> cgVariations = copy_axes(cg.get(), fontData.get());
bungeman41868fe2015-05-20 09:21:04 -07002586 // The CGFontRef returned by CGFontCreateCopyWithVariations when the passed CGFontRef was
2587 // created from a data provider does not appear to have any ownership of the underlying
2588 // data. The original CGFontRef must be kept alive until the copy will no longer be used.
bungemanc292b5f2016-12-20 12:04:29 -05002589 UniqueCFRef<CGFontRef> cgVariant;
bungeman41868fe2015-05-20 09:21:04 -07002590 if (cgVariations) {
bungemanc292b5f2016-12-20 12:04:29 -05002591 cgVariant.reset(CGFontCreateCopyWithVariations(cg.get(), cgVariations.get()));
bungeman41868fe2015-05-20 09:21:04 -07002592 } else {
mtklein18300a32016-03-16 13:53:35 -07002593 cgVariant.reset(cg.release());
bungeman41868fe2015-05-20 09:21:04 -07002594 }
2595
bungemanc292b5f2016-12-20 12:04:29 -05002596 UniqueCFRef<CTFontRef> ct(
2597 CTFontCreateWithGraphicsFont(cgVariant.get(), 0, nullptr, nullptr));
bungeman41868fe2015-05-20 09:21:04 -07002598 if (!ct) {
halcanary96fcdcc2015-08-27 07:41:13 -07002599 return nullptr;
bungeman41868fe2015-05-20 09:21:04 -07002600 }
bungemanc292b5f2016-12-20 12:04:29 -05002601 return create_from_CTFontRef(std::move(ct), std::move(cg), true);
bungeman41868fe2015-05-20 09:21:04 -07002602 }
2603
mtklein36352bf2015-03-25 18:17:31 -07002604 SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const override {
bungemanc292b5f2016-12-20 12:04:29 -05002605 UniqueCFRef<CGDataProviderRef> pr(CGDataProviderCreateWithFilename(path));
2606 if (!pr) {
halcanary96fcdcc2015-08-27 07:41:13 -07002607 return nullptr;
reed@google.com95625db2013-03-25 20:44:02 +00002608 }
Ben Wagnerfc497342017-02-24 11:15:26 -05002609 return create_from_dataProvider(std::move(pr), ttcIndex);
reed@google.com95625db2013-03-25 20:44:02 +00002610 }
skia.committer@gmail.com76015b02013-07-31 07:01:00 +00002611
bungeman11a77c62016-04-12 13:45:06 -07002612 SkTypeface* onLegacyCreateTypeface(const char familyName[], SkFontStyle style) const override {
bungemana4c4a2d2014-10-20 13:33:19 -07002613 if (familyName) {
2614 familyName = map_css_names(familyName);
2615 }
2616
bungemanbea97482016-08-24 08:29:50 -07002617 SkTypeface* face = create_from_name(familyName, style);
bungeman53d5c6e2016-04-08 07:22:29 -07002618 if (face) {
2619 return face;
bungemana4c4a2d2014-10-20 13:33:19 -07002620 }
bungeman53d5c6e2016-04-08 07:22:29 -07002621
bungemanc292b5f2016-12-20 12:04:29 -05002622 static SkTypeface* gDefaultFace;
2623 static SkOnce lookupDefault;
bungeman83f1f442017-02-06 13:21:33 -05002624 static const char FONT_DEFAULT_NAME[] = "Lucida Sans";
bungemanc292b5f2016-12-20 12:04:29 -05002625 lookupDefault([]{
2626 gDefaultFace = create_from_name(FONT_DEFAULT_NAME, SkFontStyle());
2627 });
2628 return SkSafeRef(gDefaultFace);
reed@google.com7fdcd442013-07-30 21:25:49 +00002629 }
reed@google.com95625db2013-03-25 20:44:02 +00002630};
2631
reed@google.com7fdcd442013-07-30 21:25:49 +00002632///////////////////////////////////////////////////////////////////////////////
2633
Ben Wagner3546ff12017-01-03 13:32:36 -05002634sk_sp<SkFontMgr> SkFontMgr::Factory() { return sk_make_sp<SkFontMgr_Mac>(); }
mtklein1ee76512015-11-02 10:20:27 -08002635
2636#endif//defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)