Skip to main content

valo_fontmgr/
android.rs

1//! Android's font configuration as the font manager.
2//!
3//! Android exposes no font API to a native program. It ships its fonts as a directory of
4//! files and one XML file that describes them, and every text stack on the platform reads
5//! that file, Skia's `SkFontMgr_android` included. It carries what the platform decides
6//! and a directory scan cannot know: which family a name such as `sans-serif` means, the
7//! other names that answer to it, and the order faces are tried in for a character the
8//! requested family has no glyph for.
9//!
10//! The file lists two kinds of family. A named one is what a request for that name
11//! answers with. An unnamed one is a link in the fallback chain, tagged with the
12//! languages it is for, and those are tried in the order the file lists them — the order
13//! the platform chose.
14
15use std::collections::HashMap;
16use std::path::PathBuf;
17
18use crate::files::{self, Files};
19use crate::{FontManager, Slant, Style, Typeface, Watch, NORMAL_WIDTH};
20
21/// Where the platform publishes its font configuration.
22const CONFIG: &str = "/system/etc/fonts.xml";
23/// Where the files the configuration names live.
24const FONT_DIR: &str = "/system/fonts";
25/// The family Android's user interface is set in, and what an unnamed request means.
26const DEFAULT_FAMILY: &str = "sans-serif";
27
28/// `Android` is the platform's font manager on Android.
29///
30/// The configuration is read once and not changed after; a font file is read the first
31/// time one of its faces is answered, under the lock of its map of read files. Skia's
32/// Android port needs no lock because it opens every file when it is made; this one keeps
33/// reading a file on first use instead. It builds on every system, since it reads files rather than calling an API,
34/// so a tool that cross-compiles for Android can read a configuration of its own with
35/// [`from_config`](Android::from_config); on a system that has no such file it knows no
36/// faces.
37pub struct Android {
38    families: Vec<Family>,
39    /// Every name a request may use — a family's own and each alias — lower-cased.
40    by_name: HashMap<String, Named>,
41    /// The families with no name of their own, in the order the configuration lists them:
42    /// the chain a character not covered by the requested family is looked for along.
43    fallback: Vec<usize>,
44    files: Files,
45    dir: PathBuf,
46}
47
48/// One family as the configuration lists it.
49struct Family {
50    /// The name a request answers to, or `None` for a link in the fallback chain.
51    name: Option<String>,
52    /// The languages this family is for, as the configuration tags them: a BCP 47 tag
53    /// such as `ja`, or `und-Arab` for a script with no language of its own.
54    languages: Vec<String>,
55    faces: Vec<Face>,
56}
57
58/// One face: the file it lives in, and the style the configuration gives it.
59struct Face {
60    file: String,
61    /// The face's index in a collection file; 0 for a file holding one face.
62    index: u32,
63    style: Style,
64}
65
66/// What a name resolves to: a family, and the one weight an alias narrows it to.
67#[derive(Clone, Copy)]
68struct Named {
69    family: usize,
70    /// `Some` for an alias that names one weight of its target, as `sans-serif-light`
71    /// names the 300 of `sans-serif`.
72    weight: Option<u16>,
73}
74
75impl Android {
76    /// `new` reads the platform's configuration now. It touches the file system, so read
77    /// it once and keep it.
78    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    /// `from_config` reads a configuration whose files live in `dir`, for a test and for a
84    /// system that keeps them elsewhere.
85    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        // An alias names a family that the configuration lists before it, and may name
100        // another alias; resolving in order therefore reaches the family either way.
101        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    /// The family a name means, with the weight an alias narrows it to.
129    fn named(&self, name: &str) -> Option<Named> {
130        self.by_name.get(&name.to_lowercase()).copied()
131    }
132
133    /// The faces of a family as typefaces, one per file rather than one per entry: a
134    /// variable file is listed once per weight it can be set to, and those weights are the
135    /// file's own to answer, not this manager's to multiply.
136    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    /// The families a character is looked for in, most preferred first: the requested one,
166    /// then the fallback chain with the links for the preferred languages brought forward,
167    /// then everything else the configuration lists.
168    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            // Nearest first, so the face answered is the closest one that covers.
223            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    /// Android's user-interface font is the default family; the platform names no size at
235    /// which it changes, as Apple's does.
236    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    /// The platform's fonts are part of the system image and do not change while it runs.
256    fn watch(&self, _on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch> {
257        None
258    }
259}
260
261/// Whether a family is for `locale`: the configuration tags a family with the language it
262/// serves, and a tag covers a locale that begins with it, so `zh-Hans` covers
263/// `zh-Hans-CN`. A tag for a script alone, `und-Arab`, names no language and is reached by
264/// coverage instead.
265fn 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/// What the configuration says, as this manager reads it.
274#[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
286/// Reads the part of the configuration this manager uses: `<family>`, its `<font>`
287/// children, and `<alias>`. The rest of the file — the axis values a variable file is set
288/// to, the PostScript names, which family a face is a fallback for — is skipped, because
289/// the font file answers for itself once it is read.
290fn 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
347/// A `<font>` and the file name that follows it. A face with no file names nothing and is
348/// dropped.
349fn 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
372/// One tag of the configuration, with the text that follows it up to the next one.
373struct Tag<'a> {
374    name: &'a str,
375    /// Everything between the tag's name and its end, for [`attribute`] to read.
376    attributes: &'a str,
377    /// Whether this is a closing tag, `</family>`.
378    closing: bool,
379    /// The text between this tag and the next, which for a `<font>` is its file name.
380    text: &'a str,
381}
382
383/// The configuration's tags in order. Android generates this file, so it is the plain
384/// subset of XML the generator writes: no namespaces, no entities, no comments inside a
385/// tag.
386struct 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
423/// The value of one attribute, read attribute by attribute so that a name is never found
424/// inside a longer one: `name` is not `postScriptName`.
425fn 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    /// The shapes Android's own file uses: a variable family listed once per weight, a
450    /// static family of four files, a collection face with an index, aliases with and
451    /// without a weight, and fallback families tagged by language and by script.
452    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}