Skip to main content

text/
fontdb.rs

1// fontdb -- system font database: enumerate the installed fonts, group them into families,
2// match styles, cache the result                                      [src/text/fontdb.s]
3//
4//   scan(flags) -> faces found      walk the font folders (recursively, depth <= 8) and read
5//        only the table directory, name, OS/2 and head of every .ttf / .otf / .ttc / .otc
6//        (faces with glyf, CFF, CFF2 or CBDT outlines; every face of a collection);
7//        files already in a loaded cache with the same size are not opened again (flags
8//        FDB_RESCAN: ignore the cache).  Folders: jfgui_FONTDIRS (';' separated, on Linux
9//        also ':'), else Windows %WINDIR%/Fonts and %LOCALAPPDATA%/Microsoft/Windows/Fonts;
10//        Linux /usr/share/fonts, /usr/local/share/fonts, $XDG_DATA_HOME/fonts (else
11//        ~/.local/share/fonts), ~/.fonts; macOS and iOS /System/Library/Fonts, /Library/Fonts,
12//        ~/Library/Fonts (directories are visited once: symlink loops)
13//   scan_dirs(dirs, flags) -> faces found   the same in these folders only (tests, apps with
14//        their own font folders)
15//   resolve(conf, family, lang, weight, italic) -> (face, FS_SYN_*, family)   the first installed
16//        of the FontConf's candidates (generic families, substitutes, the language's choices;
17//        fontconf.rs), else sans-serif's; load_resolved(text, conf, ...) -> (font id, family)
18//        (a variable face: its instance for weight / italic, load_var)
19//   clear()                         forget the scan result (the cache stays)
20//   family_count(), family_name(i), family_faces(i) -> &[FdFace], family_range(i)   families
21//        sorted case-insensitively
22//   face_count(), face(i)           every face, family order
23//   find(family, weight, italic) -> (face index, FS_SYN_* flags to add)   family = legacy
24//        family name (FN_FAMILY, like GDI), else a typographic family; closest weight,
25//        italic before upright; synthetic bold / italic asked when the family lacks them
26//   load(text, family, weight, italic) -> font id / ERR_*   find + load_file (+ style; a
27//        variable face: load_var); each (face, style) is loaded once until the next scan
28//   variations(face) -> Option<&FdVar>   a variable face's axes and named instances (fvar,
29//        names from its name table; read from the file on first use, kept until the next scan)
30//   var_values(face, weight, italic, size_pt, axes) -> (values, FS_SYN_* still needed)   the
31//        axis values of a choice: the axes named, else weight -> wght, italic -> ital = 1 or
32//        slnt = its most slanted value, the size in points -> opsz (clamped to each axis);
33//        synthetic bold / italic only where no axis gives them
34//   load_var(text, face, syn, weight, italic, size_pt, axes) -> font id / ERR_*   load_face +
35//        Text::vary at var_values (a face that is not variable: load_face)
36//   save_cache(path) / load_cache(path) -> 0 / -1
37//
38// Families group faces by the legacy family name (name ID 1); names prefer German, then
39// English.  Cache file (little endian): "FDB1", u32 version 4, u32 files, u32 faces, u32
40// pool bytes, u64 FNV-1a hash of everything after the 28-byte header; files {u32 path, u32
41// size, u32 first face, u32 faces}; faces {u32 file, u32 face index, u16 weight, u16 flags,
42// u32 family, u32 style, u32 full, u32 typo family, u32 0}; pool of NUL-terminated UTF-8
43// strings (offsets above point into it).  Entries are validated by path and file size.
44// Version 3: CFF2 faces count (a version 2 cache lists CFF2-only files without faces, so it
45// is not read).  Version 4: FDFF_NOLATIN.
46
47use alloc::string::String;
48use alloc::vec::Vec;
49
50use crate::font::{FN_FAMILY, FN_FULL, FN_STYLE, FN_TYPO_FAMILY, FS_SYN_BOLD, FS_SYN_ITALIC};
51use crate::fontconf::{is_generic, FontConf};
52use crate::ttf::{sfnt_name, Tb, ERR_FAIL, NAME_CAP};
53use crate::var::{Var, VarAxis, VarInstance};
54use crate::Text;
55
56pub const FDB_RESCAN: u32 = 1;
57pub const FDFF_ITALIC: u16 = 1;
58pub const FDFF_BOLD: u16 = 2;
59pub const FDFF_OBLIQUE: u16 = 4;
60pub const FDFF_CFF: u16 = 8;
61pub const FDFF_COLOR: u16 = 16;
62pub const FDFF_VAR: u16 = 32;
63pub const FDFF_SYMBOL: u16 = 64;
64/// CFF2 outlines (FDFF_CFF is set as well)
65pub const FDFF_CFF2: u16 = 128;
66/// the cmap lacks A or a: a font for another script (see FontDb::resolve)
67pub const FDFF_NOLATIN: u16 = 256;
68
69const DEPTH_MAX: u32 = 8;
70const PATH_CAP: usize = 4096;
71const HDR_READ: usize = 4096;
72const TTC_MAX: u32 = 64;
73const NT_MAX: u32 = 1024;
74const NAME_MAX: u32 = 1 << 20;
75const CMAP_MAX: u32 = 1 << 20;
76const FILES_MAX: usize = 20000;
77const LOADED_MAX: usize = 256;
78const CACHE_MAGIC: u32 = 0x3142_4446; // "FDB1"
79const CACHE_HDR: usize = 28;
80const CACHE_VERSION: u32 = 4;
81const VISIT_MAX: usize = 4096;
82const TAG_TTCF: u32 = 0x7474_6366;
83const TAG_TRUE: u32 = 0x7472_7565;
84const TAG_OTTO: u32 = 0x4F54_544F;
85const TAG_V1: u32 = 0x0001_0000;
86const T_NAME: u32 = 0x6E61_6D65;
87const T_OS2: u32 = 0x4F53_2F32;
88const T_HEAD: u32 = 0x6865_6164;
89const T_GLYF: u32 = 0x676C_7966;
90const T_CFF: u32 = 0x4346_4620;
91const T_CFF2: u32 = 0x4346_4632;
92const T_COLR: u32 = 0x434F_4C52;
93const T_CBDT: u32 = 0x4342_4454;
94const T_FVAR: u32 = 0x6676_6172;
95const T_CMAP: u32 = 0x636D_6170;
96const FVAR_MAX: u32 = 1 << 20;
97static NAME_WANT: [u32; 4] = [FN_FAMILY, FN_STYLE, FN_FULL, FN_TYPO_FAMILY];
98
99/// a face of the database (FDFACE)
100#[derive(Clone, Default)]
101pub struct FdFace {
102    pub path: String,
103    pub style: String,   // FN_STYLE
104    pub full: String,    // FN_FULL
105    pub family: String,  // FN_FAMILY, the grouping key
106    pub tfamily: String, // FN_TYPO_FAMILY
107    pub face: u32,       // face index inside the file (TTC / OTC)
108    pub weight: u16,     // usWeightClass
109    pub flags: u16,      // FDFF_*
110}
111
112/// the variations of an installed variable face (FontDb::variations)
113#[derive(Clone, Debug, Default, PartialEq)]
114pub struct FdVar {
115    /// fvar's axes (names from the face's name table)
116    pub axes: Vec<VarAxis>,
117    /// its named instances
118    pub instances: Vec<VarInstance>,
119}
120
121// file record {path, size, first face, faces}
122#[derive(Clone, Copy)]
123struct FileRec {
124    path: u32,
125    size: u32,
126    first: u32,
127    n: u32,
128}
129
130// internal face record (strings: pool offsets)
131#[derive(Clone, Copy, Default)]
132struct FaceRec {
133    file: u32,
134    face: u32,
135    weight: u16,
136    flags: u16,
137    fam: u32,
138    style: u32,
139    full: u32,
140    tfam: u32,
141}
142
143struct Family {
144    first: u32,
145    n: u32,
146}
147
148#[derive(Default)]
149struct Cache {
150    files: Vec<FileRec>,
151    faces: Vec<FaceRec>,
152    pool: Vec<u8>,
153    hash: Vec<u64>,
154    by_hash: Vec<(u64, u32)>, // (path hash, file index) sorted
155}
156
157#[derive(Default)]
158pub struct FontDb {
159    pool: Vec<u8>,
160    files: Vec<FileRec>,
161    fi: Vec<FaceRec>,
162    faces: Vec<FdFace>,
163    fam: Vec<Family>,
164    loaded: Vec<(usize, u32, i32)>, // (face, synthetic flags, font id)
165    vars: Vec<(usize, Option<FdVar>)>, // (face, its variations): read on first use
166    cache: Option<Cache>,
167    use_cache: bool,
168    visited: Vec<(u64, u64)>,
169}
170
171// fvar (and the name table for its names) of face `face` in a file
172fn read_var(path: &str, face: u32) -> Option<FdVar> {
173    let f = plat::File::open(path, plat::FO_READ)?;
174    let mut h = [0u8; 16];
175    if read_at(&f, 0, &mut h) < 12 {
176        return None;
177    }
178    let dir = if be32(&h, 0) == TAG_TTCF {
179        let mut o = [0u8; 4];
180        if read_at(&f, 12 + face as u64 * 4, &mut o) != 4 {
181            return None;
182        }
183        be32(&o, 0) as u64
184    } else {
185        0
186    };
187    let mut d = [0u8; 12];
188    if read_at(&f, dir, &mut d) != 12 {
189        return None;
190    }
191    let nt = be16(&d, 4).min(NT_MAX);
192    let mut recs = alloc::vec![0u8; (nt * 16) as usize];
193    if read_at(&f, dir + 12, &mut recs) != (nt * 16) as i64 {
194        return None;
195    }
196    let (mut fvar, mut name) = ((0u32, 0u32), (0u32, 0u32));
197    for i in 0..nt as usize {
198        let r = &recs[i * 16..];
199        match be32(r, 0) {
200            T_FVAR => fvar = (be32(r, 8), be32(r, 12)),
201            T_NAME => name = (be32(r, 8), be32(r, 12)),
202            _ => {}
203        }
204    }
205    let table = |(o, l): (u32, u32), max: u32| -> Vec<u8> {
206        let mut b = alloc::vec![0u8; l.min(max) as usize];
207        let n = read_at(&f, o as u64, &mut b);
208        b.truncate(n.max(0) as usize);
209        b
210    };
211    let fv = table(fvar, FVAR_MAX);
212    let nm = table(name, NAME_MAX);
213    let v = Var::parse(Tb(&fv), Tb(&[]), Tb(&[]), Tb(&[]), Tb(&[]), Tb(&[]), Tb(&nm))?;
214    Some(FdVar { axes: v.axes, instances: v.instances })
215}
216
217/// FNV-1a 64 (hash_fnv64, seed 0 = the offset basis)
218pub fn fnv64(d: &[u8]) -> u64 {
219    let mut h: u64 = 0xCBF2_9CE4_8422_2325;
220    for &b in d {
221        h ^= b as u64;
222        h = h.wrapping_mul(0x0000_0100_0000_01B3);
223    }
224    h
225}
226
227// ASCII case-insensitive compare, bytes otherwise  [ci_cmp]
228fn ci_cmp(a: &[u8], b: &[u8]) -> i32 {
229    let mut i = 0;
230    loop {
231        let mut x = a.get(i).copied().unwrap_or(0) as i32;
232        let mut y = b.get(i).copied().unwrap_or(0) as i32;
233        if (x - b'A' as i32) as u32 <= 25 {
234            x += 32;
235        }
236        if (y - b'A' as i32) as u32 <= 25 {
237            y += 32;
238        }
239        let d = x - y;
240        if d != 0 || y == 0 {
241            return d;
242        }
243        i += 1;
244    }
245}
246
247// a NUL-terminated pool string
248fn pstr(pool: &[u8], off: u32) -> &[u8] {
249    let s = &pool[off as usize..];
250    &s[..s.iter().position(|&c| c == 0).unwrap_or(s.len())]
251}
252
253fn pool_put(pool: &mut Vec<u8>, s: &[u8]) -> u32 {
254    let off = pool.len() as u32;
255    pool.extend_from_slice(s);
256    pool.push(0);
257    off
258}
259
260fn ends_ci(s: &str, ext: &str) -> bool {
261    s.len() >= ext.len() && s.as_bytes()[s.len() - ext.len()..].eq_ignore_ascii_case(ext.as_bytes())
262}
263
264fn be16(d: &[u8], o: usize) -> u32 {
265    u16::from_be_bytes([d[o], d[o + 1]]) as u32
266}
267
268fn be32(d: &[u8], o: usize) -> u32 {
269    u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]])
270}
271
272// does a cmap table map both A and a?  Its first Unicode subtable of format 4 or 12, else its
273// Mac Roman one of format 0 or 6; none of them (a symbol font) or one past CMAP_MAX: nothing
274// known, so yes
275fn cmap_latin(f: &plat::File, off: u32, len: u32) -> bool {
276    let mut b = alloc::vec![0u8; len.min(CMAP_MAX) as usize];
277    let got = read_at(f, off as u64, &mut b);
278    if got < 4 {
279        return true;
280    }
281    b.truncate(got as usize);
282    for mac in [false, true] {
283        for i in 0..be16(&b, 2) as usize {
284            let r = 4 + i * 8;
285            if r + 8 > b.len() {
286                break;
287            }
288            let (pid, eid, s) = (be16(&b, r), be16(&b, r + 2), be32(&b, r + 4) as usize);
289            let kind = if mac { pid == 1 && eid == 0 } else { pid == 0 || (pid == 3 && (eid == 1 || eid == 10)) };
290            if !kind || s.saturating_add(16) > b.len() {
291                continue;
292            }
293            let mapped = |cp: u32| match be16(&b, s) {
294                0 if mac => Some(b.get(s + 6 + cp as usize).is_some_and(|&g| g != 0)),
295                6 if mac => {
296                    let (first, n) = (be16(&b, s + 6), be16(&b, s + 8));
297                    let g = s + 10 + cp.wrapping_sub(first) as usize * 2;
298                    Some(cp >= first && cp - first < n && g + 2 <= b.len() && be16(&b, g) != 0)
299                }
300                4 if !mac => {
301                    let seg = be16(&b, s + 6) as usize / 2;
302                    (0..seg).map(|k| (s + 14 + k * 2, s + 16 + seg * 2 + k * 2)).take_while(|&(_, st)| st + 2 <= b.len())
303                        .find(|&(e, _)| be16(&b, e) >= cp).map(|(_, st)| be16(&b, st) <= cp)
304                }
305                12 if !mac => {
306                    let n = be32(&b, s + 12) as usize;
307                    Some((0..n).map(|k| s + 16 + k * 12).take_while(|&g| g + 8 <= b.len())
308                        .any(|g| be32(&b, g) <= cp && cp <= be32(&b, g + 4)))
309                }
310                _ => None,
311            };
312            if let (Some(upper), Some(lower)) = (mapped(0x41), mapped(0x61)) {
313                return upper && lower;
314            }
315        }
316    }
317    true
318}
319
320fn le32(d: &[u8], o: usize) -> u32 {
321    u32::from_le_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]])
322}
323
324fn read_at(f: &plat::File, off: u64, buf: &mut [u8]) -> i64 {
325    match f.read_at(off, buf) {
326        Some(n) => n as i64,
327        None => -1,
328    }
329}
330
331impl FontDb {
332    pub fn new() -> FontDb {
333        FontDb::default()
334    }
335
336    /// fontdb_clear(): forget the scan result (the cache stays)
337    pub fn clear(&mut self) {
338        self.pool = Vec::new();
339        self.files = Vec::new();
340        self.fi = Vec::new();
341        self.faces = Vec::new();
342        self.fam = Vec::new();
343        self.loaded.clear();
344        self.vars.clear();
345    }
346
347    pub fn family_count(&self) -> usize {
348        self.fam.len()
349    }
350
351    /// the family's name ("" when i is out of range)
352    pub fn family_name(&self, i: usize) -> &str {
353        match self.fam.get(i) {
354            Some(f) => &self.faces[f.first as usize].family,
355            None => "",
356        }
357    }
358
359    /// the indices (face(i), variations(i)) of family i's faces (empty when out of range)
360    pub fn family_range(&self, i: usize) -> core::ops::Range<usize> {
361        match self.fam.get(i) {
362            Some(f) => f.first as usize..(f.first + f.n) as usize,
363            None => 0..0,
364        }
365    }
366
367    /// the faces of family i (empty when out of range)
368    pub fn family_faces(&self, i: usize) -> &[FdFace] {
369        match self.fam.get(i) {
370            Some(f) => &self.faces[f.first as usize..(f.first + f.n) as usize],
371            None => &[],
372        }
373    }
374
375    pub fn face_count(&self) -> usize {
376        self.faces.len()
377    }
378
379    pub fn face(&self, i: usize) -> Option<&FdFace> {
380        self.faces.get(i)
381    }
382
383    // ------------------------------------------------------------------ scanning
384
385    /// fontdb_scan(flags) -> number of faces
386    pub fn scan(&mut self, flags: u32) -> usize {
387        let mut ws: Vec<(String, u32)> = Vec::new();
388        Self::roots(&mut ws);
389        self.scan_from(ws, flags)
390    }
391
392    /// scan these folders instead of the system's -> number of faces
393    pub fn scan_dirs(&mut self, dirs: &[&str], flags: u32) -> usize {
394        let ws = dirs.iter().filter(|d| !d.is_empty()).map(|d| (String::from(*d), 0)).collect();
395        self.scan_from(ws, flags)
396    }
397
398    fn scan_from(&mut self, mut ws: Vec<(String, u32)>, flags: u32) -> usize {
399        self.clear();
400        self.visited.clear();
401        self.use_cache = flags & FDB_RESCAN == 0 && self.cache.as_ref().is_some_and(|c| !c.files.is_empty());
402        while let Some((path, depth)) = ws.pop() {
403            if !self.visit_once(&path) {
404                continue;
405            }
406            // list the directory
407            let mut ents: Vec<(String, bool, u32)> = Vec::new();
408            if !plat::dir_list(&path, &mut |name, is_dir, size| ents.push((String::from(name), is_dir, size))) {
409                continue;
410            }
411            for (name, is_dir, size) in ents {
412                // path2 = path + '/' + name
413                let mut p2 = path.clone();
414                if p2.len() >= PATH_CAP - 2 {
415                    continue; // no room for '/' + name
416                }
417                if !p2.ends_with('/') && !p2.ends_with('\\') {
418                    p2.push('/');
419                }
420                p2.push_str(&name);
421                if p2.len() >= PATH_CAP - 2 {
422                    continue; // too long: skip
423                }
424                if is_dir {
425                    if depth < DEPTH_MAX {
426                        ws.push((p2, depth + 1));
427                    }
428                    continue;
429                }
430                if ![".ttf", ".otf", ".ttc", ".otc"].iter().any(|e| ends_ci(&p2, e)) {
431                    continue;
432                }
433                if self.files.len() >= FILES_MAX {
434                    continue;
435                }
436                self.add_file(&p2, size);
437            }
438        }
439        self.finalize();
440        self.faces.len()
441    }
442
443    // first visit of a directory (Linux: device + inode; Windows: always)  [fd_visit_once]
444    fn visit_once(&mut self, path: &str) -> bool {
445        let Some(id) = plat::dev_ino(path) else { return true };
446        if self.visited.contains(&id) {
447            return false;
448        }
449        if self.visited.len() < VISIT_MAX {
450            self.visited.push(id);
451        }
452        true
453    }
454
455    // push the font folders onto the work stack (plat::policy::font_dirs: the same folders
456    // the app's permissions always let it read), the first one on top  [fd_roots]
457    fn roots(ws: &mut Vec<(String, u32)>) {
458        for d in plat::policy::font_dirs().into_iter().rev() {
459            ws.push((d, 0));
460        }
461    }
462
463    // add a file record and its faces (from the cache or parsed)  [fd_add_file]
464    fn add_file(&mut self, path: &str, size: u32) {
465        let poff = pool_put(&mut self.pool, path.as_bytes());
466        let first = self.fi.len() as u32;
467        self.files.push(FileRec { path: poff, size, first, n: 0 });
468        let file = self.files.len() as u32 - 1;
469        if !(self.use_cache && self.from_cache(path, size, file)) {
470            self.parse(path, file);
471        }
472        // faces of this file = records added since first
473        let n = self.fi.len() as u32 - first;
474        self.files[file as usize].n = n;
475    }
476
477    // copy the cached faces of (path, size)  [fd_from_cache]
478    fn from_cache(&mut self, path: &str, size: u32, file: u32) -> bool {
479        let Some(c) = &self.cache else { return false };
480        let h = fnv64(path.as_bytes());
481        let start = c.by_hash.partition_point(|e| e.0 < h);
482        for &(eh, i) in &c.by_hash[start..] {
483            if eh != h {
484                break;
485            }
486            let (i, f) = (i as usize, &c.files[i as usize]);
487            if c.hash[i] != h || f.size != size || pstr(&c.pool, f.path) != path.as_bytes() {
488                continue;
489            }
490            for k in f.first..f.first + f.n {
491                let mut r = c.faces[k as usize];
492                r.file = file;
493                // strings into the new pool
494                r.fam = pool_put(&mut self.pool, pstr(&c.pool, r.fam));
495                r.style = pool_put(&mut self.pool, pstr(&c.pool, r.style));
496                r.full = pool_put(&mut self.pool, pstr(&c.pool, r.full));
497                r.tfam = pool_put(&mut self.pool, pstr(&c.pool, r.tfam));
498                self.fi.push(r);
499            }
500            return true;
501        }
502        false
503    }
504
505    // open the file and add every face  [fd_parse]
506    fn parse(&mut self, path: &str, file: u32) {
507        let Some(f) = plat::File::open(path, plat::FO_READ) else { return };
508        let mut hdr = alloc::vec![0u8; HDR_READ];
509        let n = read_at(&f, 0, &mut hdr);
510        if n < 12 {
511            return;
512        }
513        match be32(&hdr, 0) {
514            TAG_TTCF => {
515                let nf = be32(&hdr, 8).min(TTC_MAX);
516                // offsets must lie in what was read
517                if (nf * 4 + 12) as i64 > n {
518                    return;
519                }
520                for i in 0..nf {
521                    let dir = be32(&hdr, (12 + i * 4) as usize);
522                    self.face_rec(&f, dir, i, file);
523                }
524            }
525            TAG_V1 | TAG_TRUE | TAG_OTTO => self.face_rec(&f, 0, 0, file),
526            _ => {}
527        }
528    }
529
530    // parse one face's tables and add it  [fd_face]
531    fn face_rec(&mut self, f: &plat::File, dir: u32, face: u32, file: u32) {
532        let (mut name, mut os2, mut head, mut cmap) = ((0u32, 0u32), (0u32, 0u32), (0u32, 0u32), (0u32, 0u32));
533        let mut flags = 0u16;
534        let mut outl = false;
535        // table directory
536        let mut d = [0u8; 12];
537        if read_at(f, dir as u64, &mut d) != 12 {
538            return;
539        }
540        let nt = be16(&d, 4).min(NT_MAX);
541        let mut recs = alloc::vec![0u8; (nt * 16) as usize];
542        if read_at(f, dir as u64 + 12, &mut recs) != (nt * 16) as i64 {
543            return;
544        }
545        for i in 0..nt as usize {
546            let r = &recs[i * 16..];
547            let (tag, off, len) = (be32(r, 0), be32(r, 8), be32(r, 12));
548            match tag {
549                T_NAME => name = (off, len),
550                T_OS2 => os2 = (off, len),
551                T_HEAD => head = (off, len),
552                T_CMAP => cmap = (off, len),
553                T_GLYF => outl = true,
554                T_CFF => {
555                    flags |= FDFF_CFF;
556                    outl = true;
557                }
558                T_CFF2 => {
559                    flags |= FDFF_CFF | FDFF_CFF2;
560                    outl = true;
561                }
562                T_COLR => flags |= FDFF_COLOR,
563                T_CBDT => {
564                    outl = true;
565                    flags |= FDFF_COLOR;
566                }
567                T_FVAR => flags |= FDFF_VAR,
568                _ => {}
569            }
570        }
571        if !outl || name.1 < 6 {
572            return; // no usable outlines (e.g. sbix / SVG only)
573        }
574        // head
575        let mut mac_style = 0u32;
576        if head.1 >= 54 {
577            let mut h = [0u8; 54];
578            if read_at(f, head.0 as u64, &mut h) == 54 {
579                mac_style = be16(&h, 44);
580            }
581        }
582        // OS/2 (first 96 bytes)
583        let mut o = [0u8; 96];
584        let mut os2n = os2.1.min(96) as i64;
585        if os2n != 0 {
586            os2n = read_at(f, os2.0 as u64, &mut o[..os2n as usize]);
587            if os2n < 0 {
588                return;
589            }
590        }
591        // name table
592        let nl = name.1.min(NAME_MAX) as usize;
593        let mut nb = alloc::vec![0u8; nl];
594        let got = read_at(f, name.0 as u64, &mut nb);
595        if got <= 0 {
596            return;
597        }
598        let tb = Tb(&nb[..got as usize]);
599        let mut names: [Vec<u8>; 4] = Default::default();
600        for (i, &id) in NAME_WANT.iter().enumerate() {
601            names[i] = sfnt_name(tb, id, NAME_CAP);
602        }
603        if names[0].is_empty() {
604            return; // no family name
605        }
606        if names[3].is_empty() {
607            names[3] = names[0].clone();
608        }
609        // weight / style flags
610        let mut weight = 400u32;
611        if os2n >= 64 {
612            weight = be16(&o, 4);
613            if weight < 10 {
614                weight *= 100;
615            }
616            if weight == 0 {
617                weight = 400;
618            }
619            if weight > 1000 {
620                weight = 1000;
621            }
622            let s = be16(&o, 62);
623            if s & 1 != 0 {
624                flags |= FDFF_ITALIC;
625            }
626            if s & 0x20 != 0 {
627                flags |= FDFF_BOLD;
628            }
629            if s & 0x200 != 0 {
630                flags |= FDFF_OBLIQUE;
631            }
632            if os2n >= 82 && be32(&o, 78) & 0x8000_0000 != 0 {
633                flags |= FDFF_SYMBOL; // ulCodePageRange1 bit 31
634            }
635        } else {
636            if mac_style & 1 != 0 {
637                flags |= FDFF_BOLD;
638                weight = 700;
639            }
640            if mac_style & 2 != 0 {
641                flags |= FDFF_ITALIC;
642            }
643        }
644        if cmap.1 != 0 && !cmap_latin(f, cmap.0, cmap.1) {
645            flags |= FDFF_NOLATIN;
646        }
647        let mut r = FaceRec { file, face, weight: weight as u16, flags, ..Default::default() };
648        r.fam = pool_put(&mut self.pool, &names[0]);
649        r.style = pool_put(&mut self.pool, &names[1]);
650        r.full = pool_put(&mut self.pool, &names[2]);
651        r.tfam = pool_put(&mut self.pool, &names[3]);
652        self.fi.push(r);
653    }
654
655    // ------------------------------------------------------------------ families
656
657    // order of internal faces: family, weight, italic, style, file, face  [fd_cmp]
658    fn cmp(&self, i: usize, j: usize) -> i32 {
659        let (a, b) = (&self.fi[i], &self.fi[j]);
660        let p = &self.pool;
661        let c = ci_cmp(pstr(p, a.fam), pstr(p, b.fam));
662        if c != 0 {
663            return c;
664        }
665        let c = a.weight as i32 - b.weight as i32;
666        if c != 0 {
667            return c;
668        }
669        let m = FDFF_ITALIC | FDFF_OBLIQUE;
670        let c = (a.flags & m) as i32 - (b.flags & m) as i32;
671        if c != 0 {
672            return c;
673        }
674        let c = ci_cmp(pstr(p, a.style), pstr(p, b.style));
675        if c != 0 {
676            return c;
677        }
678        let c = a.file.wrapping_sub(b.file) as i32;
679        if c != 0 {
680            return c;
681        }
682        a.face.wrapping_sub(b.face) as i32
683    }
684
685    // duplicates: same family, full name, weight and style flags  [fd_same]
686    fn same(&self, i: usize, j: usize) -> bool {
687        let (a, b) = (&self.fi[i], &self.fi[j]);
688        let p = &self.pool;
689        a.weight == b.weight
690            && a.flags == b.flags
691            && ci_cmp(pstr(p, a.fam), pstr(p, b.fam)) == 0
692            && ci_cmp(pstr(p, a.full), pstr(p, b.full)) == 0
693    }
694
695    // sort (shell sort gaps 701 .. 1), drop duplicates, build the faces and families
696    // [fd_finalize]
697    fn finalize(&mut self) {
698        let n = self.fi.len();
699        if n == 0 {
700            return;
701        }
702        let mut idx: Vec<usize> = (0..n).collect();
703        for gap in [701usize, 301, 132, 57, 23, 10, 4, 1] {
704            for i in gap..n {
705                let t = idx[i];
706                let mut j = i;
707                while j >= gap && self.cmp(idx[j - gap], t) > 0 {
708                    idx[j] = idx[j - gap];
709                    j -= gap;
710                }
711                idx[j] = t;
712            }
713        }
714        let mut prev: Option<usize> = None;
715        let p = |o: u32| String::from_utf8_lossy(pstr(&self.pool, o)).into_owned();
716        let mut faces: Vec<FdFace> = Vec::new();
717        let mut fam: Vec<Family> = Vec::new();
718        for &k in &idx {
719            if let Some(pk) = prev
720                && self.same(pk, k)
721            {
722                continue;
723            }
724            prev = Some(k);
725            let r = self.fi[k];
726            let fdf = FdFace {
727                path: p(self.files[r.file as usize].path),
728                style: p(r.style),
729                full: p(r.full),
730                family: p(r.fam),
731                tfamily: p(r.tfam),
732                face: r.face,
733                weight: r.weight,
734                flags: r.flags,
735            };
736            // family: new when the name differs (case-insensitively) from the previous face
737            match fam.last_mut() {
738                Some(f) if ci_cmp(faces[f.first as usize].family.as_bytes(), fdf.family.as_bytes()) == 0 => f.n += 1,
739                _ => fam.push(Family { first: faces.len() as u32, n: 1 }),
740            }
741            faces.push(fdf);
742        }
743        self.faces = faces;
744        self.fam = fam;
745    }
746
747    // ------------------------------------------------------------------ matching / loading
748
749    /// fontdb_find(family, weight, italic) -> (face index, FS_SYN_* flags to add)
750    pub fn find(&self, family: &str, weight: u32, italic: bool) -> Option<(usize, u32)> {
751        let w = if weight == 0 { 400 } else { weight.min(1000) as i32 };
752        for pass in 0..2 {
753            let mut best = i32::MAX;
754            let mut bi = None;
755            for (i, f) in self.faces.iter().enumerate() {
756                let name = if pass == 0 { &f.family } else { &f.tfamily };
757                if ci_cmp(name.as_bytes(), family.as_bytes()) != 0 {
758                    continue;
759                }
760                // score: italic mismatch 10000, weight distance x 2, direction tie-break
761                let fi = f.flags & (FDFF_ITALIC | FDFF_OBLIQUE) != 0;
762                let mut s = if fi != italic { 10000 } else { 0 };
763                let fw = f.weight as i32;
764                s += (fw - w).abs() * 2;
765                // prefer heavier for w >= 500, lighter otherwise
766                if (w >= 500 && fw < w) || (w < 500 && fw > w) {
767                    s += 1;
768                }
769                if s < best {
770                    best = s;
771                    bi = Some(i);
772                }
773            }
774            if let Some(i) = bi {
775                let f = &self.faces[i];
776                let mut syn = 0;
777                if italic && f.flags & (FDFF_ITALIC | FDFF_OBLIQUE) == 0 {
778                    syn |= FS_SYN_ITALIC;
779                }
780                if w >= 600 && f.weight < 600 {
781                    syn |= FS_SYN_BOLD;
782                }
783                return Some((i, syn));
784            }
785        }
786        None
787    }
788
789    /// the first installed candidate of conf for family in lang (generic families,
790    /// substitutes, the language's choices), else sans-serif's -> (face index, FS_SYN_* flags,
791    /// the family name found).  A substitute without Latin letters (FDFF_NOLATIN) only counts
792    /// when nothing else fits, except for emoji and math: fontconfig ranks the language above
793    /// such a rule's family, and Fedora's rules put Noto Sans Arabic first in sans-serif and
794    /// monospace.  Another script's characters come from fallback.rs
795    pub fn resolve(&self, conf: &FontConf, family: &str, lang: &str, weight: u32, italic: bool) -> Option<(usize, u32, String)> {
796        let mut tried = conf.candidates(family, lang);
797        if !is_generic(family) {
798            tried.extend(conf.candidates("sans-serif", lang));
799        }
800        let any_script = ["emoji", "math"].iter().any(|g| family.trim().eq_ignore_ascii_case(g));
801        let mut spare = None;
802        for f in tried.iter().filter(|f| !is_generic(f)) {
803            if let Some((i, syn)) = self.find(f, weight, italic) {
804                if any_script || self.faces[i].flags & FDFF_NOLATIN == 0 || f.trim().eq_ignore_ascii_case(family.trim()) {
805                    return Some((i, syn, self.faces[i].family.clone()));
806                }
807                spare = spare.or(Some((i, syn)));
808            }
809        }
810        spare.map(|(i, syn)| (i, syn, self.faces[i].family.clone()))
811    }
812
813    /// resolve and load -> (font id / ERR_*, the family found)
814    pub fn load_resolved(&mut self, text: &mut Text, conf: &FontConf, family: &str, lang: &str, weight: u32, italic: bool) -> (i32, String) {
815        match self.resolve(conf, family, lang, weight, italic) {
816            Some((fi, syn, fam)) => (self.load_var(text, fi, syn, weight, italic, None, &[]), fam),
817            None => (ERR_FAIL, String::new()),
818        }
819    }
820
821    /// fontdb_load(text, family, weight, italic) -> font id / ERR_*
822    pub fn load(&mut self, text: &mut Text, family: &str, weight: u32, italic: bool) -> i32 {
823        let Some((fi, syn)) = self.find(family, weight, italic) else { return ERR_FAIL };
824        self.load_var(text, fi, syn, weight, italic, None, &[])
825    }
826
827    /// load face fi with the synthetic styles syn (FS_SYN_*) -> font id / ERR_*; each (face,
828    /// style) once until the next scan
829    pub fn load_face(&mut self, text: &mut Text, fi: usize, syn: u32) -> i32 {
830        if fi >= self.faces.len() {
831            return ERR_FAIL;
832        }
833        // loaded before?
834        for &(f, s, id) in &self.loaded {
835            if f == fi && s == syn && text.valid(id as u32) {
836                return id;
837            }
838        }
839        let face = &self.faces[fi];
840        let mut id = text.load_file(&face.path, face.face);
841        if id < 0 {
842            return id;
843        }
844        if syn != 0 {
845            id = text.style(id as u32, syn);
846            if id < 0 {
847                return id;
848            }
849        }
850        if self.loaded.len() < LOADED_MAX {
851            self.loaded.push((fi, syn, id));
852        }
853        id
854    }
855
856    // ------------------------------------------------------------------ variable faces
857
858    /// the axes and named instances of face i (None: not a variable face, or its file cannot
859    /// be read); read from the file on first use
860    pub fn variations(&mut self, i: usize) -> Option<&FdVar> {
861        let f = self.faces.get(i)?;
862        if f.flags & FDFF_VAR == 0 {
863            return None;
864        }
865        let k = match self.vars.iter().position(|v| v.0 == i) {
866            Some(k) => k,
867            None => {
868                let v = read_var(&f.path, f.face);
869                self.vars.push((i, v));
870                self.vars.len() - 1
871            }
872        };
873        self.vars[k].1.as_ref()
874    }
875
876    /// the axis values of a choice on variable face i (see the module header) -> (one value
877    /// per axis, the FS_SYN_* flags still needed); None: not a variable face
878    pub fn var_values(&mut self, i: usize, weight: u32, italic: bool, size_pt: Option<f32>, axes: &[([u8; 4], f32)]) -> Option<(Vec<f32>, u32)> {
879        let face_weight = self.faces.get(i)?.weight as u32;
880        let face_italic = self.faces.get(i)?.flags & (FDFF_ITALIC | FDFF_OBLIQUE) != 0;
881        let v = self.variations(i)?;
882        let w = if weight == 0 { 400 } else { weight.min(1000) };
883        let mut vals: Vec<f32> = v.axes.iter().map(|a| a.def).collect();
884        let mut syn = 0;
885        let find = |t: &[u8; 4]| v.axes.iter().position(|a| &a.tag == t);
886        // weight: the wght axis, else a synthetic bold like find()
887        match find(b"wght") {
888            Some(k) => {
889                let a = &v.axes[k];
890                vals[k] = (w as f32).clamp(a.min, a.max);
891                if w >= 600 && a.max < 600.0 {
892                    syn |= FS_SYN_BOLD;
893                }
894            }
895            None if w >= 600 && face_weight < 600 => syn |= FS_SYN_BOLD,
896            None => {}
897        }
898        // italic: ital = 1, else the most slanted slnt, else a synthetic italic
899        if italic && !face_italic {
900            match (find(b"ital"), find(b"slnt")) {
901                (Some(k), _) if v.axes[k].max >= 1.0 => vals[k] = 1.0,
902                (_, Some(k)) if v.axes[k].min < 0.0 => vals[k] = v.axes[k].min,
903                _ => syn |= FS_SYN_ITALIC,
904            }
905        }
906        // the optical size follows the size
907        if let (Some(k), Some(pt)) = (find(b"opsz"), size_pt) {
908            vals[k] = pt.clamp(v.axes[k].min, v.axes[k].max);
909        }
910        // the axes named win
911        for &(t, x) in axes {
912            if let Some(k) = find(&t) {
913                vals[k] = if x.is_nan() { v.axes[k].def } else { x.clamp(v.axes[k].min, v.axes[k].max) };
914                if &t == b"wght" {
915                    syn &= !FS_SYN_BOLD;
916                }
917                if &t == b"ital" || &t == b"slnt" {
918                    syn &= !FS_SYN_ITALIC;
919                }
920            }
921        }
922        Some((vals, syn))
923    }
924
925    /// load variable face fi at the axis values of a choice (var_values) with the synthetic
926    /// styles syn asks for that no axis gives -> font id / ERR_*; a face that is not
927    /// variable: load_face(fi, syn)
928    #[allow(clippy::too_many_arguments)]
929    pub fn load_var(&mut self, text: &mut Text, fi: usize, syn: u32, weight: u32, italic: bool, size_pt: Option<f32>, axes: &[([u8; 4], f32)]) -> i32 {
930        let Some((vals, vsyn)) = self.var_values(fi, weight, italic, size_pt, axes) else { return self.load_face(text, fi, syn) };
931        // the synthetic styles the variable face still needs (find asked for them without
932        // knowing the axes)
933        let syn = (syn & !(FS_SYN_BOLD | FS_SYN_ITALIC)) | vsyn;
934        let id = self.load_face(text, fi, 0);
935        if id < 0 {
936            return id;
937        }
938        let tags: Vec<([u8; 4], f32)> = match self.variations(fi) {
939            Some(v) => v.axes.iter().zip(&vals).map(|(a, &x)| (a.tag, x)).collect(),
940            None => Vec::new(),
941        };
942        let id = text.vary(id as u32, &tags);
943        if id < 0 || syn == 0 { id } else { text.style(id as u32, syn) }
944    }
945
946    // ------------------------------------------------------------------ cache
947
948    /// fontdb_save_cache(path) -> 0 / -1
949    pub fn save_cache(&self, path: &str) -> i32 {
950        let mut b = Vec::with_capacity(CACHE_HDR + self.files.len() * 16 + self.fi.len() * 32 + self.pool.len());
951        b.extend_from_slice(&CACHE_MAGIC.to_le_bytes());
952        b.extend_from_slice(&CACHE_VERSION.to_le_bytes());
953        b.extend_from_slice(&(self.files.len() as u32).to_le_bytes());
954        b.extend_from_slice(&(self.fi.len() as u32).to_le_bytes());
955        b.extend_from_slice(&(self.pool.len() as u32).to_le_bytes());
956        b.extend_from_slice(&[0u8; 8]);
957        for f in &self.files {
958            for v in [f.path, f.size, f.first, f.n] {
959                b.extend_from_slice(&v.to_le_bytes());
960            }
961        }
962        for r in &self.fi {
963            b.extend_from_slice(&r.file.to_le_bytes());
964            b.extend_from_slice(&r.face.to_le_bytes());
965            b.extend_from_slice(&r.weight.to_le_bytes());
966            b.extend_from_slice(&r.flags.to_le_bytes());
967            for v in [r.fam, r.style, r.full, r.tfam, 0] {
968                b.extend_from_slice(&v.to_le_bytes());
969            }
970        }
971        b.extend_from_slice(&self.pool);
972        let h = fnv64(&b[CACHE_HDR..]);
973        b[20..28].copy_from_slice(&h.to_le_bytes());
974        if plat::write_file(path, &b) { 0 } else { -1 }
975    }
976
977    /// fontdb_load_cache(path) -> 0 / -1 (a malformed file is rejected as a whole)
978    pub fn load_cache(&mut self, path: &str) -> i32 {
979        self.cache = None;
980        let Some(d) = plat::read_file(path) else { return -1 };
981        if d.len() < CACHE_HDR || le32(&d, 0) != CACHE_MAGIC || le32(&d, 4) != CACHE_VERSION {
982            return -1;
983        }
984        if fnv64(&d[CACHE_HDR..]) != u64::from_le_bytes(d[20..28].try_into().unwrap()) {
985            return -1;
986        }
987        let nf = le32(&d, 8) as usize;
988        let nfa = le32(&d, 12) as usize;
989        let np = le32(&d, 16) as usize;
990        if nf > FILES_MAX || nfa > FILES_MAX * 8 || np == 0 {
991            return -1;
992        }
993        if nf * 16 + nfa * 32 + np + CACHE_HDR > d.len() {
994            return -1;
995        }
996        let fo = CACHE_HDR;
997        let ao = fo + nf * 16;
998        let po = ao + nfa * 32;
999        let pool = &d[po..po + np];
1000        if pool[np - 1] != 0 {
1001            return -1;
1002        }
1003        // validate every offset
1004        let mut c = Cache::default();
1005        for i in 0..nf {
1006            let o = fo + i * 16;
1007            let f = FileRec { path: le32(&d, o), size: le32(&d, o + 4), first: le32(&d, o + 8), n: le32(&d, o + 12) };
1008            let (end, carry) = f.first.overflowing_add(f.n);
1009            if f.path as usize >= np || carry || end as usize > nfa {
1010                return -1;
1011            }
1012            c.files.push(f);
1013        }
1014        for i in 0..nfa {
1015            let o = ao + i * 32;
1016            let r = FaceRec {
1017                file: le32(&d, o),
1018                face: le32(&d, o + 4),
1019                weight: u16::from_le_bytes([d[o + 8], d[o + 9]]),
1020                flags: u16::from_le_bytes([d[o + 10], d[o + 11]]),
1021                fam: le32(&d, o + 12),
1022                style: le32(&d, o + 16),
1023                full: le32(&d, o + 20),
1024                tfam: le32(&d, o + 24),
1025            };
1026            if r.file as usize >= nf
1027                || r.fam as usize >= np
1028                || r.style as usize >= np
1029                || r.full as usize >= np
1030                || r.tfam as usize >= np
1031            {
1032                return -1;
1033            }
1034            c.faces.push(r);
1035        }
1036        c.pool = pool.to_vec();
1037        // path hashes
1038        c.hash = c.files.iter().map(|f| fnv64(pstr(&c.pool, f.path))).collect();
1039        c.by_hash = c.hash.iter().enumerate().map(|(i, &h)| (h, i as u32)).collect();
1040        c.by_hash.sort_unstable();
1041        self.cache = Some(c);
1042        0
1043    }
1044}