Skip to main content

day_fonts/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Bundled custom fonts (DESIGN §18.4).
5//!
6//! A project ships font files under a top-level `fonts/` directory. `day build` stages them into
7//! each platform's native font location (Android `res/font/`, the iOS `DayPieces` bundle +
8//! `UIAppFonts`, ArkUI rawfile, loose `Resources/fonts` on the desktops) and each backend
9//! registers them at startup so `Font::Custom("Family", pt)` resolves by the font's **family
10//! name**, the name baked into the file's `name` table (what Font Book / fontconfig report), not
11//! its file name.
12//!
13//! This module is the one implementation shared by the CLI (staging-time family extraction,
14//! identifier naming) and the runtimes (startup registration, family → file resolution):
15//!
16//! * [`parse_font_names`]: a minimal sfnt `name`-table reader for `.ttf`/`.otf`/`.ttc`.
17//! * [`font_dir`] / [`bundled_fonts`]: locate the staged font files at runtime (`DAY_FONT_ROOT`
18//!   under `day launch`, bundle-relative `Resources/fonts` when packed).
19//! * [`resolve_font_file`]: map a requested family name to one of the bundled files, for
20//!   backends whose native API wants a file path rather than a registered family (XAML).
21//! * [`font_ident`]: the identifier both the Android/ArkUI stagers and their runtimes derive
22//!   from a family name (`"Special Elite"` → `special_elite`), so lookup needs no side table.
23
24use std::path::PathBuf;
25
26/// Font file extensions accepted under `fonts/`.
27pub const FONT_EXTS: [&str; 3] = ["ttf", "otf", "ttc"];
28
29/// The names a font file reports for itself.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct FontNames {
32    /// The (typographic) family name: name ID 16, falling back to 1. This is what
33    /// `Font::Custom` matches on.
34    pub family: String,
35    /// The PostScript name (name ID 6), when present; some platform APIs resolve by it.
36    pub postscript: Option<String>,
37}
38
39fn u16be(data: &[u8], off: usize) -> Option<u16> {
40    Some(u16::from_be_bytes(data.get(off..off + 2)?.try_into().ok()?))
41}
42
43fn u32be(data: &[u8], off: usize) -> Option<u32> {
44    Some(u32::from_be_bytes(data.get(off..off + 4)?.try_into().ok()?))
45}
46
47/// Read the family and PostScript names from a raw font file (`.ttf`, `.otf`, or the first face
48/// of a `.ttc`). A tiny sfnt reader: only the table directory and the `name` table are touched,
49/// so it is safe to run on untrusted bytes (every access is bounds-checked).
50#[must_use]
51pub fn parse_font_names(data: &[u8]) -> Option<FontNames> {
52    // Font collections ('ttcf') front an array of face offsets; take the first face.
53    let base = if u32be(data, 0)? == u32::from_be_bytes(*b"ttcf") {
54        u32be(data, 12)? as usize
55    } else {
56        0
57    };
58    let version = u32be(data, base)?;
59    let known = [
60        0x0001_0000,                  // TrueType
61        u32::from_be_bytes(*b"OTTO"), // CFF OpenType
62        u32::from_be_bytes(*b"true"), // legacy Apple TrueType
63    ];
64    if !known.contains(&version) {
65        return None;
66    }
67    let num_tables = u16be(data, base + 4)? as usize;
68    let mut name_table = None;
69    for i in 0..num_tables {
70        let rec = base + 12 + i * 16;
71        if u32be(data, rec)? == u32::from_be_bytes(*b"name") {
72            let off = u32be(data, rec + 8)? as usize;
73            let len = u32be(data, rec + 12)? as usize;
74            name_table = Some(data.get(off..off.checked_add(len)?)?);
75            break;
76        }
77    }
78    let name = name_table?;
79    let count = u16be(name, 2)? as usize;
80    let storage = u16be(name, 4)? as usize;
81
82    // Highest-scoring candidate per name ID. Windows/Unicode records (UTF-16BE) are preferred
83    // over Mac Roman; the typographic family (ID 16) over the legacy family (ID 1).
84    let mut family16: Option<(u8, String)> = None;
85    let mut family1: Option<(u8, String)> = None;
86    let mut postscript: Option<(u8, String)> = None;
87    for i in 0..count {
88        let rec = 6 + i * 12;
89        let platform = u16be(name, rec)?;
90        let encoding = u16be(name, rec + 2)?;
91        let language = u16be(name, rec + 4)?;
92        let name_id = u16be(name, rec + 6)?;
93        let len = u16be(name, rec + 8)? as usize;
94        let off = u16be(name, rec + 10)? as usize;
95        if !matches!(name_id, 1 | 6 | 16) {
96            continue;
97        }
98        let Some(bytes) = name.get(storage + off..storage + off + len) else {
99            continue;
100        };
101        let (decoded, score) = match platform {
102            // Windows (3) and Unicode (0): UTF-16BE. American English first among Windows.
103            3 | 0 => {
104                // `as_chunks::<2>` rather than `chunks_exact(2)`: it yields `&[u8; 2]`, which
105                // `from_be_bytes` takes directly, with no rebuilding the pair by index and no
106                // bounds check on a length the type already carries. `.1` is the odd trailing byte
107                // of a malformed record, which a UTF-16 decode has nothing to do with, so it is
108                // dropped exactly as `chunks_exact` dropped it.
109                let units: Vec<u16> = bytes
110                    .as_chunks::<2>()
111                    .0
112                    .iter()
113                    .map(|c| u16::from_be_bytes(*c))
114                    .collect();
115                let s = String::from_utf16_lossy(&units);
116                let score = if platform == 3 && language == 0x0409 {
117                    3
118                } else if platform == 3 {
119                    2
120                } else {
121                    1
122                };
123                (s, score)
124            }
125            // Macintosh Roman: treat as Latin-1 (nearly always ASCII).
126            1 if encoding == 0 => (bytes.iter().map(|&b| b as char).collect(), 0),
127            _ => continue,
128        };
129        let decoded = decoded.trim().to_string();
130        if decoded.is_empty() {
131            continue;
132        }
133        let slot = match name_id {
134            16 => &mut family16,
135            1 => &mut family1,
136            _ => &mut postscript,
137        };
138        if slot.as_ref().is_none_or(|(s, _)| score > *s) {
139            *slot = Some((score, decoded));
140        }
141    }
142    let family = family16.or(family1)?.1;
143    Some(FontNames {
144        family,
145        postscript: postscript.map(|(_, s)| s),
146    })
147}
148
149/// The identifier the Android / ArkUI stagers derive from a family name, and that their runtimes
150/// re-derive to look the font up (Android `R.font.<ident>`): lowercase, `[a-z0-9_]` only, with a
151/// leading letter enforced. `"Special Elite"` → `special_elite`.
152#[must_use]
153pub fn font_ident(family: &str) -> String {
154    let mut s: String = family
155        .chars()
156        .map(|c| {
157            let c = c.to_ascii_lowercase();
158            if c.is_ascii_alphanumeric() || c == '_' {
159                c
160            } else {
161                '_'
162            }
163        })
164        .collect();
165    if !s.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) {
166        s.insert(0, 'r');
167    }
168    s
169}
170
171/// The directory holding the app's bundled font files at runtime: `DAY_FONT_ROOT` (the project's
172/// `fonts/` under `day launch`), then bundle-relative locations next to the executable (macOS
173/// `.app` `Resources/fonts`, files staged next to a desktop binary).
174#[must_use]
175pub fn font_dir() -> Option<PathBuf> {
176    if let Ok(root) = std::env::var("DAY_FONT_ROOT") {
177        let p = PathBuf::from(root);
178        if p.is_dir() {
179            return Some(p);
180        }
181    }
182    if let Ok(exe) = std::env::current_exe()
183        && let Some(dir) = exe.parent()
184    {
185        for rel in ["../Resources/fonts", "Resources/fonts", "fonts"] {
186            let p = dir.join(rel);
187            if p.is_dir() {
188                return Some(p);
189            }
190        }
191    }
192    None
193}
194
195/// Every bundled font file ([`font_dir`] filtered to [`FONT_EXTS`]), sorted by file name. The
196/// list backends iterate to register the app's fonts at startup.
197#[must_use]
198pub fn bundled_fonts() -> Vec<PathBuf> {
199    let Some(dir) = font_dir() else {
200        return Vec::new();
201    };
202    font_files_in(&dir)
203}
204
205/// The font files directly under `dir`, sorted by file name (shared with the CLI's scanner).
206#[must_use]
207pub fn font_files_in(dir: &std::path::Path) -> Vec<PathBuf> {
208    let mut out = Vec::new();
209    let Ok(entries) = std::fs::read_dir(dir) else {
210        return out;
211    };
212    for e in entries.flatten() {
213        let p = e.path();
214        let ext = p
215            .extension()
216            .and_then(|x| x.to_str())
217            .map(str::to_ascii_lowercase);
218        if p.is_file() && ext.is_some_and(|x| FONT_EXTS.contains(&x.as_str())) {
219            out.push(p);
220        }
221    }
222    out.sort();
223    out
224}
225
226/// Resolve a requested family name to the bundled font file that provides it (case-insensitive,
227/// PostScript name accepted too). For backends whose native font API takes a file path rather
228/// than a registered family name.
229#[must_use]
230pub fn resolve_font_file(family: &str) -> Option<PathBuf> {
231    for path in bundled_fonts() {
232        let Ok(bytes) = std::fs::read(&path) else {
233            continue;
234        };
235        if let Some(names) = parse_font_names(&bytes)
236            && (names.family.eq_ignore_ascii_case(family)
237                || names
238                    .postscript
239                    .as_deref()
240                    .is_some_and(|ps| ps.eq_ignore_ascii_case(family)))
241        {
242            return Some(path);
243        }
244    }
245    None
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    /// Build a minimal single-table sfnt whose `name` table carries the given records
253    /// (platform, encoding, language, `name_id`, utf16: bool, value).
254    fn sfnt_with_names(records: &[(u16, u16, u16, u16, bool, &str)]) -> Vec<u8> {
255        let mut strings: Vec<u8> = Vec::new();
256        let mut recs: Vec<u8> = Vec::new();
257        for &(plat, enc, lang, id, utf16, value) in records {
258            let start = strings.len() as u16;
259            if utf16 {
260                for u in value.encode_utf16() {
261                    strings.extend_from_slice(&u.to_be_bytes());
262                }
263            } else {
264                strings.extend(value.bytes());
265            }
266            let len = strings.len() as u16 - start;
267            for v in [plat, enc, lang, id, len, start] {
268                recs.extend_from_slice(&v.to_be_bytes());
269            }
270        }
271        let mut name = Vec::new();
272        name.extend_from_slice(&0u16.to_be_bytes()); // format
273        name.extend_from_slice(&(records.len() as u16).to_be_bytes());
274        name.extend_from_slice(&((6 + recs.len()) as u16).to_be_bytes()); // storage offset
275        name.extend(recs);
276        name.extend(strings);
277
278        let mut font = Vec::new();
279        font.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // sfnt version
280        font.extend_from_slice(&1u16.to_be_bytes()); // numTables
281        font.extend_from_slice(&[0; 6]); // searchRange etc (unused)
282        let name_off = 12 + 16; // directory follows header, table follows directory
283        font.extend_from_slice(b"name");
284        font.extend_from_slice(&0u32.to_be_bytes()); // checksum
285        font.extend_from_slice(&(name_off as u32).to_be_bytes());
286        font.extend_from_slice(&(name.len() as u32).to_be_bytes());
287        font.extend(name);
288        font
289    }
290
291    #[test]
292    fn parses_family_and_postscript() {
293        let font = sfnt_with_names(&[
294            (1, 0, 0, 1, false, "Mac Family"),
295            (3, 1, 0x0409, 1, true, "Win Family"),
296            (3, 1, 0x0409, 6, true, "WinFamily-Regular"),
297        ]);
298        let names = parse_font_names(&font).unwrap();
299        assert_eq!(names.family, "Win Family"); // Windows en-US beats Mac Roman
300        assert_eq!(names.postscript.as_deref(), Some("WinFamily-Regular"));
301    }
302
303    #[test]
304    fn typographic_family_wins() {
305        let font = sfnt_with_names(&[
306            (3, 1, 0x0409, 1, true, "Legacy Light"),
307            (3, 1, 0x0409, 16, true, "Legacy"),
308        ]);
309        assert_eq!(parse_font_names(&font).unwrap().family, "Legacy");
310    }
311
312    #[test]
313    fn rejects_non_fonts() {
314        assert!(parse_font_names(b"not a font at all").is_none());
315        assert!(parse_font_names(&[]).is_none());
316    }
317
318    #[test]
319    fn ident_rules() {
320        assert_eq!(font_ident("Special Elite"), "special_elite");
321        assert_eq!(font_ident("Pacifico"), "pacifico");
322        assert_eq!(font_ident("3of9"), "r3of9");
323    }
324}