quillmark_typst/
library.rs1use 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#[derive(Debug, Default)]
16pub struct FontLibrary {
17 faces: Vec<Font>,
18 files: Vec<Arc<[u8]>>,
20 alias_key: u64,
23}
24
25impl FontLibrary {
26 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 pub(crate) fn faces_with_files(&self) -> impl Iterator<Item = (&Font, &Arc<[u8]>)> {
82 self.faces.iter().zip(&self.files)
83 }
84
85 pub(crate) fn alias(&self, family: &str) -> String {
89 format!("qm-host-{:016x}:{}", self.alias_key, family.to_lowercase())
90 }
91}
92
93fn 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
108fn 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 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 #[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 #[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}