/
font_list.rs
554 lines (493 loc) · 18 KB
/
font_list.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::cell::RefCell;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use text::util::is_cjk;
use ucd::{Codepoint, UnicodeBlock};
use xml5ever::Attribute;
use xml5ever::driver::parse_document;
use xml5ever::rcdom::*;
use xml5ever::rcdom::{Node, RcDom};
use xml5ever::tendril::TendrilSink;
lazy_static! {
static ref FONT_LIST: FontList = FontList::new();
}
// Android doesn't provide an API to query system fonts until Android O:
// https://developer.android.com/reference/android/text/FontConfig.html
// System font configuration files must be parsed until Android O version is set as the minimum target.
// Android uses XML files to handle font mapping configurations.
// On Android API 21+ font mappings are loaded from /etc/fonts.xml.
// Each entry consists of a family with various font names, or a font alias.
// Example:
// <familyset>
// <!-- first font is default -->
// <family name="sans-serif">
// <font weight="100" style="normal">Roboto-Thin.ttf</font>
// <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
// <font weight="300" style="normal">Roboto-Light.ttf</font>
// <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
// <font weight="400" style="normal">Roboto-Regular.ttf</font>
// <font weight="400" style="italic">Roboto-Italic.ttf</font>
// <font weight="500" style="normal">Roboto-Medium.ttf</font>
// <font weight="500" style="italic">Roboto-MediumItalic.ttf</font>
// <font weight="900" style="normal">Roboto-Black.ttf</font>
// <font weight="900" style="italic">Roboto-BlackItalic.ttf</font>
// <font weight="700" style="normal">Roboto-Bold.ttf</font>
// <font weight="700" style="italic">Roboto-BoldItalic.ttf</font>
// </family>//
// <!-- Note that aliases must come after the fonts they reference. -->
// <alias name="sans-serif-thin" to="sans-serif" weight="100" />
// <alias name="sans-serif-light" to="sans-serif" weight="300" />
// <alias name="sans-serif-medium" to="sans-serif" weight="500" />
// <alias name="sans-serif-black" to="sans-serif" weight="900" />
// <alias name="arial" to="sans-serif" />
// <alias name="helvetica" to="sans-serif" />
// <alias name="tahoma" to="sans-serif" />
// <alias name="verdana" to="sans-serif" />
// <family name="sans-serif-condensed">
// <font weight="300" style="normal">RobotoCondensed-Light.ttf</font>
// <font weight="300" style="italic">RobotoCondensed-LightItalic.ttf</font>
// <font weight="400" style="normal">RobotoCondensed-Regular.ttf</font>
// <font weight="400" style="italic">RobotoCondensed-Italic.ttf</font>
// <font weight="700" style="normal">RobotoCondensed-Bold.ttf</font>
// <font weight="700" style="italic">RobotoCondensed-BoldItalic.ttf</font>
// </family>
// <alias name="sans-serif-condensed-light" to="sans-serif-condensed" weight="300" />
// </familyset>
// On Android API 17-20 font mappings are loaded from /system/etc/system_fonts.xml
// Each entry consists of a family with a nameset and a fileset.
// Example:
// <familyset>
// <family>
// <nameset>
// <name>sans-serif</name>
// <name>arial</name>
// <name>helvetica</name>
// <name>tahoma</name>
// <name>verdana</name>
// </nameset>
// <fileset>
// <file>Roboto-Regular.ttf</file>
// <file>Roboto-Bold.ttf</file>
// <file>Roboto-Italic.ttf</file>
// <file>Roboto-BoldItalic.ttf</file>
// </fileset>
// </family>//
// <family>
// <nameset>
// <name>sans-serif-light</name>
// </nameset>
// <fileset>
// <file>Roboto-Light.ttf</file>
// <file>Roboto-LightItalic.ttf</file>
// </fileset>
// </family>//
// <family>
// <nameset>
// <name>sans-serif-thin</name>
// </nameset>
// <fileset>
// <file>Roboto-Thin.ttf</file>
// <file>Roboto-ThinItalic.ttf</file>
// </fileset>
// </family>
// </familyset>
struct Font {
filename: String,
weight: Option<i32>,
}
struct FontFamily {
name: String,
fonts: Vec<Font>,
}
struct FontAlias {
from: String,
to: String,
weight: Option<i32>,
}
struct FontList {
families: Vec<FontFamily>,
aliases: Vec<FontAlias>,
}
impl FontList {
fn new() -> FontList {
// Possible paths containing the font mapping xml file.
let paths = ["/etc/fonts.xml", "/system/etc/system_fonts.xml"];
// Try to load and parse paths until one of them success.
let mut result = None;
paths.iter().all(|path| {
result = Self::from_path(path);
!result.is_some()
});
match result {
Some(result) => result,
// If no xml mapping file is found fallback to some default
// fonts expected to be on all Android devices.
None => FontList {
families: Self::fallback_font_families(),
aliases: Vec::new(),
},
}
}
// Creates a new FontList from a path to the font mapping xml file.
fn from_path(path: &str) -> Option<FontList> {
let xml = match Self::load_file(path) {
Ok(xml) => xml,
_ => {
return None;
},
};
let dom: RcDom = parse_document(RcDom::default(), Default::default()).one(xml);
let doc = &dom.document;
// find familyset root node
let children = doc.children.borrow();
let familyset = children.iter().find(|child| match child.data {
NodeData::Element { ref name, .. } => &*name.local == "familyset",
_ => false,
});
let familyset = match familyset {
Some(node) => node,
_ => {
return None;
},
};
// Parse familyset node
let mut families = Vec::new();
let mut aliases = Vec::new();
for node in familyset.children.borrow().iter() {
match node.data {
NodeData::Element {
ref name,
ref attrs,
..
} => {
if &*name.local == "family" {
Self::parse_family(&node, attrs, &mut families);
} else if &*name.local == "alias" {
// aliases come after the fonts they reference. -->
if !families.is_empty() {
Self::parse_alias(attrs, &mut aliases);
}
}
},
_ => {},
}
}
Some(FontList {
families: families,
aliases: aliases,
})
}
// Fonts expected to exist in Android devices.
// Only used in the unlikely case where no font xml mapping files are found.
fn fallback_font_families() -> Vec<FontFamily> {
let alternatives = [
("sans-serif", "Roboto-Regular.ttf"),
("Droid Sans", "DroidSans.ttf"),
];
alternatives
.iter()
.filter(|item| Path::new(&Self::font_absolute_path(item.1)).exists())
.map(|item| FontFamily {
name: item.0.into(),
fonts: vec![Font {
filename: item.1.into(),
weight: None,
}],
}).collect()
}
// All Android fonts are located in /system/fonts
fn font_absolute_path(filename: &str) -> String {
format!("/system/fonts/{}", filename)
}
fn find_family(&self, name: &str) -> Option<&FontFamily> {
self.families.iter().find(|f| f.name == name)
}
fn find_alias(&self, name: &str) -> Option<&FontAlias> {
self.aliases.iter().find(|f| f.from == name)
}
fn load_file(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
// Parse family and font file names
// Example:
// <family name="sans-serif">
// <font weight="100" style="normal">Roboto-Thin.ttf</font>
// <font weight="100" style="italic">Roboto-ThinItalic.ttf</font>
// <font weight="300" style="normal">Roboto-Light.ttf</font>
// <font weight="300" style="italic">Roboto-LightItalic.ttf</font>
// <font weight="400" style="normal">Roboto-Regular.ttf</font>
// </family>
fn parse_family(familyset: &Node, attrs: &RefCell<Vec<Attribute>>, out: &mut Vec<FontFamily>) {
// Fallback to old Android API v17 xml format if required
let using_api_17 = familyset
.children
.borrow()
.iter()
.any(|node| match node.data {
NodeData::Element { ref name, .. } => &*name.local == "nameset",
_ => false,
});
if using_api_17 {
Self::parse_family_v17(familyset, out);
return;
}
// Parse family name
let name = match Self::find_attrib("name", attrs) {
Some(name) => name,
_ => {
return;
},
};
let mut fonts = Vec::new();
// Parse font variants
for node in familyset.children.borrow().iter() {
match node.data {
NodeData::Element {
ref name,
ref attrs,
..
} => {
if &*name.local == "font" {
FontList::parse_font(&node, attrs, &mut fonts);
}
},
_ => {},
}
}
out.push(FontFamily {
name: name,
fonts: fonts,
});
}
// Parse family and font file names for Androi API < 21
// Example:
// <family>
// <nameset>
// <name>sans-serif</name>
// <name>arial</name>
// <name>helvetica</name>
// <name>tahoma</name>
// <name>verdana</name>
// </nameset>
// <fileset>
// <file>Roboto-Regular.ttf</file>
// <file>Roboto-Bold.ttf</file>
// <file>Roboto-Italic.ttf</file>
// <file>Roboto-BoldItalic.ttf</file>
// </fileset>
// </family>
fn parse_family_v17(familyset: &Node, out: &mut Vec<FontFamily>) {
let mut nameset = Vec::new();
let mut fileset = Vec::new();
for node in familyset.children.borrow().iter() {
match node.data {
NodeData::Element { ref name, .. } => {
if &*name.local == "nameset" {
Self::collect_contents_with_tag(node, "name", &mut nameset);
} else if &*name.local == "fileset" {
Self::collect_contents_with_tag(node, "file", &mut fileset);
}
},
_ => {},
}
}
// Create a families for each variation
for name in nameset {
let fonts: Vec<Font> = fileset
.iter()
.map(|f| Font {
filename: f.clone(),
weight: None,
}).collect();
if !fonts.is_empty() {
out.push(FontFamily {
name: name,
fonts: fonts,
})
}
}
}
// Example:
// <font weight="100" style="normal">Roboto-Thin.ttf</font>
fn parse_font(node: &Node, attrs: &RefCell<Vec<Attribute>>, out: &mut Vec<Font>) {
// Parse font filename
let filename = match Self::text_content(node) {
Some(filename) => filename,
_ => {
return;
},
};
// Parse font weight
let weight = Self::find_attrib("weight", attrs).and_then(|w| w.parse().ok());
out.push(Font {
filename: filename,
weight: weight,
})
}
// Example:
// <alias name="sans-serif-thin" to="sans-serif" weight="100" />
// <alias name="sans-serif-light" to="sans-serif" weight="300" />
// <alias name="sans-serif-medium" to="sans-serif" weight="500" />
// <alias name="sans-serif-black" to="sans-serif" weight="900" />
// <alias name="arial" to="sans-serif" />
// <alias name="helvetica" to="sans-serif" />
// <alias name="tahoma" to="sans-serif" />
// <alias name="verdana" to="sans-serif" />
fn parse_alias(attrs: &RefCell<Vec<Attribute>>, out: &mut Vec<FontAlias>) {
// Parse alias name and referenced font
let from = match Self::find_attrib("name", attrs) {
Some(from) => from,
_ => {
return;
},
};
// Parse referenced font
let to = match Self::find_attrib("to", attrs) {
Some(to) => to,
_ => {
return;
},
};
// Parse optional weight filter
let weight = Self::find_attrib("weight", attrs).and_then(|w| w.parse().ok());
out.push(FontAlias {
from: from,
to: to,
weight: weight,
})
}
fn find_attrib(name: &str, attrs: &RefCell<Vec<Attribute>>) -> Option<String> {
attrs
.borrow()
.iter()
.find(|attr| &*attr.name.local == name)
.map(|s| String::from(&s.value))
}
fn text_content(node: &Node) -> Option<String> {
node.children
.borrow()
.get(0)
.and_then(|child| match child.data {
NodeData::Text { ref contents } => {
let mut result = String::new();
result.push_str(&contents.borrow());
Some(result)
},
_ => None,
})
}
fn collect_contents_with_tag(node: &Node, tag: &str, out: &mut Vec<String>) {
for child in node.children.borrow().iter() {
match child.data {
NodeData::Element { ref name, .. } => {
if &*name.local == tag {
if let Some(content) = Self::text_content(child) {
out.push(content);
}
}
},
_ => {},
}
}
}
}
// Functions used by FontCacheThread
pub fn for_each_available_family<F>(mut callback: F)
where
F: FnMut(String),
{
for family in &FONT_LIST.families {
callback(family.name.clone());
}
for alias in &FONT_LIST.aliases {
callback(alias.from.clone());
}
}
pub fn for_each_variation<F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
if let Some(family) = FONT_LIST.find_family(family_name) {
for font in &family.fonts {
callback(FontList::font_absolute_path(&font.filename));
}
return;
}
if let Some(alias) = FONT_LIST.find_alias(family_name) {
if let Some(family) = FONT_LIST.find_family(&alias.to) {
for font in &family.fonts {
match (alias.weight, font.weight) {
(None, _) => callback(FontList::font_absolute_path(&font.filename)),
(Some(w1), Some(w2)) => {
if w1 == w2 {
callback(FontList::font_absolute_path(&font.filename))
}
},
_ => {},
}
}
}
}
}
pub fn system_default_family(generic_name: &str) -> Option<String> {
if let Some(family) = FONT_LIST.find_family(&generic_name) {
Some(family.name.clone())
} else if let Some(alias) = FONT_LIST.find_alias(&generic_name) {
Some(alias.from.clone())
} else {
// First font defined in the fonts.xml is the default on Android.
FONT_LIST.families.get(0).map(|family| family.name.clone())
}
}
// Based on gfxAndroidPlatform::GetCommonFallbackFonts() in Gecko
pub fn fallback_font_families(codepoint: Option<char>) -> Vec<&'static str> {
let mut families = vec![];
if let Some(block) = codepoint.and_then(|c| c.block()) {
match block {
UnicodeBlock::Armenian => {
families.push("Droid Sans Armenian");
},
UnicodeBlock::Hebrew => {
families.push("Droid Sans Hebrew");
},
UnicodeBlock::Arabic => {
families.push("Droid Sans Arabic");
},
UnicodeBlock::Devanagari => {
families.push("Noto Sans Devanagari");
families.push("Droid Sans Devanagari");
},
UnicodeBlock::Tamil => {
families.push("Noto Sans Tamil");
families.push("Droid Sans Tamil");
},
UnicodeBlock::Thai => {
families.push("Noto Sans Thai");
families.push("Droid Sans Thai");
},
UnicodeBlock::Georgian | UnicodeBlock::GeorgianSupplement => {
families.push("Droid Sans Georgian");
},
UnicodeBlock::Ethiopic | UnicodeBlock::EthiopicSupplement => {
families.push("Droid Sans Ethiopic");
},
_ => {
if is_cjk(codepoint.unwrap()) {
families.push("MotoyaLMaru");
families.push("Noto Sans CJK JP");
families.push("Droid Sans Japanese");
}
},
}
}
families.push("Droid Sans Fallback");
families
}
pub static SANS_SERIF_FONT_FAMILY: &'static str = "sans-serif";