Skip to main content

quillmark_typst/
library.rs

1//! The host's font library: the faces a `font_family` mark may set, apart from
2//! a quill's own fonts and the embedded fallback, parsed once per engine and
3//! shared by its sessions.
4
5use std::sync::Arc;
6
7use quillmark_core::error::{Diagnostic, RenderError, Severity};
8use typst::foundations::Bytes;
9use typst::text::Font;
10
11use crate::world::{MAX_COLLECTION_FACES, faces};
12
13/// The faces a host supplies, every one readable. Frozen at construction: a
14/// session sees the library as it was when the engine was built.
15#[derive(Debug, Default)]
16pub struct FontLibrary {
17    faces: Vec<Font>,
18    /// Each face's file, the one buffer its `Font` reads.
19    files: Vec<Arc<[u8]>>,
20    /// Drawn at construction, so the family a library face is filed under is
21    /// no name a plate can spell ahead of time.
22    alias_key: u64,
23}
24
25impl FontLibrary {
26    /// Every face in `files`, each a `.ttf`, `.otf`, `.ttc` or `.otc` file's
27    /// bytes, or one diagnostic per file refused: `engine::font_unsupported`
28    /// for another format, `engine::font_unreadable` for a file of the right
29    /// format holding no face Typst reads. A collection keeps the faces Typst
30    /// reads and drops the rest. Each file is held once, shared by its faces
31    /// and by every [`FontFace`](quillmark_core::backend::FontFace) listing
32    /// them.
33    pub fn new<F: Into<Arc<[u8]>>>(
34        files: impl IntoIterator<Item = F>,
35    ) -> Result<Self, RenderError> {
36        let mut library = FontLibrary {
37            alias_key: alias_key(),
38            ..FontLibrary::default()
39        };
40        let mut refused = Vec::new();
41        for (i, file) in files.into_iter().enumerate() {
42            let file: Arc<[u8]> = file.into();
43            if let Some(format) = foreign_format(&file) {
44                refused.push(
45                    Diagnostic::new(
46                        Severity::Error,
47                        format!("host font {i} is {format}, which the font library does not read"),
48                    )
49                    .with_code("engine::font_unsupported".to_string())
50                    .with_hint("Supply the font as a .ttf, .otf, .ttc or .otc file.".to_string()),
51                );
52                continue;
53            }
54            match faces(Bytes::new(file.clone())) {
55                Ok(read) => {
56                    let before = library.faces.len();
57                    library.faces.extend(read);
58                    if library.faces.len() == before {
59                        refused.push(unreadable(i, "holds no face Typst reads".to_string()));
60                    }
61                    library.files.resize(library.faces.len(), file);
62                }
63                Err(declared) => refused.push(unreadable(
64                    i,
65                    format!("declares {declared} faces, past the {MAX_COLLECTION_FACES} one file may hold"),
66                )),
67            }
68        }
69        if refused.is_empty() {
70            Ok(library)
71        } else {
72            Err(RenderError::new(refused))
73        }
74    }
75
76    pub(crate) fn faces(&self) -> &[Font] {
77        &self.faces
78    }
79
80    /// Each face beside its file.
81    pub(crate) fn faces_with_files(&self) -> impl Iterator<Item = (&Font, &Arc<[u8]>)> {
82        self.faces.iter().zip(&self.files)
83    }
84
85    /// The family the font book files a library face of `family` under. No
86    /// plate or fallback names it, so only a `font_family` mark, which lowers
87    /// to it, reaches a library face.
88    pub(crate) fn alias(&self, family: &str) -> String {
89        format!("qm-host-{:016x}:{}", self.alias_key, family.to_lowercase())
90    }
91}
92
93/// A key no plate can know: the OS's randomness, or failing that the
94/// process's per-instance hash seed.
95fn alias_key() -> u64 {
96    getrandom::u64().unwrap_or_else(|_| {
97        use std::hash::BuildHasher;
98        std::hash::RandomState::new().hash_one(0u8)
99    })
100}
101
102fn unreadable(i: usize, why: String) -> Diagnostic {
103    Diagnostic::new(Severity::Error, format!("host font {i} {why}"))
104        .with_code("engine::font_unreadable".to_string())
105        .with_hint("Supply a TrueType or OpenType font file or collection.".to_string())
106}
107
108/// What `file` is when its signature is not a TrueType, OpenType or
109/// collection one.
110fn foreign_format(file: &[u8]) -> Option<&'static str> {
111    match file.first_chunk::<4>() {
112        Some([0, 1, 0, 0] | b"true" | b"OTTO" | b"ttcf") => None,
113        Some(b"wOFF") => Some("a WOFF file"),
114        Some(b"wOF2") => Some("a WOFF2 file"),
115        _ => Some("not a font file"),
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use std::sync::Arc;
122
123    use super::*;
124    use quillmark_core::backend::Backend;
125    use quillmark_core::quill::{FileTreeNode, Quill};
126
127    fn taro_font(name: &str) -> Vec<u8> {
128        std::fs::read(
129            quillmark_fixtures::quills_path("taro")
130                .join("assets/fonts")
131                .join(name),
132        )
133        .expect("read font")
134    }
135
136    fn quill_shipping(fonts: &[(&str, Vec<u8>)]) -> Quill {
137        let yaml = "quill:\n  name: t\n  version: 0.1.0\n  backend: typst\n  description: d\ntypst:\n  plate_file: plate.typ\n";
138        let mut root = FileTreeNode::Directory {
139            files: Default::default(),
140        };
141        root.insert(
142            "Quill.yaml",
143            FileTreeNode::File {
144                contents: yaml.as_bytes().to_vec(),
145            },
146        )
147        .unwrap();
148        root.insert(
149            "plate.typ",
150            FileTreeNode::File {
151                contents: b"x".to_vec(),
152            },
153        )
154        .unwrap();
155        for (name, data) in fonts {
156            root.insert(
157                format!("assets/fonts/{name}"),
158                FileTreeNode::File {
159                    contents: data.clone(),
160                },
161            )
162            .unwrap();
163        }
164        Quill::from_tree(root).expect("quill")
165    }
166
167    /// The faces a session lists, as `(family, weight)`.
168    fn faces_of(quill: &Quill, library: FontLibrary) -> Vec<(String, u16)> {
169        crate::TypstBackend::new(Arc::new(library))
170            .font_faces(quill)
171            .into_iter()
172            .map(|f| (f.family, f.weight))
173            .collect()
174    }
175
176    /// A session lists the library's faces alone: the quill's own and the
177    /// fallback set its plate, never a mark.
178    #[test]
179    fn a_session_lists_only_the_librarys_faces() {
180        let host = || FontLibrary::new(vec![taro_font("Figtree-Bold.ttf")]).expect("library");
181        let shipping = quill_shipping(&[("Figtree-Regular.ttf", taro_font("Figtree-Regular.ttf"))]);
182        assert_eq!(faces_of(&shipping, host()), [("Figtree".into(), 700)]);
183        assert_eq!(
184            faces_of(&quill_shipping(&[]), host()),
185            [("Figtree".into(), 700)]
186        );
187        assert_eq!(faces_of(&shipping, FontLibrary::default()), []);
188    }
189
190    /// Every listing hands out the library's own buffer, never a copy.
191    #[test]
192    fn a_listed_face_shares_the_librarys_file() {
193        let backend = crate::TypstBackend::new(Arc::new(
194            FontLibrary::new(vec![taro_font("Figtree-Regular.ttf")]).expect("library"),
195        ));
196        let quill = quill_shipping(&[]);
197        let (first, second) = (backend.font_faces(&quill), backend.font_faces(&quill));
198        assert!(Arc::ptr_eq(&first[0].data, &second[0].data));
199        assert_eq!(&first[0].data[..], &taro_font("Figtree-Regular.ttf")[..]);
200    }
201
202    #[test]
203    fn a_host_font_in_another_format_is_refused_by_its_signature() {
204        let roboto = crate::world::FALLBACK_FONTS[0].1.to_vec();
205        assert_eq!(
206            FontLibrary::new(vec![roboto.clone()])
207                .unwrap()
208                .faces()
209                .len(),
210            1
211        );
212        let err = FontLibrary::new(vec![
213            roboto,
214            b"wOF2rest".to_vec(),
215            b"wOFFrest".to_vec(),
216            b"<svg".to_vec(),
217            b"OTTOtruncated".to_vec(),
218        ])
219        .unwrap_err();
220        let codes: Vec<&str> = err
221            .diagnostics()
222            .iter()
223            .map(|d| d.code.as_deref().unwrap())
224            .collect();
225        assert_eq!(
226            codes,
227            [
228                "engine::font_unsupported",
229                "engine::font_unsupported",
230                "engine::font_unsupported",
231                "engine::font_unreadable"
232            ],
233            "one refusal per file past the readable first, in file order"
234        );
235    }
236}