blob: bba1eaff04a68508fcf87dadb51226e17d811b12 [file] [log] [blame]
reed@google.comb1c65b62013-02-26 15:50:51 +00001/*
2 * Copyright 2009 Google Inc.
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/* migrated from chrome/src/skia/ext/SkFontHost_fontconfig_direct.cpp */
9
10#include <map>
11#include <string>
12#include <unistd.h>
13#include <fcntl.h>
14
15#include <fontconfig/fontconfig.h>
16
17#include "SkFontConfigInterface.h"
18//#include "SkUtils.h"
19#include "SkStream.h"
20
21class SkFontConfigInterfaceDirect : public SkFontConfigInterface {
22public:
23 SkFontConfigInterfaceDirect();
24 virtual ~SkFontConfigInterfaceDirect();
25
26 virtual bool match(const char familyName[], SkTypeface::Style requested,
27 unsigned* fileFaceID, SkTypeface::Style* outStyle) SK_OVERRIDE;
28 virtual bool getFamilyName(unsigned fileFaceID, SkString* name) SK_OVERRIDE;
29 virtual SkStream* openStream(unsigned fileFaceID) SK_OVERRIDE;
30
31private:
32 SkMutex mutex_;
33
34 // fileid stored in two maps below are unique per font file.
35 std::map<unsigned, std::string> fileid_to_filename_;
36 std::map<std::string, unsigned> filename_to_fileid_;
37
38 // Cache of |family,style| to |FontMatch| to minimize querying FontConfig.
39 typedef std::pair<std::string, int> FontMatchKey;
40 struct FontMatch {
41 std::string family;
42 SkTypeface::Style style;
43 unsigned filefaceid;
44 };
45 std::map<FontMatchKey, FontMatch> font_match_cache_;
46
47 unsigned next_file_id_;
48};
49
50SkFontConfigInterface* SkCreateDirectFontConfigInterface();
51SkFontConfigInterface* SkCreateDirectFontConfigInterface() {
52 return SkNEW(SkFontConfigInterfaceDirect);
53}
54
55namespace {
56
57// Equivalence classes, used to match the Liberation and other fonts
58// with their metric-compatible replacements. See the discussion in
59// GetFontEquivClass().
60enum FontEquivClass
61{
62 OTHER,
63 SANS,
64 SERIF,
65 MONO,
66 SYMBOL,
67 PGOTHIC,
68 GOTHIC,
69 PMINCHO,
70 MINCHO,
71 SIMSUN,
72 NSIMSUN,
73 SIMHEI,
74 PMINGLIU,
75 MINGLIU,
76 PMINGLIUHK,
77 MINGLIUHK,
78};
79
80// Match the font name against a whilelist of fonts, returning the equivalence
81// class.
82FontEquivClass GetFontEquivClass(const char* fontname)
83{
84 // It would be nice for fontconfig to tell us whether a given suggested
85 // replacement is a "strong" match (that is, an equivalent font) or
86 // a "weak" match (that is, fontconfig's next-best attempt at finding a
87 // substitute). However, I played around with the fontconfig API for
88 // a good few hours and could not make it reveal this information.
89 //
90 // So instead, we hardcode. Initially this function emulated
91 // /etc/fonts/conf.d/30-metric-aliases.conf
92 // from my Ubuntu system, but we're better off being very conservative.
93
94 // Arimo, Tinos and Cousine are a set of fonts metric-compatible with
95 // Arial, Times New Roman and Courier New with a character repertoire
96 // much larger than Liberation. Note that Cousine is metrically
97 // compatible with Courier New, but the former is sans-serif while
98 // the latter is serif.
99
100
101 struct FontEquivMap {
102 FontEquivClass clazz;
103 const char name[40];
104 };
105
106 static const FontEquivMap kFontEquivMap[] = {
107 { SANS, "Arial" },
108 { SANS, "Arimo" },
109 { SANS, "Liberation Sans" },
110
111 { SERIF, "Times New Roman" },
112 { SERIF, "Tinos" },
113 { SERIF, "Liberation Serif" },
114
115 { MONO, "Courier New" },
116 { MONO, "Cousine" },
117 { MONO, "Liberation Mono" },
118
119 { SYMBOL, "Symbol" },
120 { SYMBOL, "Symbol Neu" },
121
122 // MS Pゴシック
123 { PGOTHIC, "MS PGothic" },
124 { PGOTHIC, "\xef\xbc\xad\xef\xbc\xb3 \xef\xbc\xb0"
125 "\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf" },
126 { PGOTHIC, "IPAPGothic" },
127 { PGOTHIC, "MotoyaG04Gothic" },
128
129 // MS ゴシック
130 { GOTHIC, "MS Gothic" },
131 { GOTHIC, "\xef\xbc\xad\xef\xbc\xb3 "
132 "\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf" },
133 { GOTHIC, "IPAGothic" },
134 { GOTHIC, "MotoyaG04GothicMono" },
135
136 // MS P明朝
137 { PMINCHO, "MS PMincho" },
138 { PMINCHO, "\xef\xbc\xad\xef\xbc\xb3 \xef\xbc\xb0"
139 "\xe6\x98\x8e\xe6\x9c\x9d"},
140 { PMINCHO, "IPAPMincho" },
141 { PMINCHO, "MotoyaG04Mincho" },
142
143 // MS 明朝
144 { MINCHO, "MS Mincho" },
145 { MINCHO, "\xef\xbc\xad\xef\xbc\xb3 \xe6\x98\x8e\xe6\x9c\x9d" },
146 { MINCHO, "IPAMincho" },
147 { MINCHO, "MotoyaG04MinchoMono" },
148
149 // 宋体
150 { SIMSUN, "Simsun" },
151 { SIMSUN, "\xe5\xae\x8b\xe4\xbd\x93" },
152 { SIMSUN, "MSung GB18030" },
153 { SIMSUN, "Song ASC" },
154
155 // 新宋体
156 { NSIMSUN, "NSimsun" },
157 { NSIMSUN, "\xe6\x96\xb0\xe5\xae\x8b\xe4\xbd\x93" },
158 { NSIMSUN, "MSung GB18030" },
159 { NSIMSUN, "N Song ASC" },
160
161 // 黑体
162 { SIMHEI, "Simhei" },
163 { SIMHEI, "\xe9\xbb\x91\xe4\xbd\x93" },
164 { SIMHEI, "MYingHeiGB18030" },
165 { SIMHEI, "MYingHeiB5HK" },
166
167 // 新細明體
168 { PMINGLIU, "PMingLiU"},
169 { PMINGLIU, "\xe6\x96\xb0\xe7\xb4\xb0\xe6\x98\x8e\xe9\xab\x94" },
170 { PMINGLIU, "MSung B5HK"},
171
172 // 細明體
173 { MINGLIU, "MingLiU"},
174 { MINGLIU, "\xe7\xb4\xb0\xe6\x98\x8e\xe9\xab\x94" },
175 { MINGLIU, "MSung B5HK"},
176
177 // 新細明體
178 { PMINGLIUHK, "PMingLiU_HKSCS"},
179 { PMINGLIUHK, "\xe6\x96\xb0\xe7\xb4\xb0\xe6\x98\x8e\xe9\xab\x94_HKSCS" },
180 { PMINGLIUHK, "MSung B5HK"},
181
182 // 細明體
183 { MINGLIUHK, "MingLiU_HKSCS"},
184 { MINGLIUHK, "\xe7\xb4\xb0\xe6\x98\x8e\xe9\xab\x94_HKSCS" },
185 { MINGLIUHK, "MSung B5HK"},
186 };
187
188 static const size_t kFontCount =
189 sizeof(kFontEquivMap)/sizeof(kFontEquivMap[0]);
190
191 // TODO(jungshik): If this loop turns out to be hot, turn
192 // the array to a static (hash)map to speed it up.
193 for (size_t i = 0; i < kFontCount; ++i) {
194 if (strcasecmp(kFontEquivMap[i].name, fontname) == 0)
195 return kFontEquivMap[i].clazz;
196 }
197 return OTHER;
198}
199
200
201// Return true if |font_a| and |font_b| are visually and at the metrics
202// level interchangeable.
203bool IsMetricCompatibleReplacement(const char* font_a, const char* font_b)
204{
205 FontEquivClass class_a = GetFontEquivClass(font_a);
206 FontEquivClass class_b = GetFontEquivClass(font_b);
207
208 return class_a != OTHER && class_a == class_b;
209}
210
211inline unsigned FileFaceIdToFileId(unsigned filefaceid)
212{
213 return filefaceid >> 4;
214}
215
216inline unsigned FileIdAndFaceIndexToFileFaceId(unsigned fileid, int face_index)
217{
218 SkASSERT((face_index & 0xfu) == face_index);
219 return (fileid << 4) | face_index;
220}
221
222// Normally we only return exactly the font asked for. In last-resort
223// cases, the request either doesn't specify a font or is one of the
224// basic font names like "Sans", "Serif" or "Monospace". This function
225// tells you whether a given request is for such a fallback.
226bool IsFallbackFontAllowed(const std::string& family) {
227 const char* family_cstr = family.c_str();
228 return family.empty() ||
229 strcasecmp(family_cstr, "sans") == 0 ||
230 strcasecmp(family_cstr, "serif") == 0 ||
231 strcasecmp(family_cstr, "monospace") == 0;
232}
233
234// Find matching font from |font_set| for the given font family.
235FcPattern* MatchFont(FcFontSet* font_set,
236 FcChar8* post_config_family,
237 const std::string& family) {
238 // Older versions of fontconfig have a bug where they cannot select
239 // only scalable fonts so we have to manually filter the results.
240 FcPattern* match = NULL;
241 for (int i = 0; i < font_set->nfont; ++i) {
242 FcPattern* current = font_set->fonts[i];
243 FcBool is_scalable;
244
245 if (FcPatternGetBool(current, FC_SCALABLE, 0,
246 &is_scalable) != FcResultMatch ||
247 !is_scalable) {
248 continue;
249 }
250
251 // fontconfig can also return fonts which are unreadable
252 FcChar8* c_filename;
253 if (FcPatternGetString(current, FC_FILE, 0, &c_filename) != FcResultMatch)
254 continue;
255
256 if (access(reinterpret_cast<char*>(c_filename), R_OK) != 0)
257 continue;
258
259 match = current;
260 break;
261 }
262
263 if (match && !IsFallbackFontAllowed(family)) {
264 bool acceptable_substitute = false;
265 for (int id = 0; id < 255; ++id) {
266 FcChar8* post_match_family;
267 if (FcPatternGetString(match, FC_FAMILY, id, &post_match_family) !=
268 FcResultMatch)
269 break;
270 acceptable_substitute =
271 (strcasecmp(reinterpret_cast<char*>(post_config_family),
272 reinterpret_cast<char*>(post_match_family)) == 0 ||
273 // Workaround for Issue 12530:
274 // requested family: "Bitstream Vera Sans"
275 // post_config_family: "Arial"
276 // post_match_family: "Bitstream Vera Sans"
277 // -> We should treat this case as a good match.
278 strcasecmp(family.c_str(),
279 reinterpret_cast<char*>(post_match_family)) == 0) ||
280 IsMetricCompatibleReplacement(family.c_str(),
281 reinterpret_cast<char*>(post_match_family));
282 if (acceptable_substitute)
283 break;
284 }
285 if (!acceptable_substitute)
286 return NULL;
287 }
288
289 return match;
290}
291
292// Retrieves |is_bold|, |is_italic| and |font_family| properties from |font|.
293bool GetFontProperties(FcPattern* font,
294 std::string* font_family,
295 SkTypeface::Style* style) {
296 FcChar8* c_family;
297 if (FcPatternGetString(font, FC_FAMILY, 0, &c_family))
298 return false;
299
300 int resulting_bold;
301 if (FcPatternGetInteger(font, FC_WEIGHT, 0, &resulting_bold))
302 resulting_bold = FC_WEIGHT_NORMAL;
303
304 int resulting_italic;
305 if (FcPatternGetInteger(font, FC_SLANT, 0, &resulting_italic))
306 resulting_italic = FC_SLANT_ROMAN;
307
308 // If we ask for an italic font, fontconfig might take a roman font and set
309 // the undocumented property FC_MATRIX to a skew matrix. It'll then say
310 // that the font is italic or oblique. So, if we see a matrix, we don't
311 // believe that it's italic.
312 FcValue matrix;
313 const bool have_matrix = FcPatternGet(font, FC_MATRIX, 0, &matrix) == 0;
314
315 // If we ask for an italic font, fontconfig might take a roman font and set
316 // FC_EMBOLDEN.
317 FcValue embolden;
318 const bool have_embolden = FcPatternGet(font, FC_EMBOLDEN, 0, &embolden) == 0;
319
320 int styleBits = 0;
321 if (resulting_bold > FC_WEIGHT_MEDIUM && !have_embolden) {
322 styleBits |= SkTypeface::kBold;
323 }
324 if (resulting_italic > FC_SLANT_ROMAN && !have_matrix) {
325 styleBits |= SkTypeface::kItalic;
326 }
327
328 *font_family = reinterpret_cast<char*>(c_family);
329 *style = (SkTypeface::Style)styleBits;
330 return true;
331}
332
333} // anonymous namespace
334
335///////////////////////////////////////////////////////////////////////////////
336
337#define kMaxFontFamilyLength 1024
338
339SkFontConfigInterfaceDirect::SkFontConfigInterfaceDirect() : next_file_id_(0) {
340 FcInit();
341}
342
343SkFontConfigInterfaceDirect::~SkFontConfigInterfaceDirect() {
344}
345
346bool SkFontConfigInterfaceDirect::match(const char familyName[],
347 SkTypeface::Style style,
348 unsigned* result_filefaceid,
349 SkTypeface::Style* result_style) {
350 if (NULL == familyName) {
351 familyName = "sans-serif";
352 }
353 size_t familyLen = strlen(familyName);
354 if (familyLen > kMaxFontFamilyLength) {
355 return false;
356 }
357
358 SkAutoMutexAcquire ac(mutex_);
359
360 // search our cache
361 {
362 FontMatchKey key = FontMatchKey(familyName, style);
363 const std::map<FontMatchKey, FontMatch>::const_iterator i =
364 font_match_cache_.find(key);
365 if (i != font_match_cache_.end()) {
366 *result_style = i->second.style;
367 *result_filefaceid = i->second.filefaceid;
368 return true;
369 }
370 }
371
372 FcPattern* pattern = FcPatternCreate();
373
374 FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
375 FcPatternAddInteger(pattern, FC_WEIGHT,
376 (style & SkTypeface::kBold) ? FC_WEIGHT_BOLD
377 : FC_WEIGHT_NORMAL);
378 FcPatternAddInteger(pattern, FC_SLANT,
379 (style & SkTypeface::kItalic) ? FC_SLANT_ITALIC
380 : FC_SLANT_ROMAN);
381 FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
382
383 FcConfigSubstitute(NULL, pattern, FcMatchPattern);
384 FcDefaultSubstitute(pattern);
385
386 // Font matching:
387 // CSS often specifies a fallback list of families:
388 // font-family: a, b, c, serif;
389 // However, fontconfig will always do its best to find *a* font when asked
390 // for something so we need a way to tell if the match which it has found is
391 // "good enough" for us. Otherwise, we can return NULL which gets piped up
392 // and lets WebKit know to try the next CSS family name. However, fontconfig
393 // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
394 // wish to support that.
395 //
396 // Thus, if a specific family is requested we set @family_requested. Then we
397 // record two strings: the family name after config processing and the
398 // family name after resolving. If the two are equal, it's a good match.
399 //
400 // So consider the case where a user has mapped Arial to Helvetica in their
401 // config.
402 // requested family: "Arial"
403 // post_config_family: "Helvetica"
404 // post_match_family: "Helvetica"
405 // -> good match
406 //
407 // and for a missing font:
408 // requested family: "Monaco"
409 // post_config_family: "Monaco"
410 // post_match_family: "Times New Roman"
411 // -> BAD match
412 //
413 // However, we special-case fallback fonts; see IsFallbackFontAllowed().
414 FcChar8* post_config_family;
415 FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
416
417 FcResult result;
418 FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
419 if (!font_set) {
420 FcPatternDestroy(pattern);
421 return false;
422 }
423
424 FcPattern* match = MatchFont(font_set, post_config_family, familyName);
425 if (!match) {
426 FcPatternDestroy(pattern);
427 FcFontSetDestroy(font_set);
428 return false;
429 }
430
431 FcPatternDestroy(pattern);
432
433 FcChar8* c_filename;
434 if (FcPatternGetString(match, FC_FILE, 0, &c_filename) != FcResultMatch) {
435 FcFontSetDestroy(font_set);
436 return false;
437 }
438 int face_index;
439 if (FcPatternGetInteger(match, FC_INDEX, 0, &face_index) != FcResultMatch) {
440 FcFontSetDestroy(font_set);
441 return false;
442 }
443
444 FontMatch font_match;
445 {
446 unsigned out_fileid;
447 const std::string filename(reinterpret_cast<char*>(c_filename));
448 const std::map<std::string, unsigned>::const_iterator
449 i = filename_to_fileid_.find(filename);
450 if (i == filename_to_fileid_.end()) {
451 out_fileid = next_file_id_++;
452 filename_to_fileid_[filename] = out_fileid;
453 fileid_to_filename_[out_fileid] = filename;
454 } else {
455 out_fileid = i->second;
456 }
457 // fileid stored in filename_to_fileid_ and fileid_to_filename_ is
458 // unique only up to the font file. We have to encode face_index for
459 // the out param.
460 font_match.filefaceid =
461 FileIdAndFaceIndexToFileFaceId(out_fileid, face_index);
462 }
463
464 bool success = GetFontProperties(match,
465 &font_match.family,
466 &font_match.style);
467 FcFontSetDestroy(font_set);
468
469 if (success) {
470 font_match_cache_[FontMatchKey(familyName, style)] = font_match;
471 *result_filefaceid = font_match.filefaceid;
472 *result_style = font_match.style;
473 }
474
475 return success;
476}
477
478bool SkFontConfigInterfaceDirect::getFamilyName(unsigned filefaceid,
479 SkString* result_family) {
480 SkAutoMutexAcquire ac(mutex_);
481
482 FcPattern* pattern = FcPatternCreate();
483
484 {
485 const std::map<unsigned, std::string>::const_iterator
486 i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
487 if (i == fileid_to_filename_.end()) {
488 FcPatternDestroy(pattern);
489 return false;
490 }
491 int face_index = filefaceid & 0xfu;
492 FcPatternAddString(pattern, FC_FILE,
493 reinterpret_cast<const FcChar8*>(i->second.c_str()));
494 // face_index is added only when family is empty because it is not
495 // necessary to uniquiely identify a font if both file and
496 // family are given.
497 FcPatternAddInteger(pattern, FC_INDEX, face_index);
498 }
499
500 FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
501
502 FcConfigSubstitute(NULL, pattern, FcMatchPattern);
503 FcDefaultSubstitute(pattern);
504
505 // Font matching:
506 // CSS often specifies a fallback list of families:
507 // font-family: a, b, c, serif;
508 // However, fontconfig will always do its best to find *a* font when asked
509 // for something so we need a way to tell if the match which it has found is
510 // "good enough" for us. Otherwise, we can return NULL which gets piped up
511 // and lets WebKit know to try the next CSS family name. However, fontconfig
512 // configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
513 // wish to support that.
514 //
515 // Thus, if a specific family is requested we set @family_requested. Then we
516 // record two strings: the family name after config processing and the
517 // family name after resolving. If the two are equal, it's a good match.
518 //
519 // So consider the case where a user has mapped Arial to Helvetica in their
520 // config.
521 // requested family: "Arial"
522 // post_config_family: "Helvetica"
523 // post_match_family: "Helvetica"
524 // -> good match
525 //
526 // and for a missing font:
527 // requested family: "Monaco"
528 // post_config_family: "Monaco"
529 // post_match_family: "Times New Roman"
530 // -> BAD match
531 //
532 // However, we special-case fallback fonts; see IsFallbackFontAllowed().
533 FcChar8* post_config_family;
534 FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
535SkDebugf("--- post_config_family <%s>\n", post_config_family);
536 FcResult result;
537 FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
538 if (!font_set) {
539 FcPatternDestroy(pattern);
540 return false;
541 }
542
543 FcPattern* match = MatchFont(font_set, post_config_family, (const char*)post_config_family);
544 if (!match) {
545 FcPatternDestroy(pattern);
546 FcFontSetDestroy(font_set);
547 return false;
548 }
549
550 FcPatternDestroy(pattern);
551
552 FontMatch font_match;
553 font_match.filefaceid = filefaceid;
554
555 bool success = GetFontProperties(match,
556 &font_match.family,
557 &font_match.style);
558 FcFontSetDestroy(font_set);
559
560 if (success) {
561SkDebugf("--- font_match.family <%s>\n", font_match.family.c_str());
562 result_family->set(font_match.family.c_str());
563 }
564
565 return success;
566}
567
568SkStream* SkFontConfigInterfaceDirect::openStream(unsigned filefaceid) {
569 SkAutoMutexAcquire ac(mutex_);
570 const std::map<unsigned, std::string>::const_iterator
571 i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
572 if (i == fileid_to_filename_.end()) {
573 return NULL;
574 }
575 int fd = open(i->second.c_str(), O_RDONLY);
576 return (fd >= 0) ? SkNEW_ARGS(SkFDStream, (fd, true)) : NULL;
577}
578
579