Skip to main content

valo_fontmgr/
scan.rs

1//! A directory scan as the font manager, for platforms without a font API binding yet.
2//!
3//! fontdb walks the platform's font directories, so this backend knows families, styles
4//! and coverage but nothing the operating system decides: no language preference in
5//! fallback, no user-interface font, no change notification.
6//!
7//! It is Skia's `SkFontMgr_custom_directory`: the index is built when the manager is made
8//! and never changed after, so it answers several threads at once with only its map of
9//! read files locked.
10
11use std::sync::Arc;
12
13use crate::files::{self, Files};
14use crate::{FontData, FontManager, Slant, Style, Typeface, Watch, NORMAL_WIDTH};
15
16/// `Scan` is an index of the fonts found under the platform's font directories.
17///
18/// Creating it walks those directories and may block, so create it once.
19pub struct Scan {
20    database: fontdb::Database,
21    files: Files,
22}
23
24impl Scan {
25    /// `load` walks the platform's font directories now.
26    pub fn load() -> Scan {
27        let mut database = fontdb::Database::new();
28        database.load_system_fonts();
29        Scan {
30            database,
31            files: Files::default(),
32        }
33    }
34
35    fn typeface(&self, id: fontdb::ID) -> Option<Typeface> {
36        let face = self.database.face(id)?;
37        let family = face.families.first()?.0.clone();
38        let data = self.data(&face.source)?;
39        Some(Typeface::new(data, face.index, family, style_of(face)))
40    }
41
42    /// The bytes of the file a face was found in, each file mapped once and shared by its
43    /// faces.
44    fn data(&self, source: &fontdb::Source) -> Option<FontData> {
45        match source {
46            fontdb::Source::File(path) => self.files.read(path),
47            fontdb::Source::Binary(data) | fontdb::Source::SharedFile(_, data) => {
48                Some(Arc::clone(data))
49            }
50        }
51    }
52
53    /// Every face, nearest to `style` first, those of `family` before the rest.
54    fn candidates(&self, family: Option<&str>, style: Style) -> Vec<fontdb::ID> {
55        let mut keyed: Vec<(Rank, fontdb::ID)> = self
56            .database
57            .faces()
58            .map(|face| {
59                let in_family = family.is_some_and(|name| answers_to(face, name));
60                ((!in_family, style_of(face).distance(style)), face.id)
61            })
62            .collect();
63        keyed.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
64        keyed.into_iter().map(|(_, id)| id).collect()
65    }
66}
67
68impl FontManager for Scan {
69    fn family(&self, family: &str) -> Vec<Typeface> {
70        let ids: Vec<fontdb::ID> = self
71            .database
72            .faces()
73            .filter(|face| answers_to(face, family))
74            .map(|face| face.id)
75            .collect();
76        ids.into_iter().filter_map(|id| self.typeface(id)).collect()
77    }
78
79    fn match_character(
80        &self,
81        family: Option<&str>,
82        style: Style,
83        _locales: &[&str],
84        character: char,
85    ) -> Option<Typeface> {
86        for id in self.candidates(family, style) {
87            let Some(typeface) = self.typeface(id) else {
88                continue;
89            };
90            if files::covers(typeface.data(), typeface.index(), character) {
91                return Some(typeface);
92            }
93        }
94        None
95    }
96
97    fn system_font(&self, _size: f32, _style: Style) -> Option<Typeface> {
98        None
99    }
100
101    fn families(&self) -> Vec<String> {
102        let mut names: Vec<String> = self
103            .database
104            .faces()
105            .filter_map(|face| face.families.first().map(|(name, _)| name.clone()))
106            .collect();
107        names.sort();
108        names.dedup();
109        names
110    }
111
112    fn face_count(&self) -> usize {
113        self.database.len()
114    }
115
116    fn watch(&self, _on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch> {
117        None
118    }
119}
120
121/// A face's place in a search: outside the requested family first, then by style.
122type Rank = (bool, (u32, u8, u16));
123
124fn answers_to(face: &fontdb::FaceInfo, name: &str) -> bool {
125    face.families
126        .iter()
127        .any(|(family, _)| family.eq_ignore_ascii_case(name))
128}
129
130fn style_of(face: &fontdb::FaceInfo) -> Style {
131    Style {
132        weight: face.weight.0,
133        width: width_percent(face.stretch),
134        slant: match face.style {
135            fontdb::Style::Normal => Slant::Upright,
136            fontdb::Style::Italic => Slant::Italic,
137            fontdb::Style::Oblique => Slant::Oblique,
138        },
139    }
140}
141
142/// The CSS font-width percentage of a `usWidthClass` value.
143fn width_percent(stretch: fontdb::Stretch) -> f32 {
144    match stretch {
145        fontdb::Stretch::UltraCondensed => 50.0,
146        fontdb::Stretch::ExtraCondensed => 62.5,
147        fontdb::Stretch::Condensed => 75.0,
148        fontdb::Stretch::SemiCondensed => 87.5,
149        fontdb::Stretch::Normal => NORMAL_WIDTH,
150        fontdb::Stretch::SemiExpanded => 112.5,
151        fontdb::Stretch::Expanded => 125.0,
152        fontdb::Stretch::ExtraExpanded => 150.0,
153        fontdb::Stretch::UltraExpanded => 200.0,
154    }
155}