1use std::sync::Arc;
7
8use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle};
9
10#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct FontId(pub [u8; 32]);
13
14impl FontId {
15 pub fn of(bytes: &[u8]) -> FontId {
17 use sha2::Digest;
18 FontId(sha2::Sha256::digest(bytes).into())
19 }
20
21 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
42pub const MAX_FONT_BYTES: usize = 4 * 1024 * 1024;
48
49pub const INTER: &str = "Inter";
51pub const INTER_WEIGHTS: [u16; 4] = [400, 500, 600, 700];
53
54pub const WEIGHTS: [u16; 9] = [100, 200, 300, 400, 500, 600, 700, 800, 900];
56
57#[derive(Debug, Clone, Copy, PartialEq)]
59pub enum Weights {
60 Static(f32),
62 Axis(f32, f32),
64}
65
66impl Weights {
67 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
78pub struct FontFile {
81 pub id: FontId,
83 pub bytes: Arc<Vec<u8>>,
85 pub blob: Blob<u8>,
88 pub family: String,
90 pub weights: Weights,
92 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
107impl PartialEq for FontFile {
109 fn eq(&self, other: &FontFile) -> bool {
110 self.id == other.id
111 }
112}
113
114pub type FontFiles = std::collections::BTreeMap<FontId, Arc<FontFile>>;
116
117impl FontFile {
118 pub fn new(bytes: Vec<u8>) -> Result<FontFile, String> {
121 FontFile::with_id(FontId::of(&bytes), bytes)
122 }
123
124 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#[derive(Debug)]
192pub struct Family {
193 pub name: String,
195 pub faces: Vec<Arc<FontFile>>,
197}
198
199impl Family {
200 pub fn face(&self, weight: u16) -> Option<&Arc<FontFile>> {
202 self.faces.iter().find(|f| f.weights.has(weight))
203 }
204
205 pub fn weights(&self) -> Vec<u16> {
207 WEIGHTS
208 .into_iter()
209 .filter(|&w| self.face(w).is_some())
210 .collect()
211 }
212
213 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
260pub 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
266pub 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 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 #[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}