fd49b7dd217053ba14be60a8e587c1ba2526bf94
[WebKit-https.git] / Source / WebCore / platform / graphics / ios / FontCacheIOS.mm
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #import "config.h"
30 #import "FontCache.h"
31
32 #import "CoreGraphicsSPI.h"
33 #import "CoreTextSPI.h"
34 #import "FontCascade.h"
35 #import "RenderThemeIOS.h"
36 #import <wtf/NeverDestroyed.h>
37 #import <wtf/RetainPtr.h>
38 #import <wtf/text/CString.h>
39
40 namespace WebCore {
41
42 void FontCache::platformInit()
43 {
44 }
45
46 static inline bool isFontWeightBold(NSInteger fontWeight)
47 {
48     return fontWeight >= FontWeight600;
49 }
50
51 static inline bool requiresCustomFallbackFont(const UInt32 character)
52 {
53     return character == AppleLogo || character == blackCircle || character == narrowNonBreakingSpace;
54 }
55
56 #if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000
57 static CFCharacterSetRef copyFontCharacterSet(CFStringRef fontName)
58 {
59     // The size, 10, is arbitrary.
60     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithNameAndSize(fontName, 10));
61     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 10, nullptr));
62     return (CFCharacterSetRef)CTFontDescriptorCopyAttribute(fontDescriptor.get(), kCTFontCharacterSetAttribute);
63 }
64
65 static CFCharacterSetRef appleColorEmojiCharacterSet()
66 {
67     static CFCharacterSetRef characterSet = copyFontCharacterSet(CFSTR("AppleColorEmoji"));
68     return characterSet;
69 }
70
71 static CFCharacterSetRef phoneFallbackCharacterSet()
72 {
73     static CFCharacterSetRef characterSet = copyFontCharacterSet(CFSTR(".PhoneFallback"));
74     return characterSet;
75 }
76 #endif
77
78 PassRefPtr<Font> FontCache::getSystemFontFallbackForCharacters(const FontDescription& description, const Font* originalFontData, const UChar* characters, unsigned length)
79 {
80     const FontPlatformData& platformData = originalFontData->platformData();
81     CTFontRef ctFont = platformData.font();
82
83     CFIndex coveredLength = 0;
84     RetainPtr<CTFontRef> substituteFont = adoptCF(CTFontCreatePhysicalFontForCharactersWithLanguage(ctFont, (const UTF16Char*)characters, (CFIndex)length, 0, &coveredLength));
85     if (!substituteFont)
86         return nullptr;
87
88     CTFontSymbolicTraits originalTraits = CTFontGetSymbolicTraits(ctFont);
89     CTFontSymbolicTraits actualTraits = 0;
90     if (isFontWeightBold(description.weight()) || description.italic())
91         actualTraits = CTFontGetSymbolicTraits(substituteFont.get());
92
93     bool syntheticBold = (originalTraits & kCTFontTraitBold) && !(actualTraits & kCTFontTraitBold);
94     bool syntheticOblique = (originalTraits & kCTFontTraitItalic) && !(actualTraits & kCTFontTraitItalic);
95
96     FontPlatformData alternateFont(substituteFont.get(), platformData.size(), syntheticBold, syntheticOblique, platformData.m_orientation);
97     alternateFont.setIsEmoji(CTFontIsAppleColorEmoji(substituteFont.get()));
98
99     return fontForPlatformData(alternateFont);
100 }
101
102 #if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000
103 enum class LanguageSpecificFont {
104     None,
105     ChineseJapanese,
106     Korean,
107     Cyrillic,
108     Arabic,
109     Hebrew,
110     Indic,
111     Thai,
112     Lao,
113     Tibetan,
114     CanadianAboriginalSyllabic,
115     Khmer,
116     Emoji,
117 };
118
119 static LanguageSpecificFont languageSpecificFallbackFont(UChar32 c)
120 {
121     static bool isGB18030ComplianceRequired = wkIsGB18030ComplianceRequired();
122
123     // The following ranges are Korean Hangul and should be rendered by AppleSDGothicNeo
124     // U+1100 - U+11FF
125     // U+3130 - U+318F
126     // U+AC00 - U+D7A3
127
128     // These are Cyrillic and should be rendered by Helvetica Neue
129     // U+0400 - U+052F
130
131     if (c < 0x400)
132         return LanguageSpecificFont::None;
133     if (c < 0x530)
134         return LanguageSpecificFont::Cyrillic;
135     if (c < 0x590)
136         return LanguageSpecificFont::None;
137     if (c < 0x600)
138         return LanguageSpecificFont::Hebrew;
139     if (c < 0x700)
140         return LanguageSpecificFont::Arabic;
141     if (c < 0x900)
142         return LanguageSpecificFont::None;
143     if (c < 0xE00)
144         return LanguageSpecificFont::Indic;
145     if (c < 0xE80)
146         return LanguageSpecificFont::Thai;
147     if (c < 0x0F00)
148         return LanguageSpecificFont::Lao;
149     if (c < 0x1000)
150         return LanguageSpecificFont::Tibetan;
151     if (c < 0x1100)
152         return LanguageSpecificFont::None;
153     if (c < 0x1200)
154         return LanguageSpecificFont::Korean;
155     if (c < 0x1400)
156         return LanguageSpecificFont::None;
157     if (c < 0x1780)
158         return LanguageSpecificFont::CanadianAboriginalSyllabic;
159     if (c < 0x1800)
160         return LanguageSpecificFont::Khmer;
161     if (c < 0x2E80)
162         return LanguageSpecificFont::None;
163     if (c < 0x3130)
164         return LanguageSpecificFont::ChineseJapanese;
165     if (c < 0x3190)
166         return LanguageSpecificFont::Korean;
167     if (c < 0xAC00)
168         return LanguageSpecificFont::ChineseJapanese;
169     if (c < 0xD7A4)
170         return LanguageSpecificFont::Korean;
171     if (c < 0xE000)
172         return LanguageSpecificFont::ChineseJapanese;
173     if (c < 0xE600)
174         return isGB18030ComplianceRequired ? LanguageSpecificFont::ChineseJapanese : LanguageSpecificFont::Emoji;
175     if (c < 0xE865 && isGB18030ComplianceRequired)
176         return LanguageSpecificFont::ChineseJapanese;
177     if (c < 0xF900)
178         return LanguageSpecificFont::None;
179     if (c < 0xFB00)
180         return LanguageSpecificFont::ChineseJapanese;
181     if (c < 0xFB50)
182         return LanguageSpecificFont::None;
183     if (c < 0xFE00)
184         return LanguageSpecificFont::Arabic;
185     if (c < 0xFE20)
186         return LanguageSpecificFont::None;
187     if (c < 0xFE70)
188         return LanguageSpecificFont::ChineseJapanese;
189     if (c < 0xFF00)
190         return LanguageSpecificFont::Arabic;
191     if (c < 0xFFF0)
192         return LanguageSpecificFont::ChineseJapanese;
193     if (c < 0x20000)
194         return LanguageSpecificFont::None;
195     if (c < 0x30000)
196         return LanguageSpecificFont::ChineseJapanese;
197     return LanguageSpecificFont::None;
198 }
199 #endif
200
201 RefPtr<Font> FontCache::systemFallbackForCharacters(const FontDescription& description, const Font* originalFontData, bool, const UChar* characters, unsigned length)
202 {
203     // Unlike OS X, our fallback font on iPhone is Arial Unicode, which doesn't have some apple-specific glyphs like F8FF.
204     // Fall back to the Apple Fallback font in this case.
205     if (length && requiresCustomFallbackFont(*characters)) {
206         auto* fallback = getCustomFallbackFont(*characters, description);
207         if (!fallback)
208             return nullptr;
209         return fontForPlatformData(*fallback);
210     }
211
212     UChar32 c = *characters;
213     if (length > 1 && U16_IS_LEAD(c) && U16_IS_TRAIL(characters[1]))
214         c = U16_GET_SUPPLEMENTARY(c, characters[1]);
215
216     // For system fonts we use CoreText fallback mechanism.
217     if (length) {
218         RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontCopyFontDescriptor(originalFontData->getCTFont()));
219         if (CTFontDescriptorIsSystemUIFont(fontDescriptor.get()))
220             return getSystemFontFallbackForCharacters(description, originalFontData, characters, length);
221     }
222
223     RefPtr<Font> font;
224
225 #if __IPHONE_OS_VERSION_MIN_REQUIRED < 90000
226     LanguageSpecificFont languageSpecificFont = LanguageSpecificFont::None;
227     if (length)
228         languageSpecificFont = languageSpecificFallbackFont(c);
229
230     switch (languageSpecificFont) {
231     case LanguageSpecificFont::ChineseJapanese: {
232         // By default, Chinese font is preferred, fall back on Japanese.
233
234         enum CJKFontVariant {
235             kCJKFontUseHiragino = 0,
236             kCJKFontUseSTHeitiSC,
237             kCJKFontUseSTHeitiTC,
238             kCJKFontUseSTHeitiJ,
239             kCJKFontUseSTHeitiK,
240             kCJKFontsUseHKGPW3UI
241         };
242
243         static NeverDestroyed<AtomicString> plainHiragino("HiraKakuProN-W3", AtomicString::ConstructFromLiteral);
244         static NeverDestroyed<AtomicString> plainSTHeitiSC("STHeitiSC-Light", AtomicString::ConstructFromLiteral);
245         static NeverDestroyed<AtomicString> plainSTHeitiTC("STHeitiTC-Light", AtomicString::ConstructFromLiteral);
246         static NeverDestroyed<AtomicString> plainSTHeitiJ("STHeitiJ-Light", AtomicString::ConstructFromLiteral);
247         static NeverDestroyed<AtomicString> plainSTHeitiK("STHeitiK-Light", AtomicString::ConstructFromLiteral);
248         static NeverDestroyed<AtomicString> plainHKGPW3UI("HKGPW3UI", AtomicString::ConstructFromLiteral);
249         static AtomicString* cjkPlain[] = {     
250             &plainHiragino.get(),
251             &plainSTHeitiSC.get(),
252             &plainSTHeitiTC.get(),
253             &plainSTHeitiJ.get(),
254             &plainSTHeitiK.get(),
255             &plainHKGPW3UI.get(),
256         };
257
258         static NeverDestroyed<AtomicString> boldHiragino("HiraKakuProN-W6", AtomicString::ConstructFromLiteral);
259         static NeverDestroyed<AtomicString> boldSTHeitiSC("STHeitiSC-Medium", AtomicString::ConstructFromLiteral);
260         static NeverDestroyed<AtomicString> boldSTHeitiTC("STHeitiTC-Medium", AtomicString::ConstructFromLiteral);
261         static NeverDestroyed<AtomicString> boldSTHeitiJ("STHeitiJ-Medium", AtomicString::ConstructFromLiteral);
262         static NeverDestroyed<AtomicString> boldSTHeitiK("STHeitiK-Medium", AtomicString::ConstructFromLiteral);
263         static NeverDestroyed<AtomicString> boldHKGPW3UI("HKGPW3UI", AtomicString::ConstructFromLiteral);
264         static AtomicString* cjkBold[] = {  
265             &boldHiragino.get(),
266             &boldSTHeitiSC.get(),
267             &boldSTHeitiTC.get(),
268             &boldSTHeitiJ.get(),
269             &boldSTHeitiK.get(),
270             &boldHKGPW3UI.get(),
271         };
272
273         // Default below is for Simplified Chinese user: zh-Hans - note that Hiragino is the
274         // the secondary font as we want its for Hiragana and Katakana. The other CJK fonts
275         // do not, and should not, contain Hiragana or Katakana glyphs.
276         static CJKFontVariant preferredCJKFont = kCJKFontUseSTHeitiSC;
277         static CJKFontVariant secondaryCJKFont = kCJKFontsUseHKGPW3UI;
278
279         static bool CJKFontInitialized;
280         if (!CJKFontInitialized) {
281             CJKFontInitialized = true;
282             // Testing: languageName = (CFStringRef)@"ja";
283             NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
284             NSArray *languages = [defaults stringArrayForKey:@"AppleLanguages"];
285
286             if (languages) {
287                 for (NSString *language in languages) {
288                     RetainPtr<CFStringRef> languageName = adoptCF(CFLocaleCreateCanonicalLanguageIdentifierFromString(nullptr, (CFStringRef)language));
289                     if (CFEqual(languageName.get(), CFSTR("zh-Hans")))
290                         break; // Simplified Chinese - default settings
291                     else if (CFEqual(languageName.get(), CFSTR("ja"))) {
292                         preferredCJKFont = kCJKFontUseHiragino; // Japanese - prefer Hiragino and STHeiti Japanse Variant
293                         secondaryCJKFont = kCJKFontUseSTHeitiJ;
294                         break;
295                     } else if (CFEqual(languageName.get(), CFSTR("ko"))) {
296                         preferredCJKFont = kCJKFontUseSTHeitiK; // Korean - prefer STHeiti Korean Variant 
297                         break;
298                     } else if (CFEqual(languageName.get(), CFSTR("zh-Hant"))) {
299                         preferredCJKFont = kCJKFontUseSTHeitiTC; // Traditional Chinese - prefer STHeiti Traditional Variant
300                         break;
301                     }
302                 }
303             }
304         }
305
306         font = fontForFamily(description, isFontWeightBold(description.weight()) ? *cjkBold[preferredCJKFont] : *cjkPlain[preferredCJKFont], false);
307         bool useSecondaryFont = true;
308         if (font) {
309             CGGlyph glyphs[2];
310             // CGFontGetGlyphsForUnichars takes UTF-16 buffer. Should only be 1 codepoint but since we may pass in two UTF-16 characters,
311             // make room for 2 glyphs just to be safe.
312             CGFontGetGlyphsForUnichars(font->platformData().cgFont(), characters, glyphs, length);
313
314             useSecondaryFont = (glyphs[0] == 0);
315         }
316
317         if (useSecondaryFont)
318             font = fontForFamily(description, isFontWeightBold(description.weight()) ? *cjkBold[secondaryCJKFont] : *cjkPlain[secondaryCJKFont], false);
319         break;
320     }
321     case LanguageSpecificFont::Korean: {
322         static NeverDestroyed<AtomicString> koreanPlain("AppleSDGothicNeo-Medium", AtomicString::ConstructFromLiteral);
323         static NeverDestroyed<AtomicString> koreanBold("AppleSDGothicNeo-Bold", AtomicString::ConstructFromLiteral);
324         font = fontForFamily(description, isFontWeightBold(description.weight()) ? koreanBold : koreanPlain, false);
325         break;
326     }
327     case LanguageSpecificFont::Cyrillic: {
328         static NeverDestroyed<AtomicString> cyrillicPlain("HelveticaNeue", AtomicString::ConstructFromLiteral);
329         static NeverDestroyed<AtomicString> cyrillicBold("HelveticaNeue-Bold", AtomicString::ConstructFromLiteral);
330         font = fontForFamily(description, isFontWeightBold(description.weight()) ? cyrillicBold : cyrillicPlain, false);
331         break;
332     }
333     case LanguageSpecificFont::Arabic: {
334         static NeverDestroyed<AtomicString> arabicPlain("GeezaPro", AtomicString::ConstructFromLiteral);
335         static NeverDestroyed<AtomicString> arabicBold("GeezaPro-Bold", AtomicString::ConstructFromLiteral);
336         font = fontForFamily(description, isFontWeightBold(description.weight()) ? arabicBold : arabicPlain, false);
337         break;
338     }
339     case LanguageSpecificFont::Hebrew: {
340         static NeverDestroyed<AtomicString> hebrewPlain("ArialHebrew", AtomicString::ConstructFromLiteral);
341         static NeverDestroyed<AtomicString> hebrewBold("ArialHebrew-Bold", AtomicString::ConstructFromLiteral);
342         font = fontForFamily(description, isFontWeightBold(description.weight()) ? hebrewBold : hebrewPlain, false);
343         break;
344     }
345     case LanguageSpecificFont::Indic: {
346         static NeverDestroyed<AtomicString> devanagariFont("KohinoorDevanagari-Book", AtomicString::ConstructFromLiteral);
347         static NeverDestroyed<AtomicString> bengaliFont("BanglaSangamMN", AtomicString::ConstructFromLiteral);
348         static NeverDestroyed<AtomicString> gurmukhiFont("GurmukhiMN", AtomicString::ConstructFromLiteral); // Might be replaced in a future release with a Sangam version.
349         static NeverDestroyed<AtomicString> gujaratiFont("GujaratiSangamMN", AtomicString::ConstructFromLiteral);
350         static NeverDestroyed<AtomicString> oriyaFont("OriyaSangamMN", AtomicString::ConstructFromLiteral);
351         static NeverDestroyed<AtomicString> tamilFont("TamilSangamMN", AtomicString::ConstructFromLiteral);
352         static NeverDestroyed<AtomicString> teluguFont("TeluguSangamMN", AtomicString::ConstructFromLiteral);
353         static NeverDestroyed<AtomicString> kannadaFont("KannadaSangamMN", AtomicString::ConstructFromLiteral);
354         static NeverDestroyed<AtomicString> malayalamFont("MalayalamSangamMN", AtomicString::ConstructFromLiteral);
355         static NeverDestroyed<AtomicString> sinhalaFont("SinhalaSangamMN", AtomicString::ConstructFromLiteral);
356
357         static NeverDestroyed<AtomicString> devanagariFontBold("KohinoorDevanagari-Medium", AtomicString::ConstructFromLiteral);
358         static NeverDestroyed<AtomicString> bengaliFontBold("BanglaSangamMN-Bold", AtomicString::ConstructFromLiteral);
359         static NeverDestroyed<AtomicString> gurmukhiFontBold("GurmukhiMN-Bold", AtomicString::ConstructFromLiteral); // Might be replaced in a future release with a Sangam version.
360         static NeverDestroyed<AtomicString> gujaratiFontBold("GujaratiSangamMN-Bold", AtomicString::ConstructFromLiteral);
361         static NeverDestroyed<AtomicString> oriyaFontBold("OriyaSangamMN-Bold", AtomicString::ConstructFromLiteral);
362         static NeverDestroyed<AtomicString> tamilFontBold("TamilSangamMN-Bold", AtomicString::ConstructFromLiteral);
363         static NeverDestroyed<AtomicString> teluguFontBold("TeluguSangamMN-Bold", AtomicString::ConstructFromLiteral);
364         static NeverDestroyed<AtomicString> kannadaFontBold("KannadaSangamMN-Bold", AtomicString::ConstructFromLiteral);
365         static NeverDestroyed<AtomicString> malayalamFontBold("MalayalamSangamMN-Bold", AtomicString::ConstructFromLiteral);
366         static NeverDestroyed<AtomicString> sinhalaFontBold("SinhalaSangamMN-Bold", AtomicString::ConstructFromLiteral);
367
368         static AtomicString* indicUnicodePageFonts[] = {
369             &devanagariFont.get(),
370             &bengaliFont.get(),
371             &gurmukhiFont.get(),
372             &gujaratiFont.get(),
373             &oriyaFont.get(),
374             &tamilFont.get(),
375             &teluguFont.get(),
376             &kannadaFont.get(),
377             &malayalamFont.get(),
378             &sinhalaFont.get()
379         };
380
381         static AtomicString* indicUnicodePageFontsBold[] = {
382             &devanagariFontBold.get(),
383             &bengaliFontBold.get(),
384             &gurmukhiFontBold.get(),
385             &gujaratiFontBold.get(),
386             &oriyaFontBold.get(),
387             &tamilFontBold.get(),
388             &teluguFontBold.get(),
389             &kannadaFontBold.get(),
390             &malayalamFontBold.get(),
391             &sinhalaFontBold.get()
392         };
393
394         uint32_t indicPageOrderIndex = (c - 0x0900) / 0x0080; // Indic scripts start at 0x0900 in Unicode. Each script is allocalted a block of 0x80 characters.
395         if (indicPageOrderIndex < (sizeof(indicUnicodePageFonts) / sizeof(AtomicString*))) {
396             AtomicString* indicFontString = isFontWeightBold(description.weight()) ? indicUnicodePageFontsBold[indicPageOrderIndex] : indicUnicodePageFonts[indicPageOrderIndex];
397             if (indicFontString)
398                 font = fontForFamily(description, *indicFontString, false);
399         }
400         break;
401     }
402     case LanguageSpecificFont::Thai: {
403         static NeverDestroyed<AtomicString> thaiPlain("Thonburi", AtomicString::ConstructFromLiteral);
404         static NeverDestroyed<AtomicString> thaiBold("Thonburi-Bold", AtomicString::ConstructFromLiteral);
405         font = fontForFamily(description, isFontWeightBold(description.weight()) ? thaiBold : thaiPlain, false);
406         break;
407     }
408     case LanguageSpecificFont::Tibetan: {
409         static NeverDestroyed<AtomicString> tibetanPlain("Kailasa", AtomicString::ConstructFromLiteral);
410         static NeverDestroyed<AtomicString> tibetanBold("Kailasa-Bold", AtomicString::ConstructFromLiteral);
411         font = fontForFamily(description, isFontWeightBold(description.weight()) ? tibetanBold : tibetanPlain, false);
412         break;
413     }
414     case LanguageSpecificFont::CanadianAboriginalSyllabic: {
415         static NeverDestroyed<AtomicString> casPlain("EuphemiaUCAS", AtomicString::ConstructFromLiteral);
416         static NeverDestroyed<AtomicString> casBold("EuphemiaUCAS-Bold", AtomicString::ConstructFromLiteral);
417         font = fontForFamily(description, isFontWeightBold(description.weight()) ? casBold : casPlain, false);
418         break;
419     }
420     case LanguageSpecificFont::Khmer: {
421         static NeverDestroyed<AtomicString> khmer("KhmerSangamMN", AtomicString::ConstructFromLiteral);
422         font = fontForFamily(description, khmer, false);
423         break;
424     }
425     case LanguageSpecificFont::Lao: {
426         static NeverDestroyed<AtomicString> lao("LaoSangamMN", AtomicString::ConstructFromLiteral);
427         font = fontForFamily(description, lao, false);
428         break;
429     }
430     default: {
431         static NeverDestroyed<AtomicString> appleColorEmoji("AppleColorEmoji", AtomicString::ConstructFromLiteral);
432         bool useEmojiFont = languageSpecificFont == LanguageSpecificFont::Emoji;
433         if (!useEmojiFont) {
434             if (!CFCharacterSetIsLongCharacterMember(phoneFallbackCharacterSet(), c))
435                 useEmojiFont = CFCharacterSetIsLongCharacterMember(appleColorEmojiCharacterSet(), c);
436         }
437         if (useEmojiFont)
438             font = fontForFamily(description, appleColorEmoji, false);
439         else {
440             RetainPtr<CTFontRef> fallbackFont = adoptCF(CTFontCreateForCharacters(originalFontData->getCTFont(), characters, length, nullptr));
441             if (RetainPtr<CFStringRef> foundFontName = adoptCF(CTFontCopyPostScriptName(fallbackFont.get())))
442                 font = fontForFamily(description, foundFontName.get(), false);
443         }
444         break;
445     }
446     }
447 #else
448     RetainPtr<CTFontDescriptorRef> fallbackFontDescriptor = adoptCF(CTFontCreatePhysicalFontDescriptorForCharactersWithLanguage(originalFontData->getCTFont(), characters, length, nullptr, nullptr));
449     if (auto foundFontName = adoptCF(static_cast<CFStringRef>(CTFontDescriptorCopyAttribute(fallbackFontDescriptor.get(), kCTFontNameAttribute)))) {
450         if (c >= 0x0600 && c <= 0x06ff) { // Arabic
451             auto familyName = adoptCF(static_cast<CFStringRef>(CTFontDescriptorCopyAttribute(fallbackFontDescriptor.get(), kCTFontFamilyNameAttribute)));
452             if (fontFamilyShouldNotBeUsedForArabic(familyName.get()))
453                 foundFontName = isFontWeightBold(description.weight()) ? CFSTR("GeezaPro-Bold") : CFSTR("GeezaPro");
454         }
455         font = fontForFamily(description, foundFontName.get(), false);
456     }
457 #endif
458
459     if (font)
460         return font.release();
461
462     return lastResortFallbackFont(description);
463 }
464
465 RefPtr<Font> FontCache::similarFont(const FontDescription& description)
466 {
467     // Attempt to find an appropriate font using a match based on the presence of keywords in
468     // the requested names. For example, we'll match any name that contains "Arabic" to Geeza Pro.
469     RefPtr<Font> font;
470     for (unsigned i = 0; i < description.familyCount(); ++i) {
471         const AtomicString& family = description.familyAt(i);
472         if (family.isEmpty())
473             continue;
474
475         // Substitute the default monospace font for well-known monospace fonts.
476         static NeverDestroyed<AtomicString> monaco("monaco", AtomicString::ConstructFromLiteral);
477         static NeverDestroyed<AtomicString> menlo("menlo", AtomicString::ConstructFromLiteral);
478         static NeverDestroyed<AtomicString> courier("courier", AtomicString::ConstructFromLiteral);
479         if (equalIgnoringCase(family, monaco) || equalIgnoringCase(family, menlo)) {
480             font = fontForFamily(description, courier);
481             continue;
482         }
483
484         // Substitute Verdana for Lucida Grande.
485         static NeverDestroyed<AtomicString> lucidaGrande("lucida grande", AtomicString::ConstructFromLiteral);
486         static NeverDestroyed<AtomicString> verdana("verdana", AtomicString::ConstructFromLiteral);
487         if (equalIgnoringCase(family, lucidaGrande)) {
488             font = fontForFamily(description, verdana);
489             continue;
490         }
491
492         static NeverDestroyed<String> arabic(ASCIILiteral("Arabic"));
493         static NeverDestroyed<String> pashto(ASCIILiteral("Pashto"));
494         static NeverDestroyed<String> urdu(ASCIILiteral("Urdu"));
495         static String* matchWords[3] = { &arabic.get(), &pashto.get(), &urdu.get() };
496         static NeverDestroyed<AtomicString> geezaPlain("GeezaPro", AtomicString::ConstructFromLiteral);
497         static NeverDestroyed<AtomicString> geezaBold("GeezaPro-Bold", AtomicString::ConstructFromLiteral);
498         for (unsigned j = 0; j < 3 && !font; ++j) {
499             if (family.contains(*matchWords[j], false))
500                 font = fontForFamily(description, isFontWeightBold(description.weight()) ? geezaBold : geezaPlain);
501         }
502     }
503
504     return font.release();
505 }
506
507 Ref<Font> FontCache::lastResortFallbackFont(const FontDescription& fontDescription)
508 {
509     static NeverDestroyed<AtomicString> fallbackFontFamily(".PhoneFallback", AtomicString::ConstructFromLiteral);
510     return *fontForFamily(fontDescription, fallbackFontFamily, false);
511 }
512
513 FontPlatformData* FontCache::getCustomFallbackFont(const UInt32 c, const FontDescription& description)
514 {
515     ASSERT(requiresCustomFallbackFont(c));
516
517     static NeverDestroyed<AtomicString> helveticaFamily("Helvetica Neue", AtomicString::ConstructFromLiteral);
518     static NeverDestroyed<AtomicString> lockClockFamily("LockClock-Light", AtomicString::ConstructFromLiteral);
519     static NeverDestroyed<AtomicString> timesNewRomanPSMTFamily("TimesNewRomanPSMT", AtomicString::ConstructFromLiteral);
520
521     AtomicString* family = nullptr;
522     switch (c) {
523     case AppleLogo:
524         family = &helveticaFamily.get();
525         break;
526     case blackCircle:
527         family = &lockClockFamily.get();
528         break;
529     case narrowNonBreakingSpace:
530         family = &timesNewRomanPSMTFamily.get();
531         break;
532     default:
533         ASSERT_NOT_REACHED();
534         return nullptr;
535     }
536     ASSERT(family);
537     if (!family)
538         return nullptr;
539     return getCachedFontPlatformData(description, *family);
540 }
541
542 static inline FontTraitsMask toTraitsMask(CTFontSymbolicTraits ctFontTraits)
543 {
544     return static_cast<FontTraitsMask>(((ctFontTraits & kCTFontTraitItalic) ? FontStyleItalicMask : FontStyleNormalMask)
545         | FontVariantNormalMask
546         // FontWeight600 or higher is bold for CTFonts, so choose middle values for
547         // bold (600-900) and non-bold (100-500)
548         | ((ctFontTraits & kCTFontTraitBold) ? FontWeight700Mask : FontWeight300Mask));
549 }
550
551 void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
552 {
553     RetainPtr<CFStringRef> familyNameStr = familyName.string().createCFString();
554     NSDictionary *attributes = @{ (id)kCTFontFamilyNameAttribute: (NSString*)familyNameStr.get() };
555     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithAttributes((CFDictionaryRef)attributes));
556     RetainPtr<NSArray> matchedDescriptors = adoptNS((NSArray *)CTFontDescriptorCreateMatchingFontDescriptors(fontDescriptor.get(), nullptr));
557
558     NSInteger numMatches = [matchedDescriptors.get() count];
559     if (!matchedDescriptors || !numMatches)
560         return;
561
562     for (NSInteger i = 0; i < numMatches; ++i) {
563         RetainPtr<CFDictionaryRef> traits = adoptCF((CFDictionaryRef)CTFontDescriptorCopyAttribute((CTFontDescriptorRef)[matchedDescriptors.get() objectAtIndex:i], kCTFontTraitsAttribute));
564         CFNumberRef resultRef = (CFNumberRef)CFDictionaryGetValue(traits.get(), kCTFontSymbolicTrait);
565         if (resultRef) {
566             CTFontSymbolicTraits symbolicTraits;
567             CFNumberGetValue(resultRef, kCFNumberIntType, &symbolicTraits);
568             traitsMasks.append(toTraitsMask(symbolicTraits));
569         }
570     }
571 }
572
573 float FontCache::weightOfCTFont(CTFontRef font)
574 {
575     float result = 0;
576     RetainPtr<CFDictionaryRef> traits = adoptCF(CTFontCopyTraits(font));
577     if (!traits)
578         return result;
579
580     CFNumberRef resultRef = (CFNumberRef)CFDictionaryGetValue(traits.get(), kCTFontWeightTrait);
581     if (resultRef)
582         CFNumberGetValue(resultRef, kCFNumberFloatType, &result);
583
584     return result;
585 }
586
587 static CTFontRef createCTFontWithTextStyle(const String& familyName, CTFontSymbolicTraits traits, CGFloat size)
588 {
589     if (familyName.isNull())
590         return nullptr;
591
592     CTFontSymbolicTraits symbolicTraits = 0;
593     if (traits & kCTFontBoldTrait)
594         symbolicTraits |= kCTFontBoldTrait;
595     if (traits & kCTFontTraitItalic)
596         symbolicTraits |= kCTFontTraitItalic;
597     RetainPtr<CFStringRef> familyNameStr = familyName.createCFString();
598     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(familyNameStr.get(), RenderThemeIOS::contentSizeCategory(), nullptr));
599     if (symbolicTraits)
600         fontDescriptor = adoptCF(CTFontDescriptorCreateCopyWithSymbolicTraits(fontDescriptor.get(), symbolicTraits, symbolicTraits));
601
602     return CTFontCreateWithFontDescriptor(fontDescriptor.get(), size, nullptr);
603 }
604
605 static CTFontRef createCTFontWithFamilyNameAndWeight(const String& familyName, CTFontSymbolicTraits traits, float size, uint16_t weight)
606 {
607     if (familyName.isNull())
608         return nullptr;
609
610     static NeverDestroyed<AtomicString> systemUIFontWithWebKitPrefix("-webkit-system-font", AtomicString::ConstructFromLiteral);
611     static NeverDestroyed<AtomicString> systemUIFontWithApplePrefix("-apple-system", AtomicString::ConstructFromLiteral);
612     static NeverDestroyed<AtomicString> systemUIFontWithAppleAlternatePrefix("-apple-system-font", AtomicString::ConstructFromLiteral);
613     if (equalIgnoringCase(familyName, systemUIFontWithWebKitPrefix) || equalIgnoringCase(familyName, systemUIFontWithApplePrefix) || equalIgnoringCase(familyName, systemUIFontWithAppleAlternatePrefix)) {
614         CTFontUIFontType fontType = kCTFontUIFontSystem;
615         if (weight > 300) {
616             // The comment below has been copied from CoreText/UIFoundation. However, in WebKit we synthesize the oblique,
617             // so we should investigate the result <rdar://problem/14449340>:
618             // We don't do bold-italic for system fonts. If you ask for it, we'll assume that you're just kidding and that you really want bold. This is a feature.
619             if (traits & kCTFontTraitBold)
620                 fontType = kCTFontUIFontEmphasizedSystem;
621             else if (traits & kCTFontTraitItalic)
622                 fontType = static_cast<CTFontUIFontType>(kCTFontUIFontSystemItalic);
623         } else if (weight > 250)
624             fontType = static_cast<CTFontUIFontType>(kCTFontUIFontSystemLight);
625         else if (weight > 150)
626             fontType = static_cast<CTFontUIFontType>(kCTFontUIFontSystemThin);
627         else
628             fontType = static_cast<CTFontUIFontType>(kCTFontUIFontSystemUltraLight);
629         RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateForUIType(fontType, size, nullptr));
630         return CTFontCreateWithFontDescriptor(fontDescriptor.get(), size, nullptr);
631     }
632
633     static NeverDestroyed<AtomicString> systemUIMonospacedNumbersFontWithApplePrefix("-apple-system-monospaced-numbers", AtomicString::ConstructFromLiteral);
634     if (equalIgnoringCase(familyName, systemUIMonospacedNumbersFontWithApplePrefix)) {
635         RetainPtr<CTFontDescriptorRef> systemFontDescriptor = adoptCF(CTFontDescriptorCreateForUIType(kCTFontUIFontSystem, size, nullptr));
636         RetainPtr<CTFontDescriptorRef> monospaceFontDescriptor = adoptCF(CTFontDescriptorCreateCopyWithFeature(systemFontDescriptor.get(), (CFNumberRef)@(kNumberSpacingType), (CFNumberRef)@(kMonospacedNumbersSelector)));
637         return CTFontCreateWithFontDescriptor(monospaceFontDescriptor.get(), size, nullptr);
638     }
639
640
641     RetainPtr<CFStringRef> familyNameStr = familyName.createCFString();
642     CTFontSymbolicTraits requestedTraits = (CTFontSymbolicTraits)(traits & (kCTFontBoldTrait | kCTFontItalicTrait));
643     return CTFontCreateForCSS(familyNameStr.get(), weight, requestedTraits, size);
644 }
645
646 static uint16_t toCTFontWeight(FontWeight fontWeight)
647 {
648     switch (fontWeight) {
649     case FontWeight100:
650         return 100;
651     case FontWeight200:
652         return 200;
653     case FontWeight300:
654         return 300;
655     case FontWeight400:
656         return 400;
657     case FontWeight500:
658         return 500;
659     case FontWeight600:
660         return 600;
661     case FontWeight700:
662         return 700;
663     case FontWeight800:
664         return 800;
665     case FontWeight900:
666         return 900;
667     default:
668         return 400;
669     }
670 }
671
672 std::unique_ptr<FontPlatformData> FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
673 {
674     // Special case for "Courier" font. We used to have only an oblique variant on iOS, so prior to
675     // iOS 6.0, we disallowed its use here. We'll fall back on "Courier New". <rdar://problem/5116477&10850227>
676     static NeverDestroyed<AtomicString> courier("Courier", AtomicString::ConstructFromLiteral);
677     static bool shouldDisallowCourier = !iosExecutableWasLinkedOnOrAfterVersion(wkIOSSystemVersion_6_0);
678     if (shouldDisallowCourier && equalIgnoringCase(family, courier))
679         return nullptr;
680
681     CTFontSymbolicTraits traits = 0;
682     if (fontDescription.italic())
683         traits |= kCTFontTraitItalic;
684     if (isFontWeightBold(fontDescription.weight()))
685         traits |= kCTFontTraitBold;
686     float size = fontDescription.computedPixelSize();
687
688     RetainPtr<CTFontRef> ctFont;
689     if (family.startsWith("UICTFontTextStyle"))
690         ctFont = adoptCF(createCTFontWithTextStyle(family, traits, size));
691     else
692         ctFont = adoptCF(createCTFontWithFamilyNameAndWeight(family, traits, size, toCTFontWeight(fontDescription.weight())));
693     if (!ctFont)
694         return nullptr;
695
696     CTFontSymbolicTraits actualTraits = 0;
697     if (isFontWeightBold(fontDescription.weight()) || fontDescription.italic())
698         actualTraits = CTFontGetSymbolicTraits(ctFont.get());
699
700     bool isAppleColorEmoji = CTFontIsAppleColorEmoji(ctFont.get());
701
702     bool syntheticBold = (fontDescription.fontSynthesis() & FontSynthesisWeight) && (traits & kCTFontTraitBold) && !(actualTraits & kCTFontTraitBold) && !isAppleColorEmoji;
703     bool syntheticOblique = (fontDescription.fontSynthesis() & FontSynthesisStyle) && (traits & kCTFontTraitItalic) && !(actualTraits & kCTFontTraitItalic) && !isAppleColorEmoji;
704
705     auto result = std::make_unique<FontPlatformData>(ctFont.get(), size, syntheticBold, syntheticOblique, fontDescription.orientation(), fontDescription.widthVariant());
706     if (isAppleColorEmoji)
707         result->setIsEmoji(true);
708     return result;
709 }
710
711 } // namespace WebCore