Skip to main content

mln_engine/text/system_fonts/
glyphs.rs

1//! The system's font for each cluster of a label, a character and the marks
2//! and joiners after it, which shapes it or draws its glyph.
3//!
4//! The font of a cluster, for a label in a font stack, is the first font the
5//! stack names that the system has and that draws the whole cluster, else
6//! the font the system picks for it at the weight and style of the stack's
7//! first name, else the font of its first character alone. Each name is
8//! looked up once, and a font the system picked for one character of a class
9//! (`class`) serves the others of the class it has, so that a map's labels
10//! look up a few fonts, not one for every character.
11
12use std::sync::Arc;
13
14use mln_style::hash::{HashMap, HashSet};
15use mln_style::i18n;
16
17use crate::text::FontFile;
18use crate::text::font_name::{self, FontName};
19use crate::text::font_stack::FontStack;
20use crate::text::glyph::FontFace;
21use crate::text::local_fonts::FontChooser;
22use crate::text::system_fonts::source::{self, Source};
23use crate::text::system_fonts::{Finder, Query, languages, system};
24
25/// The system's fonts as a [`FontChooser`] (see the module docs). Every
26/// chooser shares the fonts the process has found.
27#[derive(Clone, Copy, Debug, Default)]
28pub struct SystemFonts;
29
30impl FontChooser for SystemFonts {
31    fn choose(&self, font_stack: &FontStack, cluster: &[char]) -> Option<FontFace> {
32        let mut fonts = system().fonts.as_ref()?.lock();
33        Some(font_for(&mut fonts, font_stack, cluster)?.face.clone())
34    }
35}
36
37/// A font the system has, at the weight it was found for.
38pub(crate) struct SystemFont {
39    file: FontFile,
40    face: FontFace,
41}
42
43impl SystemFont {
44    fn draws(&self, cluster: &[char]) -> bool {
45        cluster.iter().all(|&c| self.file.has_char(c))
46    }
47}
48
49/// The platform's font matcher, and the fonts found with it so far.
50pub(crate) struct Fonts {
51    pub(crate) finder: Finder,
52    files: source::Files,
53    /// The font of each font name, if the system has it.
54    named: HashMap<String, Option<Arc<SystemFont>>>,
55    /// The fonts the system picked for each font stack and class of
56    /// characters, in the order found.
57    picked: HashMap<(FontStack, u32), Vec<Arc<SystemFont>>>,
58    /// The clusters that no font draws whole, for each font stack.
59    missing: HashSet<(FontStack, Vec<char>)>,
60}
61
62impl Fonts {
63    /// No fonts found yet with `finder`.
64    pub(crate) fn new(finder: Finder) -> Self {
65        Fonts {
66            finder,
67            files: source::Files::default(),
68            named: HashMap::default(),
69            picked: HashMap::default(),
70            missing: HashSet::default(),
71        }
72    }
73}
74
75/// The font that draws `cluster` for a label in `font_stack` (see the module
76/// docs).
77fn font_for(fonts: &mut Fonts, font_stack: &FontStack, cluster: &[char]) -> Option<Arc<SystemFont>> {
78    let &c = cluster.first()?;
79    let names = names(font_stack);
80    let mut named = Vec::with_capacity(names.len());
81    for (name, parsed) in &names {
82        let font = fonts.named.entry((*name).to_owned()).or_insert_with(|| {
83            first_drawing(&mut fonts.files, named_fonts(&mut fonts.finder, name, parsed), &[' '], parsed.weight)
84        });
85        named.push(font.clone());
86    }
87    let key = (font_stack.clone(), class(c));
88    let picked = fonts.picked.get(&key).map_or(&[][..], Vec::as_slice);
89    if let Some(font) = first_with(&named, picked, |font| font.draws(cluster)) {
90        return Some(Arc::clone(font));
91    }
92    if !fonts.missing.contains(&(font_stack.clone(), cluster.to_vec())) {
93        let first = names.first().map_or(FontName { family: "", weight: 400, italic: false }, |(_, parsed)| *parsed);
94        let candidates = picked_fonts(&mut fonts.finder, &first, c);
95        if let Some(font) = first_drawing(&mut fonts.files, candidates, cluster, first.weight) {
96            fonts.picked.entry(key).or_default().push(Arc::clone(&font));
97            return Some(font);
98        }
99        fonts.missing.insert((font_stack.clone(), cluster.to_vec()));
100    }
101    // A mark that no font draws with its character goes with the
102    // character's font, which draws what it can.
103    if cluster.len() > 1 { font_for(fonts, font_stack, &[c]) } else { None }
104}
105
106/// The first font that has a character, as `has` says: of the stack's
107/// `named` fonts in order, else of the fonts the system `picked`.
108fn first_with<'a, F>(named: &'a [Option<F>], picked: &'a [F], has: impl Fn(&F) -> bool) -> Option<&'a F> {
109    named.iter().flatten().chain(picked).find(|font| has(font))
110}
111
112/// The first of `candidates` that the map can draw `cluster` from, as a face
113/// at `weight`.
114fn first_drawing(
115    files: &mut source::Files,
116    candidates: Vec<(String, Source)>,
117    cluster: &[char],
118    weight: u16,
119) -> Option<Arc<SystemFont>> {
120    candidates.into_iter().find_map(|(_, source)| {
121        let data = files.data(&source)?;
122        let file = FontFile::new(data.clone())?;
123        let face = FontFace::device(&source.url(), weight, data);
124        let font = SystemFont { file, face };
125        font.draws(cluster).then(|| Arc::new(font))
126    })
127}
128
129/// The names of `font_stack` that name a font, with their parts.
130fn names(font_stack: &FontStack) -> Vec<(&str, FontName<'_>)> {
131    font_stack
132        .iter()
133        .filter(|name| !name.trim().is_empty())
134        .map(|name| (name.as_str(), font_name::parse(name)))
135        .collect()
136}
137
138/// The class of `c` whose fonts are found together: CJK ideographs, kana
139/// and hangul (`i18n::allows_fixed_width_glyph_generation`), which a font
140/// for the user's languages draws together; else the 256 code points
141/// around it.
142fn class(c: char) -> u32 {
143    let ideograph = i18n::allows_fixed_width_glyph_generation(c);
144    if ideograph { u32::MAX } else { u32::from(c) >> 8 }
145}
146
147/// The fonts of the family that `name` names, if the system has it, the
148/// weight closest to the name's first, with their family name.
149pub(crate) fn named_fonts(finder: &mut Finder, name: &str, parsed: &FontName<'_>) -> Vec<(String, Source)> {
150    // Every font has a space, so the lookup finds the family whatever it
151    // draws.
152    let query = Query {
153        name: Some(name),
154        family: Some(parsed.family),
155        probe: ' ',
156        languages: &[],
157        weight: parsed.weight,
158        italic: parsed.italic,
159    };
160    let mut candidates = drawn(finder.candidates(&query), ' ', parsed.weight);
161    candidates.retain(|(family, ..)| family.eq_ignore_ascii_case(parsed.family));
162    nearest(candidates, parsed.weight)
163}
164
165/// The fonts the platform picks for `c` in the family, weight and style of
166/// `first`, the font stack's first name, the weight closest to it first,
167/// with their family names.
168pub(crate) fn picked_fonts(finder: &mut Finder, first: &FontName<'_>, c: char) -> Vec<(String, Source)> {
169    let languages = if class(c) == u32::MAX { languages::for_ideographs(&system().preferred) } else { Vec::new() };
170    let query = Query {
171        name: None,
172        family: Some(first.family).filter(|family| !family.is_empty()),
173        probe: c,
174        languages: &languages,
175        weight: first.weight,
176        italic: first.italic,
177    };
178    nearest(drawn(finder.candidates(&query), c, first.weight), first.weight)
179}
180
181/// How many of a lookup's candidates to read.
182pub(crate) const MAX_CANDIDATES: usize = 16;
183
184/// The first of `candidates` that have `c`, with the weight they draw at
185/// when asked for `weight`.
186fn drawn(candidates: Vec<(String, Source)>, c: char, weight: u16) -> Vec<(String, Source, u16)> {
187    candidates
188        .into_iter()
189        .take(MAX_CANDIDATES)
190        .filter_map(|(family, source)| {
191            let drawn = source.drawn_weight(c, weight)?;
192            Some((family, source, drawn))
193        })
194        .collect()
195}
196
197/// `candidates`, those that draw closest to `weight` first, otherwise in
198/// order.
199fn nearest(mut candidates: Vec<(String, Source, u16)>, weight: u16) -> Vec<(String, Source)> {
200    candidates.sort_by_key(|(_, _, drawn)| drawn.abs_diff(weight));
201    candidates.into_iter().map(|(family, source, _)| (family, source)).collect()
202}
203
204#[cfg(test)]
205mod tests {
206    // Which fonts the system has depends on the machine, so the tests check
207    // the fonts it finds, and pass with none; `--nocapture` lists them.
208
209    use std::num::NonZeroU16;
210
211    use super::{SystemFonts, class, first_with, named_fonts, picked_fonts};
212    use crate::text::glyph::{Glyph, GlyphIDType};
213    use crate::text::local_fonts::FontChooser;
214    use crate::text::system_fonts::{Finder, system};
215    use crate::text::{Shaper, font_name};
216
217    fn stack(names: &[&str]) -> Vec<String> {
218        names.iter().map(|name| (*name).to_owned()).collect()
219    }
220
221    /// What `f` finds with the platform's font matcher: `None` without one.
222    fn with_finder<R>(f: impl FnOnce(&mut Finder) -> R) -> Option<R> {
223        Some(f(&mut system().fonts.as_ref()?.lock().finder))
224    }
225
226    /// The glyph that the face chosen for `c` in `font_stack` maps it to.
227    fn chosen_glyph(font_stack: &[&str], c: char) -> Option<Glyph> {
228        let face = SystemFonts.choose(&stack(font_stack), &[c])?;
229        let data = face.data.expect("a device face holds its file");
230        let shaper = Shaper::at_weight(GlyphIDType::face(NonZeroU16::MIN), data, f32::from(face.weight));
231        let id = shaper.glyph_of(c).unwrap_or_else(|| panic!("no glyph for {c} in {}", face.url));
232        Some(shaper.rasterize_glyph(id))
233    }
234
235    #[test]
236    fn a_picked_font_has_the_character() {
237        for c in ['a', 'ä', 'Ж', 'α', 'א', 'ب', '中', 'あ', '한', 'ሀ'] {
238            for name in ["", "Open Sans Regular", "Noto Sans Bold"] {
239                let found = with_finder(|finder| picked_fonts(finder, &font_name::parse(name), c).into_iter().next());
240                let found = found.flatten();
241                println!("{c} for {name:?}: {found:?}");
242                if let Some((_, source)) = found {
243                    assert!(source.drawn_weight(c, 400).is_some(), "{c} for {name:?}");
244                }
245            }
246        }
247    }
248
249    #[test]
250    fn a_name_gets_its_family_if_the_system_has_it() {
251        with_finder(|finder| {
252            // The family the platform picks for 'a' is one the system has.
253            let Some((family, _)) = picked_fonts(finder, &font_name::parse(""), 'a').into_iter().next() else {
254                return;
255            };
256            let name = format!("{family} Bold");
257            let found = named_fonts(finder, &name, &font_name::parse(&name));
258            println!("{name}: {:?}", found.first());
259            assert_ne!(found.len(), 0);
260            assert!(found.iter().all(|(found, _)| found.eq_ignore_ascii_case(&family)));
261            let missing = "No Such Font Regular";
262            assert_eq!(named_fonts(finder, missing, &font_name::parse(missing)).len(), 0);
263        });
264    }
265
266    // A font the system picked, or a later name's, draws only what the
267    // stack's earlier fonts lack, whatever was drawn before.
268    #[test]
269    fn the_stacks_fonts_come_first_in_order() {
270        let ascii = Some("ab");
271        let broad = Some("abé");
272        let picked = ["abéz"];
273        let has = |c: char| move |font: &&str| font.contains(c);
274        assert_eq!(first_with(&[ascii, broad], &picked, has('a')), Some(&"ab"));
275        assert_eq!(first_with(&[ascii, broad], &picked, has('é')), Some(&"abé"));
276        assert_eq!(first_with(&[None, broad], &picked, has('a')), Some(&"abé"));
277        assert_eq!(first_with(&[ascii, broad], &picked, has('z')), Some(&"abéz"));
278        assert_eq!(first_with(&[ascii, broad], &picked, has('q')), None);
279    }
280
281    #[test]
282    fn a_chosen_face_draws_its_character() {
283        for c in ['a', '中', '한'] {
284            let glyph = chosen_glyph(&["Open Sans Regular"], c);
285            println!("{c}: {:?}", glyph.as_ref().map(|glyph| glyph.metrics));
286            if let Some(glyph) = glyph {
287                assert!(glyph.metrics.advance > 0);
288                assert!(glyph.bitmap.data.iter().any(|&alpha| alpha > 0));
289            }
290        }
291    }
292
293    // A variable font draws at each name's weight, a static family from its
294    // file of that weight.
295    #[test]
296    fn a_bold_name_draws_bolder_where_the_system_has_a_bolder_font() {
297        for c in ['a', 'Ж', 'α', 'א', 'ب'] {
298            let picked = with_finder(|finder| picked_fonts(finder, &font_name::parse(""), c).into_iter().next());
299            let Some((family, _)) = picked.flatten() else { continue };
300            let ink = |name: &str| {
301                let glyph = chosen_glyph(&[name], c)?;
302                Some(glyph.bitmap.data.iter().map(|&alpha| u64::from(alpha)).sum::<u64>())
303            };
304            let drawn = |name: &str| {
305                let found = with_finder(|finder| named_fonts(finder, name, &font_name::parse(name)).into_iter().next());
306                let (_, source) = found.flatten()?;
307                Some((source.drawn_weight(c, font_name::parse(name).weight)?, source))
308            };
309            let (regular, bold) = (format!("{family} Regular"), format!("{family} Bold"));
310            let (Some((regular_weight, _)), Some((bold_weight, source))) = (drawn(&regular), drawn(&bold)) else {
311                continue;
312            };
313            println!("{c}: {regular_weight} {:?}, {bold_weight} {:?} from {source:?}", ink(&regular), ink(&bold));
314            if bold_weight > regular_weight {
315                assert!(ink(&bold) > ink(&regular), "{c} in {family}");
316            }
317        }
318    }
319
320    #[test]
321    fn cjk_characters_share_a_class() {
322        assert_eq!(class('中'), class('あ'));
323        assert_eq!(class('中'), class('한'));
324        assert_eq!(class('a'), class('ä'));
325        assert_ne!(class('a'), class('Ж'));
326    }
327}