1use std::collections::HashMap;
16use std::path::PathBuf;
17
18use crate::files::{self, Files};
19use crate::{FontManager, Slant, Style, Typeface, Watch, NORMAL_WIDTH};
20
21const CONFIG: &str = "/system/etc/fonts.xml";
23const FONT_DIR: &str = "/system/fonts";
25const DEFAULT_FAMILY: &str = "sans-serif";
27
28pub struct Android {
38 families: Vec<Family>,
39 by_name: HashMap<String, Named>,
41 fallback: Vec<usize>,
44 files: Files,
45 dir: PathBuf,
46}
47
48struct Family {
50 name: Option<String>,
52 languages: Vec<String>,
55 faces: Vec<Face>,
56}
57
58struct Face {
60 file: String,
61 index: u32,
63 style: Style,
64}
65
66#[derive(Clone, Copy)]
68struct Named {
69 family: usize,
70 weight: Option<u16>,
73}
74
75impl Android {
76 pub fn new() -> Android {
79 let config = std::fs::read_to_string(CONFIG).unwrap_or_default();
80 Android::from_config(&config, PathBuf::from(FONT_DIR))
81 }
82
83 pub fn from_config(xml: &str, dir: PathBuf) -> Android {
86 let Config { families, aliases } = parse(xml);
87 let mut by_name = HashMap::new();
88 for (index, family) in families.iter().enumerate() {
89 if let Some(name) = &family.name {
90 by_name.insert(
91 name.to_lowercase(),
92 Named {
93 family: index,
94 weight: None,
95 },
96 );
97 }
98 }
99 for alias in aliases {
102 let Some(target) = by_name.get(&alias.to.to_lowercase()).copied() else {
103 continue;
104 };
105 by_name.insert(
106 alias.name.to_lowercase(),
107 Named {
108 family: target.family,
109 weight: alias.weight.or(target.weight),
110 },
111 );
112 }
113 let fallback = families
114 .iter()
115 .enumerate()
116 .filter(|(_, family)| family.name.is_none())
117 .map(|(index, _)| index)
118 .collect();
119 Android {
120 families,
121 by_name,
122 fallback,
123 files: Files::default(),
124 dir,
125 }
126 }
127
128 fn named(&self, name: &str) -> Option<Named> {
130 self.by_name.get(&name.to_lowercase()).copied()
131 }
132
133 fn typefaces(&self, named: Named) -> Vec<Typeface> {
137 let family = &self.families[named.family];
138 let name = family.name.clone().unwrap_or_default();
139 let mut wanted: Vec<(String, u32, Style)> = Vec::new();
140 for face in &family.faces {
141 if named
142 .weight
143 .is_some_and(|weight| face.style.weight != weight)
144 {
145 continue;
146 }
147 if !wanted
148 .iter()
149 .any(|(file, index, _)| *file == face.file && *index == face.index)
150 {
151 wanted.push((face.file.clone(), face.index, face.style));
152 }
153 }
154 wanted
155 .into_iter()
156 .filter_map(|(file, index, style)| self.typeface(&name, &file, index, style))
157 .collect()
158 }
159
160 fn typeface(&self, family: &str, file: &str, index: u32, style: Style) -> Option<Typeface> {
161 let data = self.files.read(&self.dir.join(file))?;
162 Some(Typeface::new(data, index, family, style))
163 }
164
165 fn search_order(&self, family: Option<&str>, locales: &[&str]) -> Vec<usize> {
169 let mut order: Vec<usize> = Vec::new();
170 let push = |index: usize, order: &mut Vec<usize>| {
171 if !order.contains(&index) {
172 order.push(index);
173 }
174 };
175 if let Some(named) = family.and_then(|name| self.named(name)) {
176 push(named.family, &mut order);
177 }
178 for locale in locales {
179 for &index in &self.fallback {
180 if speaks(&self.families[index], locale) {
181 push(index, &mut order);
182 }
183 }
184 }
185 for &index in &self.fallback {
186 push(index, &mut order);
187 }
188 for index in 0..self.families.len() {
189 push(index, &mut order);
190 }
191 order
192 }
193}
194
195impl Default for Android {
196 fn default() -> Android {
197 Android::new()
198 }
199}
200
201impl FontManager for Android {
202 fn family(&self, family: &str) -> Vec<Typeface> {
203 match self.named(family) {
204 Some(named) => self.typefaces(named),
205 None => Vec::new(),
206 }
207 }
208
209 fn match_character(
210 &self,
211 family: Option<&str>,
212 style: Style,
213 locales: &[&str],
214 character: char,
215 ) -> Option<Typeface> {
216 for index in self.search_order(family, locales) {
217 let named = Named {
218 family: index,
219 weight: None,
220 };
221 let mut faces = self.typefaces(named);
222 faces.sort_by_key(|face| face.style().distance(style));
224 if let Some(covering) = faces
225 .into_iter()
226 .find(|face| files::covers(face.data(), face.index(), character))
227 {
228 return Some(covering);
229 }
230 }
231 None
232 }
233
234 fn system_font(&self, _size: f32, style: Style) -> Option<Typeface> {
237 crate::nearest(self.family(DEFAULT_FAMILY), style)
238 }
239
240 fn families(&self) -> Vec<String> {
241 let mut names: Vec<String> = self
242 .families
243 .iter()
244 .filter_map(|family| family.name.clone())
245 .collect();
246 names.sort();
247 names.dedup();
248 names
249 }
250
251 fn face_count(&self) -> usize {
252 self.families.iter().map(|family| family.faces.len()).sum()
253 }
254
255 fn watch(&self, _on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch> {
257 None
258 }
259}
260
261fn speaks(family: &Family, locale: &str) -> bool {
266 let locale = locale.to_lowercase();
267 family.languages.iter().any(|language| {
268 let language = language.to_lowercase();
269 locale == language || locale.starts_with(&format!("{language}-"))
270 })
271}
272
273#[derive(Default)]
275struct Config {
276 families: Vec<Family>,
277 aliases: Vec<Alias>,
278}
279
280struct Alias {
281 name: String,
282 to: String,
283 weight: Option<u16>,
284}
285
286fn parse(xml: &str) -> Config {
291 let mut config = Config::default();
292 let mut family: Option<Family> = None;
293 for tag in Tags::new(xml) {
294 match tag.name {
295 "family" if tag.closing => {
296 if let Some(family) = family.take() {
297 config.families.push(family);
298 }
299 }
300 "family" => {
301 if let Some(family) = family.take() {
302 config.families.push(family);
303 }
304 family = Some(Family {
305 name: attribute(tag.attributes, "name"),
306 languages: attribute(tag.attributes, "lang")
307 .into_iter()
308 .flat_map(|langs| {
309 langs
310 .split(',')
311 .map(str::trim)
312 .filter(|lang| !lang.is_empty())
313 .map(str::to_owned)
314 .collect::<Vec<String>>()
315 })
316 .collect(),
317 faces: Vec::new(),
318 });
319 }
320 "font" if !tag.closing => {
321 if let (Some(family), Some(face)) = (family.as_mut(), face_of(&tag)) {
322 family.faces.push(face);
323 }
324 }
325 "alias" if !tag.closing => {
326 if let (Some(name), Some(to)) = (
327 attribute(tag.attributes, "name"),
328 attribute(tag.attributes, "to"),
329 ) {
330 config.aliases.push(Alias {
331 name,
332 to,
333 weight: attribute(tag.attributes, "weight")
334 .and_then(|weight| weight.parse().ok()),
335 });
336 }
337 }
338 _ => {}
339 }
340 }
341 if let Some(family) = family {
342 config.families.push(family);
343 }
344 config
345}
346
347fn face_of(tag: &Tag) -> Option<Face> {
350 let file = tag.text.trim();
351 if file.is_empty() {
352 return None;
353 }
354 Some(Face {
355 file: file.to_owned(),
356 index: attribute(tag.attributes, "index")
357 .and_then(|index| index.parse().ok())
358 .unwrap_or(0),
359 style: Style {
360 weight: attribute(tag.attributes, "weight")
361 .and_then(|weight| weight.parse().ok())
362 .unwrap_or(400),
363 width: NORMAL_WIDTH,
364 slant: match attribute(tag.attributes, "style").as_deref() {
365 Some("italic") => Slant::Italic,
366 _ => Slant::Upright,
367 },
368 },
369 })
370}
371
372struct Tag<'a> {
374 name: &'a str,
375 attributes: &'a str,
377 closing: bool,
379 text: &'a str,
381}
382
383struct Tags<'a> {
387 rest: &'a str,
388}
389
390impl<'a> Tags<'a> {
391 fn new(xml: &'a str) -> Tags<'a> {
392 Tags { rest: xml }
393 }
394}
395
396impl<'a> Iterator for Tags<'a> {
397 type Item = Tag<'a>;
398
399 fn next(&mut self) -> Option<Tag<'a>> {
400 let start = self.rest.find('<')?;
401 let body = &self.rest[start + 1..];
402 let end = body.find('>')?;
403 let (body, after) = (&body[..end], &body[end + 1..]);
404 self.rest = after;
405 let text = match after.find('<') {
406 Some(next) => &after[..next],
407 None => after,
408 };
409 let closing = body.starts_with('/');
410 let body = body.trim_start_matches('/').trim_end_matches('/');
411 let name_end = body
412 .find(|c: char| c.is_ascii_whitespace())
413 .unwrap_or(body.len());
414 Some(Tag {
415 name: &body[..name_end],
416 attributes: &body[name_end..],
417 closing,
418 text,
419 })
420 }
421}
422
423fn attribute(attributes: &str, wanted: &str) -> Option<String> {
426 let mut rest = attributes.trim_start();
427 while !rest.is_empty() {
428 let equals = rest.find('=')?;
429 let name = rest[..equals].trim();
430 let after = rest[equals + 1..].trim_start();
431 let quote = after.chars().next()?;
432 if quote != '"' && quote != '\'' {
433 return None;
434 }
435 let value_end = after[1..].find(quote)?;
436 let value = &after[1..1 + value_end];
437 if name == wanted {
438 return Some(value.to_owned());
439 }
440 rest = after[2 + value_end..].trim_start();
441 }
442 None
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 const CONFIG: &str = r#"<?xml version="1.0" encoding="utf-8"?>
453<familyset version="23">
454 <family name="sans-serif">
455 <font weight="400" style="normal">
456 Roboto-Regular.ttf
457 <axis tag="wght" stylevalue="400"/>
458 </font>
459 <font weight="700" style="normal">
460 Roboto-Regular.ttf
461 <axis tag="wght" stylevalue="700"/>
462 </font>
463 </family>
464 <family name="serif">
465 <font weight="400" style="normal" postScriptName="NotoSerif">NotoSerif-Regular.ttf</font>
466 <font weight="700" style="normal">NotoSerif-Bold.ttf</font>
467 <font weight="400" style="italic">NotoSerif-Italic.ttf</font>
468 </family>
469 <alias name="arial" to="sans-serif"/>
470 <alias name="sans-serif-light" to="sans-serif" weight="300"/>
471 <family lang="ja">
472 <font weight="400" style="normal" index="2" postScriptName="NotoSansCJKJP">NotoSansCJK-Regular.ttc</font>
473 </family>
474 <family lang="und-Arab" variant="elegant">
475 <font weight="400" style="normal">NotoNaskhArabic-Regular.ttf</font>
476 </family>
477</familyset>
478"#;
479
480 fn config() -> Config {
481 parse(CONFIG)
482 }
483
484 fn manager() -> Android {
485 Android::from_config(CONFIG, PathBuf::from("/system/fonts"))
486 }
487
488 #[test]
489 fn a_family_keeps_its_faces_with_their_files_and_styles() {
490 let config = config();
491 let serif = config
492 .families
493 .iter()
494 .find(|family| family.name.as_deref() == Some("serif"))
495 .expect("the named family");
496 assert_eq!(serif.faces.len(), 3);
497 assert_eq!(serif.faces[0].file, "NotoSerif-Regular.ttf");
498 assert_eq!(serif.faces[0].style.weight, 400);
499 assert_eq!(serif.faces[0].style.slant, Slant::Upright);
500 assert_eq!(serif.faces[2].style.slant, Slant::Italic);
501 }
502
503 #[test]
504 fn a_file_name_is_read_past_the_axes_that_follow_it() {
505 let config = config();
506 let sans = &config.families[0];
507 assert_eq!(
508 sans.faces.len(),
509 2,
510 "one entry per weight the file is set to"
511 );
512 for face in &sans.faces {
513 assert_eq!(face.file, "Roboto-Regular.ttf");
514 }
515 }
516
517 #[test]
518 fn a_collection_face_keeps_its_index() {
519 let config = config();
520 let japanese = config
521 .families
522 .iter()
523 .find(|family| family.languages.iter().any(|lang| lang == "ja"))
524 .expect("the fallback family");
525 assert_eq!(japanese.faces[0].index, 2);
526 assert_eq!(japanese.faces[0].file, "NotoSansCJK-Regular.ttc");
527 }
528
529 #[test]
530 fn an_alias_names_a_family_and_may_narrow_it_to_one_weight() {
531 let manager = manager();
532 let plain = manager.named("arial").expect("the alias");
533 assert_eq!(
534 manager.families[plain.family].name.as_deref(),
535 Some("sans-serif")
536 );
537 assert_eq!(plain.weight, None);
538 let light = manager.named("sans-serif-light").expect("the alias");
539 assert_eq!(light.weight, Some(300));
540 }
541
542 #[test]
543 fn a_name_is_matched_whatever_its_case_and_an_unknown_one_answers_nothing() {
544 let manager = manager();
545 assert!(manager.named("SANS-SERIF").is_some());
546 assert!(manager.named("Arial").is_some());
547 assert!(manager.named("comic sans").is_none());
548 assert!(manager.family("comic sans").is_empty());
549 }
550
551 #[test]
552 fn an_attribute_is_not_found_inside_a_longer_one() {
553 let attributes = r#" weight="400" style="normal" postScriptName="NotoSerif""#;
554 assert_eq!(attribute(attributes, "name"), None, "not postScriptName");
555 assert_eq!(
556 attribute(attributes, "postScriptName").as_deref(),
557 Some("NotoSerif")
558 );
559 assert_eq!(attribute(attributes, "weight").as_deref(), Some("400"));
560 }
561
562 #[test]
563 fn the_fallback_chain_is_the_unnamed_families_in_the_order_the_file_lists_them() {
564 let manager = manager();
565 assert_eq!(manager.fallback.len(), 2);
566 for &index in &manager.fallback {
567 assert!(manager.families[index].name.is_none());
568 }
569 }
570
571 #[test]
572 fn a_language_the_configuration_tags_brings_its_family_forward() {
573 let manager = manager();
574 let japanese = manager
575 .fallback
576 .iter()
577 .copied()
578 .find(|&index| speaks(&manager.families[index], "ja-JP"))
579 .expect("the family for the locale");
580 let order = manager.search_order(Some("sans-serif"), &["ja-JP"]);
581 let sans = manager.named("sans-serif").expect("the family").family;
582 assert_eq!(order[0], sans, "the requested family is tried first");
583 assert_eq!(order[1], japanese, "then the chain for the locale");
584 }
585
586 #[test]
587 fn a_script_tagged_family_is_reached_by_coverage_not_by_locale() {
588 let manager = manager();
589 let arabic = manager
590 .families
591 .iter()
592 .find(|family| family.languages.iter().any(|lang| lang == "und-Arab"))
593 .expect("the family");
594 assert!(!speaks(arabic, "ar-EG"));
595 assert!(manager.search_order(None, &["ar-EG"]).len() >= manager.families.len());
596 }
597
598 #[test]
599 fn every_family_is_searched_even_when_no_language_matches() {
600 let manager = manager();
601 let order = manager.search_order(None, &[]);
602 assert_eq!(order.len(), manager.families.len());
603 }
604
605 #[test]
606 fn face_count_is_every_entry_the_configuration_lists() {
607 assert_eq!(manager().face_count(), 7);
608 }
609
610 #[test]
611 fn families_lists_the_named_ones() {
612 assert_eq!(manager().families(), vec!["sans-serif", "serif"]);
613 }
614}