Skip to main content

noonoo_engine/
fonts.rs

1//! `@font-face`: faces fetched through the host's loader and handed to the
2//! host to register.
3//!
4//! The engine keeps no parsed font store (a `FontSet` borrows its fonts, so
5//! the host owns it). It keeps each face's *bytes* (validated by parsing
6//! them once) or, for `local()`, the host's own name, under the declared
7//! family, weight and style: [`Engine::loaded_fonts`]. A host builds its
8//! `FontSet` from that list whenever [`Engine::poll_resources`] says
9//! something changed. Until a face arrives, text uses whatever the host's
10//! set offers for the family (font-display `swap`).
11
12use std::collections::HashMap;
13use std::sync::Arc;
14
15use noonoo_css::FontSource;
16use noonoo_net::RequestId;
17
18use crate::Engine;
19
20/// The most faces one engine tracks.
21const MAX_FACES: usize = 64;
22/// The largest font file it keeps, in bytes.
23const MAX_FONT_BYTES: usize = 16 * 1024 * 1024;
24
25/// What a loaded face is made of.
26#[derive(Clone, PartialEq, Eq, Debug)]
27pub enum FontData {
28    /// The font file (TrueType or OpenType, parsed once to check it).
29    Bytes(Arc<[u8]>),
30    /// A face the host already has, by the `local()` name that matched.
31    Local(String),
32}
33
34/// A `@font-face` the host should register.
35#[derive(Clone, PartialEq, Eq, Debug)]
36pub struct LoadedFont {
37    /// The declared `font-family`.
38    pub family: String,
39    /// The declared `font-weight` (a range registers at its first value).
40    pub weight: u16,
41    /// Whether the face is italic or oblique.
42    pub italic: bool,
43    /// The font.
44    pub data: FontData,
45}
46
47struct Face {
48    family: String,
49    weight: u16,
50    italic: bool,
51    sources: Vec<FontSource>,
52    next: usize,
53}
54
55type LocalFonts = Box<dyn Fn(&str) -> bool + Send + Sync>;
56
57#[derive(Default)]
58pub(crate) struct Fonts {
59    faces: Vec<Face>,
60    loaded: Vec<LoadedFont>,
61    pending: HashMap<RequestId, usize>,
62    local: Option<LocalFonts>,
63}
64
65impl Fonts {
66    pub(crate) fn owns(&self, id: RequestId) -> bool {
67        self.pending.contains_key(&id)
68    }
69}
70
71/// Whether a `format()` hint names something `noonoo-ttf` reads.
72fn supported(format: Option<&str>) -> bool {
73    matches!(
74        format,
75        None | Some("truetype" | "opentype" | "ttf" | "otf" | "collection")
76    )
77}
78
79impl Engine {
80    /// The faces loaded from `@font-face` rules so far, for the host to
81    /// register (each under its family, weight and style).
82    pub fn loaded_fonts(&self) -> &[LoadedFont] {
83        &self.resources.fonts.loaded
84    }
85
86    /// How the engine asks the host whether a `local()` name is a face it
87    /// has (for instance, `FontSet::select(name, ..).is_some()`). Without
88    /// one, `local()` sources are skipped.
89    pub fn set_local_fonts(&mut self, has: impl Fn(&str) -> bool + Send + Sync + 'static) {
90        self.resources.fonts.local = Some(Box::new(has));
91    }
92
93    /// Start loading the `@font-face` rules not seen before; returns the
94    /// number of requests started.
95    pub(crate) fn load_fonts(&mut self) -> usize {
96        if self.resources.loader.is_none() {
97            return 0;
98        }
99        let mut started = 0;
100        for face in self.font_faces() {
101            if self.resources.fonts.faces.len() >= MAX_FACES {
102                break;
103            }
104            let known = self.resources.fonts.faces.iter().any(|f| {
105                f.family == face.family
106                    && f.weight == face.weight
107                    && f.italic == face.italic
108                    && f.sources == face.sources
109            });
110            if known {
111                continue;
112            }
113            self.resources.fonts.faces.push(Face {
114                family: face.family,
115                weight: face.weight,
116                italic: face.italic,
117                sources: face.sources,
118                next: 0,
119            });
120            let index = self.resources.fonts.faces.len() - 1;
121            if self.advance_face(index) {
122                started += 1;
123            }
124        }
125        started
126    }
127
128    /// Move face `index` to its next usable source: a `local()` the host
129    /// has completes it; a supported `url()` is requested (true). False
130    /// when nothing is left to fetch.
131    fn advance_face(&mut self, index: usize) -> bool {
132        loop {
133            let fonts = &mut self.resources.fonts;
134            let face = &mut fonts.faces[index];
135            let Some(source) = face.sources.get(face.next).cloned() else {
136                return false;
137            };
138            face.next += 1;
139            match source {
140                FontSource::Local(name) => {
141                    if fonts.local.as_ref().is_some_and(|has| has(&name)) {
142                        let face = &fonts.faces[index];
143                        fonts.loaded.push(LoadedFont {
144                            family: face.family.clone(),
145                            weight: face.weight,
146                            italic: face.italic,
147                            data: FontData::Local(name),
148                        });
149                        return false;
150                    }
151                }
152                FontSource::Url { url, format } => {
153                    if !supported(format.as_deref()) {
154                        continue;
155                    }
156                    let url = match &self.resources.base_url {
157                        Some(base) => noonoo_net::resolve(base, &url),
158                        None => url,
159                    };
160                    let Some(loader) = &self.resources.loader else {
161                        return false;
162                    };
163                    let (request, completion) = self.resources.completions.request(url);
164                    self.resources.fonts.pending.insert(request.id, index);
165                    loader.start(request, completion);
166                    return true;
167                }
168            }
169        }
170    }
171
172    /// Take in a finished font load. True when a face was added.
173    pub(crate) fn font_arrived(
174        &mut self,
175        id: RequestId,
176        result: Result<Vec<u8>, noonoo_net::LoadError>,
177    ) -> bool {
178        let Some(index) = self.resources.fonts.pending.remove(&id) else {
179            return false;
180        };
181        let usable = result
182            .ok()
183            .filter(|bytes| bytes.len() <= MAX_FONT_BYTES)
184            .filter(|bytes| noonoo_ttf::Font::parse(bytes).is_ok());
185        match usable {
186            Some(bytes) => {
187                let face = &self.resources.fonts.faces[index];
188                let font = LoadedFont {
189                    family: face.family.clone(),
190                    weight: face.weight,
191                    italic: face.italic,
192                    data: FontData::Bytes(bytes.into()),
193                };
194                self.resources.fonts.loaded.push(font);
195                true
196            }
197            None => {
198                // Try the next source; a `local()` that matches counts.
199                let before = self.resources.fonts.loaded.len();
200                self.advance_face(index);
201                self.resources.fonts.loaded.len() > before
202            }
203        }
204    }
205}