Skip to main content

devpage_design/
fonts.rs

1//! Fonts: a design's text is set in Inter, which the engine embeds, or in a
2//! **font file** from the served folder — a `.ttf` or `.otf` of one font,
3//! checked as it is read and known by its content, so a scene holds and
4//! sends it once however many texts use it.
5
6use std::sync::Arc;
7
8use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle};
9
10/// A font file's identity: the SHA-256 of its bytes.
11#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct FontId(pub [u8; 32]);
13
14impl FontId {
15    /// The identity of the font file of `bytes`.
16    pub fn of(bytes: &[u8]) -> FontId {
17        use sha2::Digest;
18        FontId(sha2::Sha256::digest(bytes).into())
19    }
20
21    /// The family name the file is registered under for layout: its own,
22    /// so a text gets exactly this file — never another font that calls its
23    /// family by the same name, Inter included.
24    pub fn family(&self) -> String {
25        let mut name = String::from("devpage-font-");
26        for b in self.0 {
27            name.push_str(&format!("{b:02x}"));
28        }
29        name
30    }
31}
32
33impl std::fmt::Debug for FontId {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        for b in &self.0[..6] {
36            write!(f, "{b:02x}")?;
37        }
38        Ok(())
39    }
40}
41
42/// The largest font file a design may use. Every font file a design uses
43/// goes whole to each browser that shows it, before the design draws: a
44/// whole Latin family, Greek and Cyrillic included, is well under 1 MB, and
45/// a larger file covers thousands of characters — Chinese or Japanese — and
46/// should be subset to the ones the design shows.
47pub const MAX_FONT_BYTES: usize = 4 * 1024 * 1024;
48
49/// The family name of the embedded font, and its weights.
50pub const INTER: &str = "Inter";
51/// The weights the engine embeds Inter in.
52pub const INTER_WEIGHTS: [u16; 4] = [400, 500, 600, 700];
53
54/// The weights a text may ask for: 100 to 900 in steps of 100.
55pub const WEIGHTS: [u16; 9] = [100, 200, 300, 400, 500, 600, 700, 800, 900];
56
57/// The weights one font file has.
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub enum Weights {
60    /// A static font: its one weight.
61    Static(f32),
62    /// A variable font: its weight axis, from and to.
63    Axis(f32, f32),
64}
65
66impl Weights {
67    /// Whether a text of `weight` can be set in the file: its one weight, or a
68    /// weight on its axis.
69    pub fn has(&self, weight: u16) -> bool {
70        let w = weight as f32;
71        match *self {
72            Weights::Static(own) => own == w,
73            Weights::Axis(from, to) => (from..=to).contains(&w),
74        }
75    }
76}
77
78/// A font file, checked: its bytes, its family's name as its own tables give
79/// it, its weights, and whether it is upright.
80pub struct FontFile {
81    /// Its identity: the SHA-256 of its bytes.
82    pub id: FontId,
83    /// Its bytes, as read: what the wire carries.
84    pub bytes: Arc<Vec<u8>>,
85    /// The bytes as parley and both backends take them: one blob for the
86    /// file's life, so every cache keyed by it keeps working.
87    pub blob: Blob<u8>,
88    /// Its family's name, as its own tables give it.
89    pub family: String,
90    /// The weights it has: a static font's one, or a variable font's axis.
91    pub weights: Weights,
92    /// Whether it is upright: neither italic nor oblique.
93    pub upright: bool,
94}
95
96impl std::fmt::Debug for FontFile {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("FontFile")
99            .field("id", &self.id)
100            .field("family", &self.family)
101            .field("weights", &self.weights)
102            .field("upright", &self.upright)
103            .finish()
104    }
105}
106
107/// Font files compare by their identity, which is their bytes.
108impl PartialEq for FontFile {
109    fn eq(&self, other: &FontFile) -> bool {
110        self.id == other.id
111    }
112}
113
114/// A scene's font files by id.
115pub type FontFiles = std::collections::BTreeMap<FontId, Arc<FontFile>>;
116
117impl FontFile {
118    /// Checks `bytes` as a font file, or says why it isn't one — a sentence
119    /// that follows the file's path.
120    pub fn new(bytes: Vec<u8>) -> Result<FontFile, String> {
121        FontFile::with_id(FontId::of(&bytes), bytes)
122    }
123
124    /// Checks `bytes`, already known to be the file `id`.
125    pub fn with_id(id: FontId, bytes: Vec<u8>) -> Result<FontFile, String> {
126        if bytes.len() > MAX_FONT_BYTES {
127            return Err(format!(
128                "is {:.1} MB; a font file is at most {} MB — subset it to the characters the design shows",
129                bytes.len() as f64 / (1024.0 * 1024.0),
130                MAX_FONT_BYTES / (1024 * 1024)
131            ));
132        }
133        match bytes.get(..4) {
134            Some(b"wOFF") => {
135                return Err(
136                    "is a WOFF file, which devpage doesn't read — decompress it to a .ttf or .otf"
137                        .into(),
138                );
139            }
140            Some(b"wOF2") => {
141                return Err(
142                    "is a WOFF2 file, which devpage doesn't read — decompress it to a .ttf or .otf"
143                        .into(),
144                );
145            }
146            Some(b"ttcf") => {
147                return Err(
148                    "is a collection of fonts; name one font's own .ttf or .otf file".into(),
149                );
150            }
151            Some([0, 1, 0, 0] | b"OTTO" | b"true") => {}
152            _ => return Err("is not a font: devpage reads .ttf and .otf files".into()),
153        }
154        let bytes = Arc::new(bytes);
155        let blob = Blob::new(bytes.clone());
156        let mut collection = Collection::new(CollectionOptions {
157            shared: false,
158            system_fonts: false,
159        });
160        let mut found = collection.register_fonts(blob.clone(), None);
161        let (family, info) = match (found.len(), found.first_mut()) {
162            (1, Some((family, infos))) if infos.len() == 1 => (*family, infos.remove(0)),
163            (0, _) => return Err("is a .ttf or .otf file that doesn't read as a font".into()),
164            _ => {
165                return Err(
166                    "holds more than one font; name one font's own .ttf or .otf file".into(),
167                );
168            }
169        };
170        let family = collection
171            .family_name(family)
172            .unwrap_or_default()
173            .to_string();
174        let weights = match info.axes().iter().find(|a| a.tag.to_be_bytes() == *b"wght") {
175            Some(axis) => Weights::Axis(axis.min, axis.max),
176            None => Weights::Static(info.weight().value()),
177        };
178        Ok(FontFile {
179            id,
180            bytes,
181            blob,
182            family,
183            weights,
184            upright: info.style() == FontStyle::Normal,
185        })
186    }
187}
188
189/// One family's font files, from a file or a folder: the faces a text's
190/// weight picks from.
191#[derive(Debug)]
192pub struct Family {
193    /// The family's name, as its files' own tables give it.
194    pub name: String,
195    /// Its upright faces, at most one of each weight.
196    pub faces: Vec<Arc<FontFile>>,
197}
198
199impl Family {
200    /// The face a text of `weight` is set in, when the family has it.
201    pub fn face(&self, weight: u16) -> Option<&Arc<FontFile>> {
202        self.faces.iter().find(|f| f.weights.has(weight))
203    }
204
205    /// Every weight a text may ask of the family.
206    pub fn weights(&self) -> Vec<u16> {
207        WEIGHTS
208            .into_iter()
209            .filter(|&w| self.face(w).is_some())
210            .collect()
211    }
212
213    /// A folder's font files, each with its name, as one family — or why
214    /// they aren't one. Italic and oblique faces are passed over.
215    pub fn of_folder(files: Vec<(String, Arc<FontFile>)>) -> Result<Family, String> {
216        if files.is_empty() {
217            return Err("holds no .ttf or .otf file".into());
218        }
219        let upright: Vec<_> = files.into_iter().filter(|(_, f)| f.upright).collect();
220        let Some((_, first)) = upright.first() else {
221            return Err("holds italic faces only; a text is set upright".into());
222        };
223        let name = first.family.clone();
224        if upright.iter().any(|(_, f)| f.family != name) {
225            let mut families: Vec<String> = Vec::new();
226            for (file, f) in &upright {
227                let entry = format!("{} ({file})", f.family);
228                if !families
229                    .iter()
230                    .any(|e| e.starts_with(&format!("{} (", f.family)))
231                {
232                    families.push(entry);
233                }
234            }
235            return Err(format!(
236                "holds more than one family: {}",
237                families.join(", ")
238            ));
239        }
240        for w in WEIGHTS {
241            let of: Vec<&str> = upright
242                .iter()
243                .filter(|(_, f)| f.weights.has(w))
244                .map(|(file, _)| file.as_str())
245                .collect();
246            if of.len() > 1 {
247                return Err(format!(
248                    "holds two files of weight {w}: {} and {}",
249                    of[0], of[1]
250                ));
251            }
252        }
253        Ok(Family {
254            name,
255            faces: upright.into_iter().map(|(_, f)| f).collect(),
256        })
257    }
258}
259
260/// Whether a file in a font folder is one of its fonts, by its name.
261pub fn is_font_name(name: &str) -> bool {
262    let lower = name.to_ascii_lowercase();
263    lower.ends_with(".ttf") || lower.ends_with(".otf")
264}
265
266/// `weights` as a sentence's list: `300, 400 and 700`.
267pub fn list(weights: &[u16]) -> String {
268    let words: Vec<String> = weights.iter().map(|w| w.to_string()).collect();
269    match words.split_last() {
270        Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
271        Some((last, _)) => last.clone(),
272        None => "none".into(),
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    fn inter() -> Vec<u8> {
281        std::fs::read(concat!(
282            env!("CARGO_MANIFEST_DIR"),
283            "/fonts/Inter-Regular.ttf"
284        ))
285        .unwrap()
286    }
287
288    /// A face as a folder might hold it: Inter's regular, said to be
289    /// `weight` and upright or not.
290    fn face(weight: f32, upright: bool) -> Arc<FontFile> {
291        let mut file = FontFile::new(inter()).unwrap();
292        file.weights = Weights::Static(weight);
293        file.upright = upright;
294        Arc::new(file)
295    }
296
297    #[test]
298    fn a_font_file_knows_its_family_and_weights() {
299        let file = FontFile::new(inter()).unwrap();
300        assert_eq!(file.family, "Inter");
301        assert_eq!(file.weights, Weights::Static(400.0));
302        assert!(file.upright);
303        let figtree = std::fs::read(concat!(
304            env!("CARGO_MANIFEST_DIR"),
305            "/../docs/designs/checkout/fonts/Figtree/Figtree-Variable.ttf"
306        ))
307        .unwrap();
308        let file = FontFile::new(figtree).unwrap();
309        assert_eq!(file.family, "Figtree");
310        assert_eq!(file.weights, Weights::Axis(300.0, 900.0));
311        let family = Family {
312            name: file.family.clone(),
313            faces: vec![Arc::new(file)],
314        };
315        assert_eq!(family.weights(), [300, 400, 500, 600, 700, 800, 900]);
316    }
317
318    /// A folder's italic faces are passed over; one with nothing else is a
319    /// problem.
320    #[test]
321    fn a_folder_is_its_upright_faces() {
322        let family = Family::of_folder(vec![
323            ("Regular.ttf".into(), face(400.0, true)),
324            ("Italic.ttf".into(), face(400.0, false)),
325            ("Bold.ttf".into(), face(700.0, true)),
326        ])
327        .unwrap();
328        assert_eq!(family.weights(), [400, 700]);
329        assert_eq!(
330            Family::of_folder(vec![("Italic.ttf".into(), face(400.0, false))]).unwrap_err(),
331            "holds italic faces only; a text is set upright"
332        );
333        assert_eq!(list(&[400]), "400");
334        assert_eq!(list(&[400, 700]), "400 and 700");
335    }
336}