Debian Codegraph @

src/ports/SkTypeface_mac_ct.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * 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
8 #include "include/core/SkTypes.h"
9 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
10
11 #ifdef SK_BUILD_FOR_MAC
12 #import <ApplicationServices/ApplicationServices.h>
13 #endif
14
15 #ifdef SK_BUILD_FOR_IOS
16 #include <CoreText/CoreText.h>
17 #include <CoreText/CTFontManager.h>
18 #include <CoreGraphics/CoreGraphics.h>
19 #include <CoreFoundation/CoreFoundation.h>
20 #endif
21
22 #include "include/core/SkColor.h"
23 #include "include/core/SkData.h"
24 #include "include/core/SkFontArguments.h"
25 #include "include/core/SkFontParameters.h"
26 #include "include/core/SkFontStyle.h"
27 #include "include/core/SkFontTypes.h"
28 #include "include/core/SkRect.h"
29 #include "include/core/SkRefCnt.h"
30 #include "include/core/SkScalar.h"
31 #include "include/core/SkStream.h"
32 #include "include/core/SkString.h"
33 #include "include/core/SkTypeface.h"
34 #include "include/ports/SkTypeface_mac.h"
35 #include "include/private/base/SkFixed.h"
36 #include "include/private/base/SkMalloc.h"
37 #include "include/private/base/SkMutex.h"
38 #include "include/private/base/SkOnce.h"
39 #include "include/private/base/SkTDArray.h"
40 #include "include/private/base/SkTPin.h"
41 #include "include/private/base/SkTemplates.h"
42 #include "include/private/base/SkTo.h"
43 #include "src/base/SkEndian.h"
44 #include "src/base/SkUTF.h"
45 #include "src/core/SkAdvancedTypefaceMetrics.h"
46 #include "src/core/SkFontDescriptor.h"
47 #include "src/core/SkMask.h"
48 #include "src/core/SkScalerContext.h"
49 #include "src/core/SkTypefaceCache.h"
50 #include "src/ports/SkScalerContext_mac_ct.h"
51 #include "src/ports/SkTypeface_mac_ct.h"
52 #include "src/sfnt/SkOTTableTypes.h"
53 #include "src/sfnt/SkOTTable_OS_2.h"
54 #include "src/sfnt/SkOTTable_OS_2_V4.h"
55 #include "src/sfnt/SkOTUtils.h"
56 #include "src/sfnt/SkSFNTHeader.h"
57 #include "src/utils/mac/SkCGBase.h"
58 #include "src/utils/mac/SkCGGeometry.h"
59 #include "src/utils/mac/SkCTFont.h"
60 #include "src/utils/mac/SkCTFontCreateExactCopy.h"
61 #include "src/utils/mac/SkUniqueCFRef.h"
62
63 #include <dlfcn.h>
64 #include <limits.h>
65 #include <string.h>
66 #include <memory>
67
68 using namespace skia_private;
69
70 /** Assumes src and dst are not nullptr. */
71 void SkStringFromCFString(CFStringRef src, SkString* dst) {
72 // Reserve enough room for the worst-case string,
73 // plus 1 byte for the trailing null.
74 CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(src),
75 kCFStringEncodingUTF8) + 1;
76 dst->resize(length);
77 CFStringGetCString(src, dst->data(), length, kCFStringEncodingUTF8);
78 // Resize to the actual UTF-8 length used, stripping the null character.
79 dst->resize(strlen(dst->c_str()));
80 }
81
82 SkString SkCFTypeIDDescription(CFTypeID id) {
83 SkUniqueCFRef<CFStringRef> typeDescription(CFCopyTypeIDDescription(id));
84 SkString skTypeDescription;
85 SkStringFromCFString(typeDescription.get(), &skTypeDescription);
86 return skTypeDescription;
87 }
88
89 template<typename CF> CFTypeID SkCFGetTypeID();
90 #define SK_GETCFTYPEID(cf) \
91 template<> CFTypeID SkCFGetTypeID<cf##Ref>() { return cf##GetTypeID(); }
92 SK_GETCFTYPEID(CFArray)
93 SK_GETCFTYPEID(CFBoolean)
94 SK_GETCFTYPEID(CFDictionary)
95 SK_GETCFTYPEID(CFNumber)
96
97 /* Checked dynamic downcast of CFTypeRef.
98 *
99 * @param cf the ref to downcast.
100 * @param cfAsCF if cf can be cast to the type CF, receives the downcast ref.
101 * @param name if non-nullptr the cast is expected to succeed and failures will be logged.
102 * @return true if the cast succeeds, false otherwise.
103 */
104 template <typename CF>
105 static bool SkCFDynamicCast(CFTypeRef cf, CF* cfAsCF, char const* name) {
106 //SkDEBUGF("SkCFDynamicCast '%s' of type %s to type %s\n", name ? name : "<annon>",
107 // SkCFTypeIDDescription( CFGetTypeID(cf) ).c_str()
108 // SkCFTypeIDDescription(SkCFGetTypeID<CF>()).c_str());
109 if (!cf) {
110 if (name) {
111 SkDEBUGF("%s not present\n", name);
112 }
113 return false;
114 }
115 if (CFGetTypeID(cf) != SkCFGetTypeID<CF>()) {
116 if (name) {
117 SkDEBUGF("%s is a %s but expected a %s\n", name,
118 SkCFTypeIDDescription( CFGetTypeID(cf) ).c_str(),
119 SkCFTypeIDDescription(SkCFGetTypeID<CF>()).c_str());
120 }
121 return false;
122 }
123 *cfAsCF = static_cast<CF>(cf);
124 return true;
125 }
126
127 template<typename T> struct SkCFNumberTypeFor {};
128 #define SK_CFNUMBERTYPE_FOR(c, cf) \
129 template<> struct SkCFNumberTypeFor<c> : std::integral_constant<CFNumberType, cf> {};
130 SK_CFNUMBERTYPE_FOR(char , kCFNumberCharType )
131 SK_CFNUMBERTYPE_FOR(short , kCFNumberShortType )
132 SK_CFNUMBERTYPE_FOR(int , kCFNumberIntType )
133 SK_CFNUMBERTYPE_FOR(long , kCFNumberLongType )
134 SK_CFNUMBERTYPE_FOR(long long, kCFNumberLongLongType)
135 SK_CFNUMBERTYPE_FOR(float , kCFNumberFloatType )
136 SK_CFNUMBERTYPE_FOR(double , kCFNumberDoubleType )
137
138 template <typename T>
139 static bool SkCFNumberDynamicCast(CFTypeRef cf, T* number, CFNumberRef* cfNumber, char const* name){
140 CFNumberRef cfAsCFNumber;
141 if (!SkCFDynamicCast(cf, &cfAsCFNumber, name)) {
142 return false;
143 }
144 if (!CFNumberGetValue(cfAsCFNumber, SkCFNumberTypeFor<T>::value, number)) {
145 if (name) {
146 SkDEBUGF("%s CFNumber not extractable\n", name);
147 }
148 return false;
149 }
150 if (cfNumber) {
151 *cfNumber = cfAsCFNumber;
152 }
153 return true;
154 }
155
156 CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face) {
157 return face ? (CTFontRef)face->internal_private_getCTFontRef() : nullptr;
158 }
159
160 static bool find_by_CTFontRef(SkTypeface* cached, void* context) {
161 CTFontRef self = (CTFontRef)context;
162 CTFontRef other = (CTFontRef)cached->internal_private_getCTFontRef();
163
164 return CFEqual(self, other);
165 }
166
167 /** Creates a typeface, searching the cache if providedData is nullptr. */
168 sk_sp<SkTypeface> SkTypeface_Mac::Make(SkUniqueCFRef<CTFontRef> font,
169 OpszVariation opszVariation,
170 std::unique_ptr<SkStreamAsset> providedData) {
171 static SkMutex gTFCacheMutex;
172 static SkTypefaceCache gTFCache;
173
174 SkASSERT(font);
175 const bool isFromStream(providedData);
176
177 auto makeTypeface = [&]() {
178 SkUniqueCFRef<CTFontDescriptorRef> desc(CTFontCopyFontDescriptor(font.get()));
179 SkFontStyle style = SkCTFontDescriptorGetSkFontStyle(desc.get(), isFromStream);
180 CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(font.get());
181 bool isFixedPitch = SkToBool(traits & kCTFontMonoSpaceTrait);
182
183 return sk_sp<SkTypeface>(new SkTypeface_Mac(std::move(font), style, isFixedPitch,
184 opszVariation, std::move(providedData)));
185 };
186
187 if (isFromStream) {
188 return makeTypeface();
189 }
190
191 SkAutoMutexExclusive ama(gTFCacheMutex);
192 sk_sp<SkTypeface> face = gTFCache.findByProcAndRef(find_by_CTFontRef, (void*)font.get());
193 if (!face) {
194 face = makeTypeface();
195 if (face) {
196 gTFCache.add(face);
197 }
198 }
199 return face;
200 }
201
202 /* This function is visible on the outside. It first searches the cache, and if
203 * not found, returns a new entry (after adding it to the cache).
204 */
205 sk_sp<SkTypeface> SkMakeTypefaceFromCTFont(CTFontRef font) {
206 CFRetain(font);
207 return SkTypeface_Mac::Make(SkUniqueCFRef<CTFontRef>(font),
208 OpszVariation(),
209 nullptr);
210 }
211
212 static bool find_dict_CGFloat(CFDictionaryRef dict, CFStringRef name, CGFloat* value) {
213 CFNumberRef num;
214 return CFDictionaryGetValueIfPresent(dict, name, (const void**)&num)
215 && CFNumberIsFloatType(num)
216 && CFNumberGetValue(num, kCFNumberCGFloatType, value);
217 }
218
219 template <typename S, typename D, typename C> struct LinearInterpolater {
220 struct Mapping {
221 S src_val;
222 D dst_val;
223 };
224 constexpr LinearInterpolater(Mapping const mapping[], int mappingCount)
225 : fMapping(mapping), fMappingCount(mappingCount) {}
226
227 static D map(S value, S src_min, S src_max, D dst_min, D dst_max) {
228 SkASSERT(src_min < src_max);
229 SkASSERT(dst_min <= dst_max);
230 return C()(dst_min + (((value - src_min) * (dst_max - dst_min)) / (src_max - src_min)));
231 }
232
233 D map(S val) const {
234 // -Inf to [0]
235 if (val < fMapping[0].src_val) {
236 return fMapping[0].dst_val;
237 }
238
239 // Linear from [i] to [i+1]
240 for (int i = 0; i < fMappingCount - 1; ++i) {
241 if (val < fMapping[i+1].src_val) {
242 return map(val, fMapping[i].src_val, fMapping[i+1].src_val,
243 fMapping[i].dst_val, fMapping[i+1].dst_val);
244 }
245 }
246
247 // From [n] to +Inf
248 // if (fcweight < Inf)
249 return fMapping[fMappingCount - 1].dst_val;
250 }
251
252 Mapping const * fMapping;
253 int fMappingCount;
254 };
255
256 struct RoundCGFloatToInt {
257 int operator()(CGFloat s) { return s + 0.5; }
258 };
259 struct CGFloatIdentity {
260 CGFloat operator()(CGFloat s) { return s; }
261 };
262
263 /** Convert the [0, 1000] CSS weight to [-1, 1] CTFontDescriptor weight (for system fonts).
264 *
265 * The -1 to 1 weights reported by CTFontDescriptors have different mappings depending on if the
266 * CTFont is native or created from a CGDataProvider.
267 */
268 CGFloat SkCTFontCTWeightForCSSWeight(int fontstyleWeight) {
269 using Interpolator = LinearInterpolater<int, CGFloat, CGFloatIdentity>;
270
271 // Note that Mac supports the old OS2 version A so 0 through 10 are as if multiplied by 100.
272 // However, on this end we can't tell, so this is ignored.
273
274 static Interpolator::Mapping nativeWeightMappings[11];
275 static SkOnce once;
276 once([&] {
277 const CGFloat(&nsFontWeights)[11] = SkCTFontGetNSFontWeightMapping();
278 for (int i = 0; i < 11; ++i) {
279 nativeWeightMappings[i].src_val = i * 100;
280 nativeWeightMappings[i].dst_val = nsFontWeights[i];
281 }
282 });
283 static constexpr Interpolator nativeInterpolator(
284 nativeWeightMappings, std::size(nativeWeightMappings));
285
286 return nativeInterpolator.map(fontstyleWeight);
287 }
288
289 /** Convert the [-1, 1] CTFontDescriptor weight to [0, 1000] CSS weight.
290 *
291 * The -1 to 1 weights reported by CTFontDescriptors have different mappings depending on if the
292 * CTFont is native or created from a CGDataProvider.
293 */
294 static int ct_weight_to_fontstyle(CGFloat cgWeight, bool fromDataProvider) {
295 using Interpolator = LinearInterpolater<CGFloat, int, RoundCGFloatToInt>;
296
297 // Note that Mac supports the old OS2 version A so 0 through 10 are as if multiplied by 100.
298 // However, on this end we can't tell, so this is ignored.
299
300 static Interpolator::Mapping nativeWeightMappings[11];
301 static Interpolator::Mapping dataProviderWeightMappings[11];
302 static SkOnce once;
303 once([&] {
304 const CGFloat(&nsFontWeights)[11] = SkCTFontGetNSFontWeightMapping();
305 const CGFloat(&userFontWeights)[11] = SkCTFontGetDataFontWeightMapping();
306 for (int i = 0; i < 11; ++i) {
307 nativeWeightMappings[i].src_val = nsFontWeights[i];
308 nativeWeightMappings[i].dst_val = i * 100;
309
310 dataProviderWeightMappings[i].src_val = userFontWeights[i];
311 dataProviderWeightMappings[i].dst_val = i * 100;
312 }
313 });
314 static constexpr Interpolator nativeInterpolator(
315 nativeWeightMappings, std::size(nativeWeightMappings));
316 static constexpr Interpolator dataProviderInterpolator(
317 dataProviderWeightMappings, std::size(dataProviderWeightMappings));
318
319 return fromDataProvider ? dataProviderInterpolator.map(cgWeight)
320 : nativeInterpolator.map(cgWeight);
321 }
322
323 /** Convert the [0, 10] CSS weight to [-1, 1] CTFontDescriptor width. */
324 CGFloat SkCTFontCTWidthForCSSWidth(int fontstyleWidth) {
325 using Interpolator = LinearInterpolater<int, CGFloat, CGFloatIdentity>;
326
327 // Values determined by creating font data with every width, creating a CTFont,
328 // and asking the CTFont for its width. See TypefaceStyle test for basics.
329 static constexpr Interpolator::Mapping widthMappings[] = {
330 { 0, -0.5 },
331 { 10, 0.5 },
332 };
333 static constexpr Interpolator interpolator(widthMappings, std::size(widthMappings));
334 return interpolator.map(fontstyleWidth);
335 }
336
337 /** Convert the [-1, 1] CTFontDescriptor width to [0, 10] CSS weight. */
338 static int ct_width_to_fontstyle(CGFloat cgWidth) {
339 using Interpolator = LinearInterpolater<CGFloat, int, RoundCGFloatToInt>;
340
341 // Values determined by creating font data with every width, creating a CTFont,
342 // and asking the CTFont for its width. See TypefaceStyle test for basics.
343 static constexpr Interpolator::Mapping widthMappings[] = {
344 { -0.5, 0 },
345 { 0.5, 10 },
346 };
347 static constexpr Interpolator interpolator(widthMappings, std::size(widthMappings));
348 return interpolator.map(cgWidth);
349 }
350
351 SkFontStyle SkCTFontDescriptorGetSkFontStyle(CTFontDescriptorRef desc, bool fromDataProvider) {
352 SkUniqueCFRef<CFTypeRef> traits(CTFontDescriptorCopyAttribute(desc, kCTFontTraitsAttribute));
353 CFDictionaryRef fontTraitsDict;
354 if (!SkCFDynamicCast(traits.get(), &fontTraitsDict, "Font traits")) {
355 return SkFontStyle();
356 }
357
358 CGFloat weight, width, slant;
359 if (!find_dict_CGFloat(fontTraitsDict, kCTFontWeightTrait, &weight)) {
360 weight = 0;
361 }
362 if (!find_dict_CGFloat(fontTraitsDict, kCTFontWidthTrait, &width)) {
363 width = 0;
364 }
365 if (!find_dict_CGFloat(fontTraitsDict, kCTFontSlantTrait, &slant)) {
366 slant = 0;
367 }
368
369 return SkFontStyle(ct_weight_to_fontstyle(weight, fromDataProvider),
370 ct_width_to_fontstyle(width),
371 slant ? SkFontStyle::kItalic_Slant
372 : SkFontStyle::kUpright_Slant);
373 }
374
375
376 // Web fonts added to the CTFont registry do not return their character set.
377 // Iterate through the font in this case. The existing caller caches the result,
378 // so the performance impact isn't too bad.
379 static void populate_glyph_to_unicode_slow(CTFontRef ctFont, CFIndex glyphCount,
380 SkUnichar* out) {
381 sk_bzero(out, glyphCount * sizeof(SkUnichar));
382 UniChar unichar = 0;
383 while (glyphCount > 0) {
384 CGGlyph glyph;
385 if (CTFontGetGlyphsForCharacters(ctFont, &unichar, &glyph, 1)) {
386 if (out[glyph] == 0) {
387 out[glyph] = unichar;
388 --glyphCount;
389 }
390 }
391 if (++unichar == 0) {
392 break;
393 }
394 }
395 }
396
397 static constexpr uint16_t kPlaneSize = 1 << 13;
398
399 static void get_plane_glyph_map(const uint8_t* bits,
400 CTFontRef ctFont,
401 CFIndex glyphCount,
402 SkUnichar* glyphToUnicode,
403 uint8_t planeIndex) {
404 SkUnichar planeOrigin = (SkUnichar)planeIndex << 16; // top half of codepoint.
405 for (uint16_t i = 0; i < kPlaneSize; i++) {
406 uint8_t mask = bits[i];
407 if (!mask) {
408 continue;
409 }
410 for (uint8_t j = 0; j < 8; j++) {
411 if (0 == (mask & ((uint8_t)1 << j))) {
412 continue;
413 }
414 uint16_t planeOffset = (i << 3) | j;
415 SkUnichar codepoint = planeOrigin | (SkUnichar)planeOffset;
416 uint16_t utf16[2] = {planeOffset, 0};
417 size_t count = 1;
418 if (planeOrigin != 0) {
419 count = SkUTF::ToUTF16(codepoint, utf16);
420 }
421 CGGlyph glyphs[2] = {0, 0};
422 if (CTFontGetGlyphsForCharacters(ctFont, utf16, glyphs, count)) {
423 SkASSERT(glyphs[1] == 0);
424 // CTFontCopyCharacterSet and CTFontGetGlyphsForCharacters seem to add 'support'
425 // for characters 0x9, 0xA, and 0xD mapping them to the glyph for character 0x20?
426 // Prefer mappings to codepoints at or above 0x20.
427 if (glyphs[0] < glyphCount && glyphToUnicode[glyphs[0]] < 0x20) {
428 glyphToUnicode[glyphs[0]] = codepoint;
429 }
430 }
431 }
432 }
433 }
434 // Construct Glyph to Unicode table.
435 static void populate_glyph_to_unicode(CTFontRef ctFont, CFIndex glyphCount,
436 SkUnichar* glyphToUnicode) {
437 sk_bzero(glyphToUnicode, sizeof(SkUnichar) * glyphCount);
438 SkUniqueCFRef<CFCharacterSetRef> charSet(CTFontCopyCharacterSet(ctFont));
439 if (!charSet) {
440 populate_glyph_to_unicode_slow(ctFont, glyphCount, glyphToUnicode);
441 return;
442 }
443
444 SkUniqueCFRef<CFDataRef> bitmap(
445 CFCharacterSetCreateBitmapRepresentation(nullptr, charSet.get()));
446 if (!bitmap) {
447 return;
448 }
449 CFIndex dataLength = CFDataGetLength(bitmap.get());
450 if (!dataLength) {
451 return;
452 }
453 SkASSERT(dataLength >= kPlaneSize);
454 const UInt8* bits = CFDataGetBytePtr(bitmap.get());
455
456 get_plane_glyph_map(bits, ctFont, glyphCount, glyphToUnicode, 0);
457 /*
458 A CFData object that specifies the bitmap representation of the Unicode
459 character points the for the new character set. The bitmap representation could
460 contain all the Unicode character range starting from BMP to Plane 16. The
461 first 8KiB (8192 bytes) of the data represent the BMP range. The BMP range 8KiB
462 can be followed by zero to sixteen 8KiB bitmaps, each prepended with the plane
463 index byte. For example, the bitmap representing the BMP and Plane 2 has the
464 size of 16385 bytes (8KiB for BMP, 1 byte index, and a 8KiB bitmap for Plane
465 2). The plane index byte, in this case, contains the integer value two.
466 */
467
468 if (dataLength <= kPlaneSize) {
469 return;
470 }
471 int extraPlaneCount = (dataLength - kPlaneSize) / (1 + kPlaneSize);
472 SkASSERT(dataLength == kPlaneSize + extraPlaneCount * (1 + kPlaneSize));
473 while (extraPlaneCount-- > 0) {
474 bits += kPlaneSize;
475 uint8_t planeIndex = *bits++;
476 SkASSERT(planeIndex >= 1);
477 SkASSERT(planeIndex <= 16);
478 get_plane_glyph_map(bits, ctFont, glyphCount, glyphToUnicode, planeIndex);
479 }
480 }
481
482 void SkTypeface_Mac::getGlyphToUnicodeMap(SkSpan<SkUnichar> dstArray) const {
483 SkUniqueCFRef<CTFontRef> ctFont =
484 SkCTFontCreateExactCopy(fFontRef.get(), CTFontGetUnitsPerEm(fFontRef.get()),
485 fOpszVariation);
486 CFIndex glyphCount = std::min((size_t)CTFontGetGlyphCount(ctFont.get()), dstArray.size());
487 populate_glyph_to_unicode(ctFont.get(), glyphCount, dstArray.data());
488 }
489
490 std::unique_ptr<SkAdvancedTypefaceMetrics> SkTypeface_Mac::onGetAdvancedMetrics() const {
491
492 SkUniqueCFRef<CTFontRef> ctFont =
493 SkCTFontCreateExactCopy(fFontRef.get(), CTFontGetUnitsPerEm(fFontRef.get()),
494 fOpszVariation);
495
496 std::unique_ptr<SkAdvancedTypefaceMetrics> info(new SkAdvancedTypefaceMetrics);
497
498 CFArrayRef ctAxes = this->getVariationAxes();
499 if (ctAxes && CFArrayGetCount(ctAxes) > 0) {
500 info->fFlags |= SkAdvancedTypefaceMetrics::kVariable_FontFlag;
501 }
502
503 SkOTTableOS2_V4::Type fsType;
504 if (sizeof(fsType) == this->getTableData(SkTEndian_SwapBE32(SkOTTableOS2::TAG),
505 offsetof(SkOTTableOS2_V4, fsType),
506 sizeof(fsType),
507 &fsType)) {
508 SkOTUtils::SetAdvancedTypefaceFlags(fsType, info.get());
509 }
510
511 // If it's not an OpenType font, mark it as 'other'. Assume that OpenType
512 // fonts always have both glyf and loca tables or a CFF table.
513 // At the least, this is what is needed to subset the font.
514 // CTFontCopyAttribute() does not always succeed in determining this directly.
515 constexpr SkFontTableTag glyf = SkSetFourByteTag('g','l','y','f');
516 constexpr SkFontTableTag loca = SkSetFourByteTag('l','o','c','a');
517 constexpr SkFontTableTag CFF = SkSetFourByteTag('C','F','F',' ');
518 if (this->getTableSize(glyf) && this->getTableSize(loca)) {
519 info->fType = SkAdvancedTypefaceMetrics::kTrueType_Font;
520 } else if (this->getTableSize(CFF)) {
521 info->fType = SkAdvancedTypefaceMetrics::kCFF_Font;
522 } else {
523 return info;
524 }
525
526 CTFontSymbolicTraits symbolicTraits = CTFontGetSymbolicTraits(ctFont.get());
527 if (symbolicTraits & kCTFontMonoSpaceTrait) {
528 info->fStyle |= SkAdvancedTypefaceMetrics::kFixedPitch_Style;
529 }
530 if (symbolicTraits & kCTFontItalicTrait) {
531 info->fStyle |= SkAdvancedTypefaceMetrics::kItalic_Style;
532 }
533 CTFontStylisticClass stylisticClass = symbolicTraits & kCTFontClassMaskTrait;
534 if (stylisticClass >= kCTFontOldStyleSerifsClass && stylisticClass <= kCTFontSlabSerifsClass) {
535 info->fStyle |= SkAdvancedTypefaceMetrics::kSerif_Style;
536 } else if (stylisticClass & kCTFontScriptsClass) {
537 info->fStyle |= SkAdvancedTypefaceMetrics::kScript_Style;
538 }
539 info->fItalicAngle = (int16_t) CTFontGetSlantAngle(ctFont.get());
540 info->fAscent = (int16_t) CTFontGetAscent(ctFont.get());
541 info->fDescent = (int16_t) CTFontGetDescent(ctFont.get());
542 info->fCapHeight = (int16_t) CTFontGetCapHeight(ctFont.get());
543 CGRect bbox = CTFontGetBoundingBox(ctFont.get());
544
545 SkRect r;
546 r.setLTRB(SkScalarFromCGFloat(SkCGRectGetMinX(bbox)), // Left
547 SkScalarFromCGFloat(SkCGRectGetMaxY(bbox)), // Top
548 SkScalarFromCGFloat(SkCGRectGetMaxX(bbox)), // Right
549 SkScalarFromCGFloat(SkCGRectGetMinY(bbox))); // Bottom
550
551 r.roundOut(&(info->fBBox));
552
553 // Figure out a good guess for StemV - Min width of i, I, !, 1.
554 // This probably isn't very good with an italic font.
555 int16_t min_width = SHRT_MAX;
556 info->fStemV = 0;
557 static const UniChar stem_chars[] = {'i', 'I', '!', '1'};
558 const size_t count = sizeof(stem_chars) / sizeof(stem_chars[0]);
559 CGGlyph glyphs[count];
560 CGRect boundingRects[count];
561 if (CTFontGetGlyphsForCharacters(ctFont.get(), stem_chars, glyphs, count)) {
562 CTFontGetBoundingRectsForGlyphs(ctFont.get(), kCTFontOrientationHorizontal,
563 glyphs, boundingRects, count);
564 for (size_t i = 0; i < count; i++) {
565 int16_t width = (int16_t) boundingRects[i].size.width;
566 if (width > 0 && width < min_width) {
567 min_width = width;
568 info->fStemV = min_width;
569 }
570 }
571 }
572 return info;
573 }
574
575 static SK_SFNT_ULONG get_font_type_tag(CTFontRef ctFont) {
576 SkUniqueCFRef<CFNumberRef> fontFormatRef(
577 static_cast<CFNumberRef>(CTFontCopyAttribute(ctFont, kCTFontFormatAttribute)));
578 if (!fontFormatRef) {
579 return 0;
580 }
581
582 SInt32 fontFormatValue;
583 if (!CFNumberGetValue(fontFormatRef.get(), kCFNumberSInt32Type, &fontFormatValue)) {
584 return 0;
585 }
586
587 switch (fontFormatValue) {
588 case kCTFontFormatOpenTypePostScript:
589 return SkSFNTHeader::fontType_OpenTypeCFF::TAG;
590 case kCTFontFormatOpenTypeTrueType:
591 return SkSFNTHeader::fontType_WindowsTrueType::TAG;
592 case kCTFontFormatTrueType:
593 return SkSFNTHeader::fontType_MacTrueType::TAG;
594 case kCTFontFormatPostScript:
595 return SkSFNTHeader::fontType_PostScript::TAG;
596 case kCTFontFormatBitmap:
597 return SkSFNTHeader::fontType_MacTrueType::TAG;
598 case kCTFontFormatUnrecognized:
599 default:
600 return 0;
601 }
602 }
603
604 std::unique_ptr<SkStreamAsset> SkTypeface_Mac::onOpenStream(int* ttcIndex) const {
605 *ttcIndex = 0;
606
•607 SkAutoSharedMutexExclusive sm(fStreamMutex);
608 if (fStream) {
•609 return fStream->duplicate();
610 }
611
612 SK_SFNT_ULONG fontType = get_font_type_tag(fFontRef.get());
613
614 // get table tags
615 int numTables = this->countTables();
616 SkTDArray<SkFontTableTag> tableTags;
617 tableTags.resize(numTables);
618 this->readTableTags(tableTags);
619
620 // CT seems to be unreliable in being able to obtain the type,
621 // even if all we want is the first four bytes of the font resource.
622 // Just the presence of the FontForge 'FFTM' table seems to throw it off.
623 if (fontType == 0) {
624 fontType = SkSFNTHeader::fontType_WindowsTrueType::TAG;
625
626 // see https://skbug.com/40038881#c7
627 bool couldBeCFF = false;
628 constexpr SkFontTableTag CFFTag = SkSetFourByteTag('C', 'F', 'F', ' ');
629 constexpr SkFontTableTag CFF2Tag = SkSetFourByteTag('C', 'F', 'F', '2');
630 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
631 if (CFFTag == tableTags[tableIndex] || CFF2Tag == tableTags[tableIndex]) {
632 couldBeCFF = true;
633 }
634 }
635 if (couldBeCFF) {
636 fontType = SkSFNTHeader::fontType_OpenTypeCFF::TAG;
637 }
638 }
639
640 // Sometimes CoreGraphics incorrectly thinks a font is kCTFontFormatPostScript.
641 // It is exceedingly unlikely that this is the case, so double check
642 // (see https://crbug.com/809763 ).
643 if (fontType == SkSFNTHeader::fontType_PostScript::TAG) {
644 // see if there are any required 'typ1' tables (see Adobe Technical Note #5180)
645 bool couldBeTyp1 = false;
646 constexpr SkFontTableTag TYPE1Tag = SkSetFourByteTag('T', 'Y', 'P', '1');
647 constexpr SkFontTableTag CIDTag = SkSetFourByteTag('C', 'I', 'D', ' ');
648 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
649 if (TYPE1Tag == tableTags[tableIndex] || CIDTag == tableTags[tableIndex]) {
650 couldBeTyp1 = true;
651 }
652 }
653 if (!couldBeTyp1) {
654 fontType = SkSFNTHeader::fontType_OpenTypeCFF::TAG;
655 }
656 }
657
658 // get the table sizes and accumulate the total size of the font
659 SkTDArray<size_t> tableSizes;
660 size_t totalSize = sizeof(SkSFNTHeader) + sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
661 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
662 size_t tableSize = this->getTableSize(tableTags[tableIndex]);
663 totalSize += (tableSize + 3) & ~3;
664 *tableSizes.append() = tableSize;
665 }
666
667 // reserve memory for stream, and zero it (tables must be zero padded)
668 sk_sp<SkData> streamData = SkData::MakeZeroInitialized(totalSize);
669 char* dataStart = (char*)streamData->writable_data();
670 char* dataPtr = dataStart;
671
672 // compute font header entries
673 uint16_t entrySelector = 0;
674 uint16_t searchRange = 1;
675 while (searchRange < numTables >> 1) {
676 entrySelector++;
677 searchRange <<= 1;
678 }
679 searchRange <<= 4;
680 uint16_t rangeShift = (numTables << 4) - searchRange;
681
682 // write font header
683 SkSFNTHeader* header = (SkSFNTHeader*)dataPtr;
684 header->fontType = fontType;
685 header->numTables = SkEndian_SwapBE16(numTables);
686 header->searchRange = SkEndian_SwapBE16(searchRange);
687 header->entrySelector = SkEndian_SwapBE16(entrySelector);
688 header->rangeShift = SkEndian_SwapBE16(rangeShift);
689 dataPtr += sizeof(SkSFNTHeader);
690
691 // write tables
692 SkSFNTHeader::TableDirectoryEntry* entry = (SkSFNTHeader::TableDirectoryEntry*)dataPtr;
693 dataPtr += sizeof(SkSFNTHeader::TableDirectoryEntry) * numTables;
694 for (int tableIndex = 0; tableIndex < numTables; ++tableIndex) {
695 size_t tableSize = tableSizes[tableIndex];
696 this->getTableData(tableTags[tableIndex], 0, tableSize, dataPtr);
697 entry->tag = SkEndian_SwapBE32(tableTags[tableIndex]);
698 entry->checksum = SkEndian_SwapBE32(SkOTUtils::CalcTableChecksum((SK_OT_ULONG*)dataPtr,
699 tableSize));
700 entry->offset = SkEndian_SwapBE32(SkToU32(dataPtr - dataStart));
701 entry->logicalLength = SkEndian_SwapBE32(SkToU32(tableSize));
702
703 dataPtr += (tableSize + 3) & ~3;
704 ++entry;
705 }
706 fStream = std::make_unique<SkMemoryStream>(std::move(streamData));
707 return fStream->duplicate();
708 }
709
710 std::unique_ptr<SkStreamAsset> SkTypeface_Mac::onOpenExistingStream(int* ttcIndex) const {
711 *ttcIndex = 0;
•712 SkAutoSharedMutexShared sm(fStreamMutex);
713 return fStream ? fStream->duplicate() : nullptr;
714 }
715
716 bool SkTypeface_Mac::onGlyphMaskNeedsCurrentColor() const {
717 // `CPAL` (`COLR` and `SVG`) fonts may need the current color.
718 // However, even `sbix` fonts can have glyphs which need the current color.
719 // These may be glyphs with paths but no `sbix` entries, which are impossible to distinguish.
720 return this->fHasColorGlyphs;
721 }
722
723 CFArrayRef SkTypeface_Mac::getVariationAxes() const {
724 fInitVariationAxes([this]{
725 // Prefer kCTFontVariationAxesAttribute, faster since it doesn't localize axis names.
726 SkUniqueCFRef<CTFontDescriptorRef> desc(CTFontCopyFontDescriptor(fFontRef.get()));
727 SkUniqueCFRef<CFTypeRef> cf(
728 CTFontDescriptorCopyAttribute(desc.get(), kCTFontVariationAxesAttribute));
729 CFArrayRef array;
730 if (cf && SkCFDynamicCast(cf.get(), &array, "Axes")) {
731 fVariationAxes.reset(array);
732 cf.release();
733 return;
734 }
735 fVariationAxes.reset(CTFontCopyVariationAxes(fFontRef.get()));
736 });
737 return fVariationAxes.get();
738 }
739
740 int SkTypeface_Mac::onGetVariationDesignPosition(
741 SkSpan<SkFontArguments::VariationPosition::Coordinate> coordinates) const
742 {
743 CFArrayRef ctAxes = this->getVariationAxes();
744 if (!ctAxes) {
745 return -1;
746 }
747 CFIndex axisCount = CFArrayGetCount(ctAxes);
748 if (coordinates.size() < (size_t)axisCount) {
749 return axisCount;
750 }
751
752 // On 10.12 and later, this only returns non-default variations.
753 SkUniqueCFRef<CFDictionaryRef> ctVariation(CTFontCopyVariation(fFontRef.get()));
754 if (!ctVariation) {
755 return -1;
756 }
757
758 for (int i = 0; i < axisCount; ++i) {
759 CFDictionaryRef axisInfoDict;
760 if (!SkCFDynamicCast(CFArrayGetValueAtIndex(ctAxes, i), &axisInfoDict, "Axis")) {
761 return -1;
762 }
763
764 int64_t tagLong;
765 CFNumberRef tagNumber;
766 CFTypeRef tag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
767 if (!SkCFNumberDynamicCast(tag, &tagLong, &tagNumber, "Axis tag")) {
768 return -1;
769 }
770 coordinates[i].axis = tagLong;
771
772 CGFloat valueCGFloat;
773 CFTypeRef value = CFDictionaryGetValue(ctVariation.get(), tagNumber);
774 if (value) {
775 if (!SkCFNumberDynamicCast(value, &valueCGFloat, nullptr, "Variation value")) {
776 return -1;
777 }
778 } else {
779 CFTypeRef def = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisDefaultValueKey);
780 if (!SkCFNumberDynamicCast(def, &valueCGFloat, nullptr, "Axis default value")) {
781 return -1;
782 }
783 }
784 coordinates[i].value = SkScalarFromCGFloat(valueCGFloat);
785 }
786 return axisCount;
787 }
788
789 int SkTypeface_Mac::onGetUPEM() const {
790 SkUniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(fFontRef.get(), nullptr));
791 return CGFontGetUnitsPerEm(cgFont.get());
792 }
793
794 SkTypeface::LocalizedStrings* SkTypeface_Mac::onCreateFamilyNameIterator() const {
795 sk_sp<SkTypeface::LocalizedStrings> nameIter =
796 SkOTUtils::LocalizedStrings_NameTable::MakeForFamilyNames(*this);
797 if (!nameIter) {
798 CFStringRef cfLanguageRaw;
799 SkUniqueCFRef<CFStringRef> cfFamilyName(
800 CTFontCopyLocalizedName(fFontRef.get(), kCTFontFamilyNameKey, &cfLanguageRaw));
801 SkUniqueCFRef<CFStringRef> cfLanguage(cfLanguageRaw);
802
803 SkString skLanguage;
804 SkString skFamilyName;
805 if (cfLanguage) {
806 SkStringFromCFString(cfLanguage.get(), &skLanguage);
807 } else {
808 skLanguage = "und"; //undetermined
809 }
810 if (cfFamilyName) {
811 SkStringFromCFString(cfFamilyName.get(), &skFamilyName);
812 }
813
814 nameIter = sk_make_sp<SkOTUtils::LocalizedStrings_SingleName>(skFamilyName, skLanguage);
815 }
816 return nameIter.release();
817 }
818
819 int SkTypeface_Mac::onGetTableTags(SkSpan<SkFontTableTag> tags) const {
820 SkUniqueCFRef<CFArrayRef> cfArray(
821 CTFontCopyAvailableTables(fFontRef.get(), kCTFontTableOptionNoOptions));
822 if (!cfArray) {
823 return 0;
824 }
825 const CFIndex count = CFArrayGetCount(cfArray.get());
826 const CFIndex n = std::min(count, (CFIndex)tags.size());
827 for (CFIndex i = 0; i < n; ++i) {
828 uintptr_t fontTag = reinterpret_cast<uintptr_t>(
829 CFArrayGetValueAtIndex(cfArray.get(), i));
830 tags[i] = static_cast<SkFontTableTag>(fontTag);
831 }
832 return count;
833 }
834
835 // If, as is the case with web fonts, the CTFont data isn't available,
836 // the CGFont data may work. While the CGFont may always provide the
837 // right result, leave the CTFont code path to minimize disruption.
838 static SkUniqueCFRef<CFDataRef> copy_table_from_font(CTFontRef ctFont, SkFontTableTag tag) {
839 SkUniqueCFRef<CFDataRef> data(CTFontCopyTable(ctFont, (CTFontTableTag) tag,
840 kCTFontTableOptionNoOptions));
841 if (!data) {
842 SkUniqueCFRef<CGFontRef> cgFont(CTFontCopyGraphicsFont(ctFont, nullptr));
843 data.reset(CGFontCopyTableForTag(cgFont.get(), tag));
844 }
845 return data;
846 }
847
848 size_t SkTypeface_Mac::onGetTableData(SkFontTableTag tag, size_t offset,
849 size_t length, void* dstData) const {
850 SkUniqueCFRef<CFDataRef> srcData = copy_table_from_font(fFontRef.get(), tag);
851 if (!srcData) {
852 return 0;
853 }
854
855 size_t srcSize = CFDataGetLength(srcData.get());
856 if (offset >= srcSize) {
857 return 0;
858 }
859 if (length > srcSize - offset) {
860 length = srcSize - offset;
861 }
862 if (dstData) {
863 memcpy(dstData, CFDataGetBytePtr(srcData.get()) + offset, length);
864 }
865 return length;
866 }
867
868 sk_sp<SkData> SkTypeface_Mac::onCopyTableData(SkFontTableTag tag) const {
869 SkUniqueCFRef<CFDataRef> srcData = copy_table_from_font(fFontRef.get(), tag);
870 if (!srcData) {
871 return nullptr;
872 }
873 const UInt8* data = CFDataGetBytePtr(srcData.get());
874 CFIndex length = CFDataGetLength(srcData.get());
875 return SkData::MakeWithProc(data, length,
876 [](const void*, void* ctx) {
877 CFRelease((CFDataRef)ctx);
878 }, (void*)srcData.release());
879 }
880
881 std::unique_ptr<SkScalerContext> SkTypeface_Mac::onCreateScalerContext(
882 const SkScalerContextEffects& effects, const SkDescriptor* desc) const
883 {
884 return std::make_unique<SkScalerContext_Mac>(*const_cast<SkTypeface_Mac*>(this), effects, desc);
885 }
886
887 void SkTypeface_Mac::onFilterRec(SkScalerContextRec* rec) const {
888 rec->useStrokeForFakeBold();
889
890 if (rec->fFlags & SkScalerContext::kLCD_BGROrder_Flag ||
891 rec->fFlags & SkScalerContext::kLCD_Vertical_Flag)
892 {
893 rec->fMaskFormat = SkMask::kA8_Format;
894 // Render the glyphs as close as possible to what was requested.
895 // The above turns off subpixel rendering, but the user requested it.
896 // Normal hinting will cause the A8 masks to be generated from CoreGraphics subpixel masks.
897 // See comments below for more details.
898 rec->setHinting(SkFontHinting::kNormal);
899 }
900
901 unsigned flagsWeDontSupport = SkScalerContext::kForceAutohinting_Flag |
902 SkScalerContext::kLCD_BGROrder_Flag |
903 SkScalerContext::kLCD_Vertical_Flag;
904
905 rec->fFlags &= ~flagsWeDontSupport;
906
907 const SkCTFontSmoothBehavior smoothBehavior = SkCTFontGetSmoothBehavior();
908
909 // Only two levels of hinting are supported.
910 // kNo_Hinting means avoid CoreGraphics outline dilation (smoothing).
911 // kNormal_Hinting means CoreGraphics outline dilation (smoothing) is allowed.
912 if (rec->getHinting() != SkFontHinting::kNone) {
913 rec->setHinting(SkFontHinting::kNormal);
914 }
915 // If smoothing has no effect, don't request it.
916 if (smoothBehavior == SkCTFontSmoothBehavior::none) {
917 rec->setHinting(SkFontHinting::kNone);
918 }
919
920 // FIXME: lcd smoothed un-hinted rasterization unsupported.
921 // Tracked by http://code.google.com/p/skia/issues/detail?id=915 .
922 // There is no current means to honor a request for unhinted lcd,
923 // so arbitrarilly ignore the hinting request and honor lcd.
924
925 // Hinting and smoothing should be orthogonal, but currently they are not.
926 // CoreGraphics has no API to influence hinting. However, its lcd smoothed
927 // output is drawn from auto-dilated outlines (the amount of which is
928 // determined by AppleFontSmoothing). Its regular anti-aliased output is
929 // drawn from un-dilated outlines.
930
931 // The behavior of Skia is as follows:
932 // [AA][no-hint]: generate AA using CoreGraphic's AA output.
933 // [AA][yes-hint]: use CoreGraphic's LCD output and reduce it to a single
934 // channel. This matches [LCD][yes-hint] in weight.
935 // [LCD][no-hint]: currently unable to honor, and must pick which to respect.
936 // Currently side with LCD, effectively ignoring the hinting setting.
937 // [LCD][yes-hint]: generate LCD using CoreGraphic's LCD output.
938 if (rec->fMaskFormat == SkMask::kLCD16_Format) {
939 if (smoothBehavior == SkCTFontSmoothBehavior::subpixel) {
940 //CoreGraphics creates 555 masks for smoothed text anyway.
941 rec->fMaskFormat = SkMask::kLCD16_Format;
942 rec->setHinting(SkFontHinting::kNormal);
943 } else {
944 rec->fMaskFormat = SkMask::kA8_Format;
945 if (smoothBehavior != SkCTFontSmoothBehavior::none) {
946 rec->setHinting(SkFontHinting::kNormal);
947 }
948 }
949 }
950
951 // CoreText provides no information as to whether a glyph will be color or not.
952 // Fonts may mix outlines and bitmaps, so information is needed on a glyph by glyph basis.
953 // If a font contains an 'sbix' table, consider it to be a color font, and disable lcd.
954 if (fHasColorGlyphs) {
955 rec->fMaskFormat = SkMask::kARGB32_Format;
956 }
957
958 // Unhinted A8 masks (those not derived from LCD masks) must respect SK_GAMMA_APPLY_TO_A8.
959 // All other masks can use regular gamma.
960 if (SkMask::kA8_Format == rec->fMaskFormat && SkFontHinting::kNone == rec->getHinting()) {
961 #ifndef SK_GAMMA_APPLY_TO_A8
962 // SRGBTODO: Is this correct? Do we want contrast boost?
963 rec->ignorePreBlend();
964 #endif
965 } else {
966 SkColor color = rec->getLuminanceColor();
967 if (smoothBehavior == SkCTFontSmoothBehavior::some) {
968 // CoreGraphics smoothed text without subpixel coverage blitting goes from a gamma of
969 // 2.0 for black foreground to a gamma of 1.0 for white foreground. Emulate this
970 // through the mask gamma by reducing the color values to 1/2.
971 color = SkColorSetRGB(SkColorGetR(color) * 1/2,
972 SkColorGetG(color) * 1/2,
973 SkColorGetB(color) * 1/2);
974 } else if (smoothBehavior == SkCTFontSmoothBehavior::subpixel) {
975 // CoreGraphics smoothed text with subpixel coverage blitting goes from a gamma of
976 // 2.0 for black foreground to a gamma of ~1.4? for white foreground. Emulate this
977 // through the mask gamma by reducing the color values to 3/4.
978 color = SkColorSetRGB(SkColorGetR(color) * 3/4,
979 SkColorGetG(color) * 3/4,
980 SkColorGetB(color) * 3/4);
981 }
982 rec->setLuminanceColor(color);
983
984 // CoreGraphics dialates smoothed text to provide contrast.
985 rec->setContrast(0);
986 }
987 }
988
989 /** Takes ownership of the CFStringRef. */
990 static const char* get_str(CFStringRef ref, SkString* str) {
991 if (nullptr == ref) {
992 return nullptr;
993 }
994 SkStringFromCFString(ref, str);
995 CFRelease(ref);
996 return str->c_str();
997 }
998
999 void SkTypeface_Mac::onGetFamilyName(SkString* familyName) const {
1000 get_str(CTFontCopyFamilyName(fFontRef.get()), familyName);
1001 }
1002
1003 bool SkTypeface_Mac::onGetPostScriptName(SkString* skPostScriptName) const {
1004 SkUniqueCFRef<CFStringRef> ctPostScriptName(CTFontCopyPostScriptName(fFontRef.get()));
1005 if (!ctPostScriptName) {
1006 return false;
1007 }
1008 if (skPostScriptName) {
1009 SkStringFromCFString(ctPostScriptName.get(), skPostScriptName);
1010 }
1011 return true;
1012 }
1013
1014 void SkTypeface_Mac::onGetFontDescriptor(SkFontDescriptor* desc,
1015 bool* isLocalStream) const {
1016 SkString tmpStr;
1017
1018 desc->setFamilyName(get_str(CTFontCopyFamilyName(fFontRef.get()), &tmpStr));
1019 desc->setFullName(get_str(CTFontCopyFullName(fFontRef.get()), &tmpStr));
1020 desc->setPostscriptName(get_str(CTFontCopyPostScriptName(fFontRef.get()), &tmpStr));
1021 desc->setStyle(this->fontStyle());
1022 desc->setFactoryId(FactoryId);
1023 *isLocalStream = fIsFromStream;
1024 }
1025
1026 void SkTypeface_Mac::onCharsToGlyphs(SkSpan<const SkUnichar> uni, SkSpan<SkGlyphID> glyphs) const {
1027 SkASSERT(uni.size() == glyphs.size());
1028 const int count = SkToInt(uni.size());
1029
1030 // Undocumented behavior of CTFontGetGlyphsForCharacters with non-bmp code points:
1031 // When a surrogate pair is detected, the glyph index used is the index of the high surrogate.
1032 // It is documented that if a mapping is unavailable, the glyph will be set to 0.
1033
1034 AutoSTMalloc<1024, UniChar> charStorage;
1035 const UniChar* src; // UniChar is a UTF-16 16-bit code unit.
1036 int srcCount;
1037 const SkUnichar* utf32 = uni.data();
1038 UniChar* utf16 = charStorage.reset(2 * count);
1039 src = utf16;
1040 for (int i = 0; i < count; ++i) {
1041 utf16 += SkUTF::ToUTF16(utf32[i], utf16);
1042 }
1043 srcCount = SkToInt(utf16 - src);
1044
1045 // If there are any non-bmp code points, the provided 'glyphs' storage will be inadequate.
1046 AutoSTMalloc<1024, uint16_t> glyphStorage;
1047 uint16_t* macGlyphs = glyphs.data();
1048 if (srcCount > count) {
1049 macGlyphs = glyphStorage.reset(srcCount);
1050 }
1051
1052 CTFontGetGlyphsForCharacters(fFontRef.get(), src, macGlyphs, srcCount);
1053
1054 // If there were any non-bmp, then copy and compact.
1055 // If all are bmp, 'glyphs' already contains the compact glyphs.
1056 // If some are non-bmp, copy and compact into 'glyphs'.
1057 if (srcCount > count) {
1058 SkASSERT(glyphs.data() != macGlyphs);
1059 int extra = 0;
1060 for (int i = 0; i < count; ++i) {
1061 glyphs[i] = macGlyphs[i + extra];
1062 if (SkUTF::IsLeadingSurrogateUTF16(src[i + extra])) {
1063 ++extra;
1064 }
1065 }
1066 } else {
1067 SkASSERT(glyphs.data() == macGlyphs);
1068 }
1069 }
1070
1071 int SkTypeface_Mac::onCountGlyphs() const {
1072 return SkToInt(CTFontGetGlyphCount(fFontRef.get()));
1073 }
1074
1075 /** Creates a dictionary suitable for setting the axes on a CTFont. */
1076 static CTFontVariation ctvariation_from_SkFontArguments(CTFontRef ct, CFArrayRef ctAxes,
1077 const SkFontArguments& args) {
1078 OpszVariation opsz;
1079 constexpr const SkFourByteTag opszTag = SkSetFourByteTag('o','p','s','z');
1080
1081 if (!ctAxes) {
1082 return CTFontVariation();
1083 }
1084 CFIndex axisCount = CFArrayGetCount(ctAxes);
1085
1086 // On 10.12 and later, this only returns non-default variations.
1087 SkUniqueCFRef<CFDictionaryRef> oldCtVariation(CTFontCopyVariation(ct));
1088
1089 const SkFontArguments::VariationPosition position = args.getVariationDesignPosition();
1090
1091 SkUniqueCFRef<CFMutableDictionaryRef> newCtVariation(
1092 CFDictionaryCreateMutable(kCFAllocatorDefault, axisCount,
1093 &kCFTypeDictionaryKeyCallBacks,
1094 &kCFTypeDictionaryValueCallBacks));
1095 SkUniqueCFRef<CFMutableDictionaryRef> wrongOpszVariation;
1096
1097 for (int i = 0; i < axisCount; ++i) {
1098 CFDictionaryRef axisInfoDict;
1099 if (!SkCFDynamicCast(CFArrayGetValueAtIndex(ctAxes, i), &axisInfoDict, "Axis")) {
1100 return CTFontVariation();
1101 }
1102
1103 int64_t tagLong;
1104 CFNumberRef tagNumber;
1105 CFTypeRef tag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
1106 if (!SkCFNumberDynamicCast(tag, &tagLong, &tagNumber, "Axis tag")) {
1107 return CTFontVariation();
1108 }
1109
1110 // The variation axes can be set to any value, but cg will effectively pin them.
1111 // Pin them here to normalize.
1112 double minDouble;
1113 double maxDouble;
1114 double defDouble;
1115 CFTypeRef min = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMinimumValueKey);
1116 CFTypeRef max = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMaximumValueKey);
1117 CFTypeRef def = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisDefaultValueKey);
1118 if (!SkCFNumberDynamicCast(min, &minDouble, nullptr, "Axis min") ||
1119 !SkCFNumberDynamicCast(max, &maxDouble, nullptr, "Axis max") ||
1120 !SkCFNumberDynamicCast(def, &defDouble, nullptr, "Axis def"))
1121 {
1122 return CTFontVariation();
1123 }
1124
1125 // Start with the default value.
1126 double value = defDouble;
1127
1128 // Then the current value.
1129 bool haveCurrentDouble = false;
1130 double currentDouble = 0;
1131 if (oldCtVariation) {
1132 CFTypeRef currentNumber = CFDictionaryGetValue(oldCtVariation.get(), tagNumber);
1133 if (currentNumber) {
1134 if (!SkCFNumberDynamicCast(currentNumber, &value, nullptr, "Variation value")) {
1135 return CTFontVariation();
1136 }
1137 currentDouble = value;
1138 haveCurrentDouble = true;
1139 }
1140 }
1141
1142 // Then the requested value.
1143 // The position may be over specified. If there are multiple values for a given axis,
1144 // use the last one since that's what css-fonts-4 requires.
1145 for (int j = position.coordinateCount; j --> 0;) {
1146 if (position.coordinates[j].axis == tagLong) {
1147 value = SkTPin<double>(position.coordinates[j].value, minDouble, maxDouble);
1148 if (tagLong == opszTag) {
1149 opsz.isSet = true;
1150 }
1151 break;
1152 }
1153 }
1154 if (tagLong == opszTag) {
1155 opsz.value = value;
1156 if (haveCurrentDouble && value == currentDouble) {
1157 // Calculate a value strictly in range but different from currentValue.
1158 double wrongOpszDouble = ((maxDouble - minDouble) / 2.0) + minDouble;
1159 if (wrongOpszDouble == currentDouble) {
1160 wrongOpszDouble = ((maxDouble - minDouble) / 4.0) + minDouble;
1161 }
1162 wrongOpszVariation.reset(
1163 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
1164 &kCFTypeDictionaryKeyCallBacks,
1165 &kCFTypeDictionaryValueCallBacks));
1166 SkUniqueCFRef<CFNumberRef> wrongOpszNumber(
1167 CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &wrongOpszDouble));
1168 CFDictionarySetValue(wrongOpszVariation.get(), tagNumber, wrongOpszNumber.get());
1169 }
1170 }
1171 SkUniqueCFRef<CFNumberRef> valueNumber(
1172 CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value));
1173 CFDictionaryAddValue(newCtVariation.get(), tagNumber, valueNumber.get());
1174 }
1175 return { SkUniqueCFRef<CFDictionaryRef>(std::move(newCtVariation)),
1176 SkUniqueCFRef<CFDictionaryRef>(std::move(wrongOpszVariation)),
1177 opsz };
1178 }
1179
1180 sk_sp<SkTypeface> SkTypeface_Mac::onMakeClone(const SkFontArguments& args) const {
1181 CTFontVariation ctVariation = ctvariation_from_SkFontArguments(fFontRef.get(),
1182 this->getVariationAxes(),
1183 args);
1184
1185 SkUniqueCFRef<CTFontRef> ctVariant;
1186 if (ctVariation.variation) {
1187 SkUniqueCFRef<CFMutableDictionaryRef> attributes(
1188 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
1189 &kCFTypeDictionaryKeyCallBacks,
1190 &kCFTypeDictionaryValueCallBacks));
1191
1192 CTFontRef ctFont = fFontRef.get();
1193 SkUniqueCFRef<CTFontRef> wrongOpszFont;
1194 if (ctVariation.wrongOpszVariation) {
1195 // On macOS 11 cloning a system font with an opsz axis and not changing the
1196 // value of the opsz axis (either by setting it to the same value or not
1197 // specifying it at all) when setting a variation causes the variation to
1198 // be set but the cloned font will still compare CFEqual to the original
1199 // font. Work around this by setting the opsz to something which isn't the
1200 // desired value before setting the entire desired variation.
1201 //
1202 // A similar issue occurs with fonts from data on macOS 10.15 and the same
1203 // work around seems to apply. This is less noticeable though since CFEqual
1204 // isn't used on these fonts.
1205 CFDictionarySetValue(attributes.get(),
1206 kCTFontVariationAttribute, ctVariation.wrongOpszVariation.get());
1207 SkUniqueCFRef<CTFontDescriptorRef> varDesc(
1208 CTFontDescriptorCreateWithAttributes(attributes.get()));
1209 wrongOpszFont.reset(CTFontCreateCopyWithAttributes(ctFont, 0, nullptr, varDesc.get()));
1210 ctFont = wrongOpszFont.get();
1211 }
1212
1213 CFDictionarySetValue(attributes.get(),
1214 kCTFontVariationAttribute, ctVariation.variation.get());
1215 SkUniqueCFRef<CTFontDescriptorRef> varDesc(
1216 CTFontDescriptorCreateWithAttributes(attributes.get()));
1217 ctVariant.reset(CTFontCreateCopyWithAttributes(ctFont, 0, nullptr, varDesc.get()));
1218 } else {
1219 ctVariant.reset((CTFontRef)CFRetain(fFontRef.get()));
1220 }
1221 if (!ctVariant) {
1222 return nullptr;
1223 }
•1224 SkAutoSharedMutexShared sm(fStreamMutex);
1225 return SkTypeface_Mac::Make(std::move(ctVariant), ctVariation.opsz,
1226 fStream ? fStream->duplicate() : nullptr);
1227 }
1228
1229 static sk_sp<SkData> skdata_from_skstreamasset(std::unique_ptr<SkStreamAsset> stream) {
1230 size_t size = stream->getLength();
1231 if (const void* base = stream->getMemoryBase()) {
1232 return SkData::MakeWithProc(base, size,
1233 [](const void*, void* ctx) -> void {
1234 delete (SkStreamAsset*)ctx;
1235 }, stream.release());
1236 }
1237 return SkData::MakeFromStream(stream.get(), size);
1238 }
1239
1240 static SkUniqueCFRef<CFDataRef> cfdata_from_skdata(sk_sp<SkData> data) {
1241 void const * const addr = data->data();
1242 size_t const size = data->size();
1243
1244 CFAllocatorContext ctx = {
1245 0, // CFIndex version
1246 data.release(), // void* info
1247 nullptr, // const void *(*retain)(const void *info);
1248 nullptr, // void (*release)(const void *info);
1249 nullptr, // CFStringRef (*copyDescription)(const void *info);
1250 nullptr, // void * (*allocate)(CFIndex size, CFOptionFlags hint, void *info);
1251 nullptr, // void*(*reallocate)(void* ptr,CFIndex newsize,CFOptionFlags hint,void* info);
1252 [](void*,void* info) -> void { // void (*deallocate)(void *ptr, void *info);
1253 SkASSERT(info);
1254 ((SkData*)info)->unref();
1255 },
1256 nullptr, // CFIndex (*preferredSize)(CFIndex size, CFOptionFlags hint, void *info);
1257 };
1258 SkUniqueCFRef<CFAllocatorRef> alloc(CFAllocatorCreate(kCFAllocatorDefault, &ctx));
1259 return SkUniqueCFRef<CFDataRef>(CFDataCreateWithBytesNoCopy(
1260 kCFAllocatorDefault, (const UInt8 *)addr, size, alloc.get()));
1261 }
1262
1263 static SkUniqueCFRef<CTFontRef> ctfont_from_skdata(sk_sp<SkData> data, int ttcIndex) {
1264 // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available.
1265 if (ttcIndex != 0) {
1266 return nullptr;
1267 }
1268
1269 SkUniqueCFRef<CFDataRef> cfData(cfdata_from_skdata(std::move(data)));
1270
1271 SkUniqueCFRef<CTFontDescriptorRef> desc(
1272 CTFontManagerCreateFontDescriptorFromData(cfData.get()));
1273 if (!desc) {
1274 return nullptr;
1275 }
1276 return SkUniqueCFRef<CTFontRef>(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr));
1277 }
1278
1279 sk_sp<SkTypeface> SkTypeface_Mac::MakeFromStream(std::unique_ptr<SkStreamAsset> stream,
1280 const SkFontArguments& args)
1281 {
1282 // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available.
1283 int ttcIndex = args.getCollectionIndex();
1284 if (ttcIndex != 0) {
1285 return nullptr;
1286 }
1287
1288 sk_sp<SkData> data = skdata_from_skstreamasset(stream->duplicate());
1289 if (!data) {
1290 return nullptr;
1291 }
1292 SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(std::move(data), ttcIndex);
1293 if (!ct) {
1294 return nullptr;
1295 }
1296
1297 SkUniqueCFRef<CTFontRef> ctVariant;
1298 CTFontVariation ctVariation;
1299 if (args.getVariationDesignPosition().coordinateCount == 0) {
1300 ctVariant = std::move(ct);
1301 } else {
1302 SkUniqueCFRef<CFArrayRef> axes(CTFontCopyVariationAxes(ct.get()));
1303 ctVariation = ctvariation_from_SkFontArguments(ct.get(), axes.get(), args);
1304
1305 if (ctVariation.variation) {
1306 SkUniqueCFRef<CFMutableDictionaryRef> attributes(
1307 CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
1308 &kCFTypeDictionaryKeyCallBacks,
1309 &kCFTypeDictionaryValueCallBacks));
1310 CFDictionaryAddValue(attributes.get(),
1311 kCTFontVariationAttribute, ctVariation.variation.get());
1312 SkUniqueCFRef<CTFontDescriptorRef> varDesc(
1313 CTFontDescriptorCreateWithAttributes(attributes.get()));
1314 ctVariant.reset(CTFontCreateCopyWithAttributes(ct.get(), 0, nullptr, varDesc.get()));
1315 } else {
1316 ctVariant = std::move(ct);
1317 }
1318 }
1319 if (!ctVariant) {
1320 return nullptr;
1321 }
1322
1323 return SkTypeface_Mac::Make(std::move(ctVariant), ctVariation.opsz, std::move(stream));
1324 }
1325
1326 int SkTypeface_Mac::onGetVariationDesignParameters(
1327 SkSpan<SkFontParameters::Variation::Axis> parameters) const
1328 {
1329 CFArrayRef ctAxes = this->getVariationAxes();
1330 if (!ctAxes) {
1331 return -1;
1332 }
1333 CFIndex axisCount = CFArrayGetCount(ctAxes);
1334
1335 if (parameters.size() < (size_t)axisCount) {
1336 return axisCount;
1337 }
1338
1339 // Added in 10.13
1340 static CFStringRef* kCTFontVariationAxisHiddenKeyPtr =
1341 static_cast<CFStringRef*>(dlsym(RTLD_DEFAULT, "kCTFontVariationAxisHiddenKey"));
1342
1343 for (int i = 0; i < axisCount; ++i) {
1344 CFDictionaryRef axisInfoDict;
1345 if (!SkCFDynamicCast(CFArrayGetValueAtIndex(ctAxes, i), &axisInfoDict, "Axis")) {
1346 return -1;
1347 }
1348
1349 int64_t tagLong;
1350 CFTypeRef tag = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisIdentifierKey);
1351 if (!SkCFNumberDynamicCast(tag, &tagLong, nullptr, "Axis tag")) {
1352 return -1;
1353 }
1354
1355 double minDouble;
1356 double maxDouble;
1357 double defDouble;
1358 CFTypeRef min = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMinimumValueKey);
1359 CFTypeRef max = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisMaximumValueKey);
1360 CFTypeRef def = CFDictionaryGetValue(axisInfoDict, kCTFontVariationAxisDefaultValueKey);
1361 if (!SkCFNumberDynamicCast(min, &minDouble, nullptr, "Axis min") ||
1362 !SkCFNumberDynamicCast(max, &maxDouble, nullptr, "Axis max") ||
1363 !SkCFNumberDynamicCast(def, &defDouble, nullptr, "Axis def"))
1364 {
1365 return -1;
1366 }
1367
1368 SkFontParameters::Variation::Axis& skAxis = parameters[i];
1369 skAxis.tag = tagLong;
1370 skAxis.min = minDouble;
1371 skAxis.max = maxDouble;
1372 skAxis.def = defDouble;
1373 skAxis.setHidden(false);
1374 if (kCTFontVariationAxisHiddenKeyPtr) {
1375 CFTypeRef hidden = CFDictionaryGetValue(axisInfoDict,*kCTFontVariationAxisHiddenKeyPtr);
1376 if (hidden) {
1377 // At least macOS 11 Big Sur Beta 4 uses CFNumberRef instead of CFBooleanRef.
1378 // https://crbug.com/1113444
1379 CFBooleanRef hiddenBoolean;
1380 int hiddenInt;
1381 if (SkCFDynamicCast(hidden, &hiddenBoolean, nullptr)) {
1382 skAxis.setHidden(CFBooleanGetValue(hiddenBoolean));
1383 } else if (SkCFNumberDynamicCast(hidden, &hiddenInt, nullptr, "Axis hidden")) {
1384 skAxis.setHidden(hiddenInt);
1385 } else {
1386 return -1;
1387 }
1388 }
1389 }
1390 }
1391 return axisCount;
1392 }
1393
1394 #endif