Tizen 2.1 base
[framework/web/webkit-efl.git] / Source / WebCore / platform / graphics / freetype / FontCacheFreeType.cpp
1 /*
2  * Copyright (C) 2008 Alp Toker <alp@atoker.com>
3  * Copyright (C) 2010 Igalia S.L.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  *
20  */
21
22 #include "config.h"
23 #include "FontCache.h"
24
25 #include "Font.h"
26 #include "OwnPtrCairo.h"
27 #include "RefPtrCairo.h"
28 #include "SimpleFontData.h"
29 #include <cairo-ft.h>
30 #include <cairo.h>
31 #include <fontconfig/fcfreetype.h>
32 #include <wtf/Assertions.h>
33 #include <wtf/text/CString.h>
34
35 #if ENABLE(TIZEN_WEBKIT_OWN_FONT_FILES)
36 #define APP_FONT_DIR "/usr/share/app_fonts"
37 #endif
38
39 namespace WebCore {
40
41 void FontCache::platformInit()
42 {
43 #if ENABLE(TIZEN_WEBKIT_OWN_FONT_FILES)
44     FcConfig *fc_config;
45     fc_config = FcConfigGetCurrent();
46     FcConfigAppFontAddDir(fc_config, (FcChar8*)APP_FONT_DIR);
47     FcConfigSetCurrent(fc_config);
48 #endif
49     // It's fine to call FcInit multiple times per the documentation.
50     if (!FcInit())
51         ASSERT_NOT_REACHED();
52 }
53
54 FcPattern* createFontConfigPatternForCharacters(const UChar* characters, int length)
55 {
56     FcPattern* pattern = FcPatternCreate();
57
58     FcCharSet* fontConfigCharSet = FcCharSetCreate();
59     for (int i = 0; i < length; ++i) {
60         if (U16_IS_SURROGATE(characters[i]) && U16_IS_SURROGATE_LEAD(characters[i])
61                 && i != length - 1 && U16_IS_TRAIL(characters[i + 1])) {
62             FcCharSetAddChar(fontConfigCharSet, U16_GET_SUPPLEMENTARY(characters[i], characters[i+1]));
63             i++;
64         } else
65             FcCharSetAddChar(fontConfigCharSet, characters[i]);
66     }
67     FcPatternAddCharSet(pattern, FC_CHARSET, fontConfigCharSet);
68     FcCharSetDestroy(fontConfigCharSet);
69
70     FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
71     FcConfigSubstitute(0, pattern, FcMatchPattern);
72     FcDefaultSubstitute(pattern);
73     return pattern;
74 }
75
76 FcPattern* findBestFontGivenFallbacks(const FontPlatformData& fontData, FcPattern* pattern)
77 {
78 #if ENABLE(TIZEN_USER_SETTING_FONT)
79     //If we don't find glyphs for characters, we can use SLP fallback font that is selected by user in Setting
80     RefPtr<FcPattern> settingsPattern = adoptRef(FcPatternCreate());
81     String settingsFamilyNameString = "SLP";
82
83     if (!FcPatternAddString(settingsPattern.get(), FC_FAMILY, reinterpret_cast<const FcChar8*>(settingsFamilyNameString.utf8().data())))
84         return 0;
85
86     FcConfigSubstitute(0, settingsPattern.get(), FcMatchPattern);
87     FcDefaultSubstitute(settingsPattern.get());
88
89     FcResult fallbackFontConfigResult;
90     FcFontSet* fallbacks = FcFontSort(0, settingsPattern.get(), FcTrue, 0, &fallbackFontConfigResult);
91
92     FcFontSet* fcSets[] = { fallbacks };
93     return FcFontSetMatch(0, fcSets, 1, pattern, &fallbackFontConfigResult);
94 #endif
95
96     if (!fontData.m_pattern)
97         return 0;
98
99     if (!fontData.m_fallbacks) {
100         FcResult fontConfigResult;
101         fontData.m_fallbacks = FcFontSort(0, fontData.m_pattern.get(), FcTrue, 0, &fontConfigResult);
102     }
103
104     if (!fontData.m_fallbacks)
105         return 0;
106
107     FcFontSet* sets[] = { fontData.m_fallbacks };
108     FcResult fontConfigResult;
109     return FcFontSetMatch(0, sets, 1, pattern, &fontConfigResult);
110 }
111
112 const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length)
113 {
114     RefPtr<FcPattern> pattern = adoptRef(createFontConfigPatternForCharacters(characters, length));
115     const FontPlatformData& fontData = font.primaryFont()->platformData();
116
117     RefPtr<FcPattern> fallbackPattern = adoptRef(findBestFontGivenFallbacks(fontData, pattern.get()));
118     if (fallbackPattern) {
119         FontPlatformData alternateFontData(fallbackPattern.get(), font.fontDescription());
120         return getCachedFontData(&alternateFontData, DoNotRetain);
121     }
122
123     FcResult fontConfigResult;
124     RefPtr<FcPattern> resultPattern = adoptRef(FcFontMatch(0, pattern.get(), &fontConfigResult));
125     if (!resultPattern)
126         return 0;
127     FontPlatformData alternateFontData(resultPattern.get(), font.fontDescription());
128     return getCachedFontData(&alternateFontData, DoNotRetain);
129 }
130
131 SimpleFontData* FontCache::getSimilarFontPlatformData(const Font& font)
132 {
133     return 0;
134 }
135
136 SimpleFontData* FontCache::getLastResortFallbackFont(const FontDescription& fontDescription, ShouldRetain shouldRetain)
137 {
138     // We want to return a fallback font here, otherwise the logic preventing FontConfig
139     // matches for non-fallback fonts might return 0. See isFallbackFontAllowed.
140     static AtomicString timesStr("serif");
141     return getCachedFontData(fontDescription, timesStr, false, shouldRetain);
142 }
143
144 void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
145 {
146 }
147
148 static String getFamilyNameStringFromFontDescriptionAndFamily(const FontDescription& fontDescription, const AtomicString& family)
149 {
150     // If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
151     // the fallback name (like "monospace") that fontconfig understands.
152     if (family.length() && !family.startsWith("-webkit-"))
153         return family.string();
154
155     switch (fontDescription.genericFamily()) {
156     case FontDescription::StandardFamily:
157     case FontDescription::SerifFamily:
158         return "serif";
159     case FontDescription::SansSerifFamily:
160         return "sans-serif";
161     case FontDescription::MonospaceFamily:
162         return "monospace";
163     case FontDescription::CursiveFamily:
164         return "cursive";
165     case FontDescription::FantasyFamily:
166         return "fantasy";
167     case FontDescription::NoFamily:
168     default:
169         return "";
170     }
171 }
172
173 int fontWeightToFontconfigWeight(FontWeight weight)
174 {
175     switch (weight) {
176     case FontWeight100:
177         return FC_WEIGHT_THIN;
178     case FontWeight200:
179         return FC_WEIGHT_ULTRALIGHT;
180     case FontWeight300:
181         return FC_WEIGHT_LIGHT;
182     case FontWeight400:
183         return FC_WEIGHT_REGULAR;
184     case FontWeight500:
185         return FC_WEIGHT_MEDIUM;
186     case FontWeight600:
187         return FC_WEIGHT_SEMIBOLD;
188     case FontWeight700:
189         return FC_WEIGHT_BOLD;
190     case FontWeight800:
191         return FC_WEIGHT_EXTRABOLD;
192     case FontWeight900:
193         return FC_WEIGHT_ULTRABLACK;
194     default:
195         ASSERT_NOT_REACHED();
196         return FC_WEIGHT_REGULAR;
197     }
198 }
199
200 FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
201 {
202     // The CSS font matching algorithm (http://www.w3.org/TR/css3-fonts/#font-matching-algorithm)
203     // says that we must find an exact match for font family, slant (italic or oblique can be used)
204     // and font weight (we only match bold/non-bold here).
205     RefPtr<FcPattern> pattern = adoptRef(FcPatternCreate());
206     String familyNameString(getFamilyNameStringFromFontDescriptionAndFamily(fontDescription, family));
207     if (!FcPatternAddString(pattern.get(), FC_FAMILY, reinterpret_cast<const FcChar8*>(familyNameString.utf8().data())))
208         return 0;
209
210     bool italic = fontDescription.italic();
211     if (!FcPatternAddInteger(pattern.get(), FC_SLANT, italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN))
212         return 0;
213     if (!FcPatternAddInteger(pattern.get(), FC_WEIGHT, fontWeightToFontconfigWeight(fontDescription.weight())))
214         return 0;
215     if (!FcPatternAddDouble(pattern.get(), FC_PIXEL_SIZE, fontDescription.computedPixelSize()))
216         return 0;
217
218     // The strategy is originally from Skia (src/ports/SkFontHost_fontconfig.cpp):
219
220     // Allow Fontconfig to do pre-match substitution. Unless we are accessing a "fallback"
221     // family like "sans," this is the only time we allow Fontconfig to substitute one
222     // family name for another (i.e. if the fonts are aliased to each other).
223     FcConfigSubstitute(0, pattern.get(), FcMatchPattern);
224     FcDefaultSubstitute(pattern.get());
225
226     FcChar8* fontConfigFamilyNameAfterConfiguration;
227     FcPatternGetString(pattern.get(), FC_FAMILY, 0, &fontConfigFamilyNameAfterConfiguration);
228     String familyNameAfterConfiguration = String::fromUTF8(reinterpret_cast<char*>(fontConfigFamilyNameAfterConfiguration));
229
230     FcResult fontConfigResult;
231     RefPtr<FcPattern> resultPattern = adoptRef(FcFontMatch(0, pattern.get(), &fontConfigResult));
232     if (!resultPattern) // No match.
233         return 0;
234
235     FcChar8* fontConfigFamilyNameAfterMatching;
236     FcPatternGetString(resultPattern.get(), FC_FAMILY, 0, &fontConfigFamilyNameAfterMatching);
237     String familyNameAfterMatching = String::fromUTF8(reinterpret_cast<char*>(fontConfigFamilyNameAfterMatching));
238
239     // If Fontconfig gave use a different font family than the one we requested, we should ignore it
240     // and allow WebCore to give us the next font on the CSS fallback list. The only exception is if
241     // this family name is a commonly used generic family.
242     if (!equalIgnoringCase(familyNameAfterConfiguration, familyNameAfterMatching)
243         && !(equalIgnoringCase(familyNameString, "sans") || equalIgnoringCase(familyNameString, "sans-serif")
244           || equalIgnoringCase(familyNameString, "serif") || equalIgnoringCase(familyNameString, "monospace")
245           || equalIgnoringCase(familyNameString, "fantasy") || equalIgnoringCase(familyNameString, "cursive")))
246         return 0;
247
248     // Verify that this font has an encoding compatible with Fontconfig. Fontconfig currently
249     // supports three encodings in FcFreeTypeCharIndex: Unicode, Symbol and AppleRoman.
250     // If this font doesn't have one of these three encodings, don't select it.
251     FontPlatformData* platformData = new FontPlatformData(resultPattern.get(), fontDescription);
252     if (!platformData->hasCompatibleCharmap()) {
253         delete platformData;
254         return 0;
255     }
256
257     return platformData;
258 }
259
260 }