Skip to main content

strata_layout/typography/
opentype.rs

1//! Pure Rust OpenType / TrueType font parser, metrics extractor, and font database.
2//!
3//! Parses sfnt container tables: `head`, `hhea`, `maxp`, `OS/2`, `hmtx`, `cmap` (Formats 4 & 12),
4//! and `kern` (Format 0) directly from binary font data without external dependencies.
5//! Provides authentic font face metrics, glyph advance widths, and optical pair kerning.
6
7use std::collections::HashMap;
8use std::sync::{Arc, OnceLock, RwLock};
9
10use strata_primitives::geom::LayoutUnit;
11use strata_primitives::AtomId;
12use strata_style::types::{FontStyle, FontWeight};
13
14use super::font_metrics::FontMetrics;
15
16/// Errors that can occur when parsing OpenType / TrueType font files.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum OpenTypeParseError {
19    UnexpectedEof,
20    InvalidSignature(u32),
21    TableNotFound(&'static str),
22    InvalidTableData(&'static str),
23}
24
25impl std::fmt::Display for OpenTypeParseError {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match self {
28            Self::UnexpectedEof => write!(f, "Unexpected EOF while parsing font binary"),
29            Self::InvalidSignature(sig) => write!(f, "Invalid sfnt signature: 0x{:08X}", sig),
30            Self::TableNotFound(tag) => write!(f, "Required font table not found: {}", tag),
31            Self::InvalidTableData(msg) => write!(f, "Invalid table data: {}", msg),
32        }
33    }
34}
35
36impl std::error::Error for OpenTypeParseError {}
37
38#[inline(always)]
39fn read_u16_be(data: &[u8], offset: usize) -> Option<u16> {
40    if offset + 2 <= data.len() {
41        Some(u16::from_be_bytes([data[offset], data[offset + 1]]))
42    } else {
43        None
44    }
45}
46
47#[inline(always)]
48fn read_i16_be(data: &[u8], offset: usize) -> Option<i16> {
49    if offset + 2 <= data.len() {
50        Some(i16::from_be_bytes([data[offset], data[offset + 1]]))
51    } else {
52        None
53    }
54}
55
56#[inline(always)]
57fn read_u32_be(data: &[u8], offset: usize) -> Option<u32> {
58    if offset + 4 <= data.len() {
59        Some(u32::from_be_bytes([
60            data[offset],
61            data[offset + 1],
62            data[offset + 2],
63            data[offset + 3],
64        ]))
65    } else {
66        None
67    }
68}
69
70/// Parsed OpenType / TrueType font face.
71#[derive(Clone)]
72pub struct OpenTypeFont {
73    data: Arc<[u8]>,
74    pub units_per_em: u16,
75    pub ascender: i16,
76    pub descender: i16,
77    pub line_gap: i16,
78    pub typo_ascender: i16,
79    pub typo_descender: i16,
80    pub typo_line_gap: i16,
81    pub x_height: Option<i16>,
82    pub cap_height: Option<i16>,
83    pub weight_class: u16,
84    pub is_italic: bool,
85    pub is_monospace: bool,
86    pub num_glyphs: u16,
87    pub number_of_h_metrics: u16,
88    hmtx_offset: usize,
89    cmap_subtable_offset: usize,
90    cmap_format: u16,
91    kern_subtable_offset: Option<usize>,
92    pub gsub_offset: Option<usize>,
93    pub supported_features: Vec<[u8; 4]>,
94}
95
96impl std::fmt::Debug for OpenTypeFont {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("OpenTypeFont")
99            .field("units_per_em", &self.units_per_em)
100            .field("ascender", &self.ascender)
101            .field("descender", &self.descender)
102            .field("line_gap", &self.line_gap)
103            .field("weight_class", &self.weight_class)
104            .field("is_italic", &self.is_italic)
105            .field("is_monospace", &self.is_monospace)
106            .field("num_glyphs", &self.num_glyphs)
107            .finish()
108    }
109}
110
111impl OpenTypeFont {
112    /// Parses an OpenType or TrueType font from memory.
113    pub fn parse(bytes: &[u8]) -> Result<Self, OpenTypeParseError> {
114        if bytes.len() < 12 {
115            return Err(OpenTypeParseError::UnexpectedEof);
116        }
117
118        let sfnt_version = read_u32_be(bytes, 0).ok_or(OpenTypeParseError::UnexpectedEof)?;
119        // TrueType 1.0 (0x00010000), OpenType CFF (0x4F54544F 'OTTO'), Apple TrueType (0x74727565 'true'), typ1 (0x74797031)
120        if sfnt_version != 0x00010000
121            && sfnt_version != 0x4F54544F
122            && sfnt_version != 0x74727565
123            && sfnt_version != 0x74797031
124        {
125            return Err(OpenTypeParseError::InvalidSignature(sfnt_version));
126        }
127
128        let num_tables = read_u16_be(bytes, 4).ok_or(OpenTypeParseError::UnexpectedEof)? as usize;
129        if bytes.len() < 12 + num_tables * 16 {
130            return Err(OpenTypeParseError::UnexpectedEof);
131        }
132
133        let mut head_offset = None;
134        let mut hhea_offset = None;
135        let mut maxp_offset = None;
136        let mut os2_offset = None;
137        let mut hmtx_offset = None;
138        let mut cmap_offset = None;
139        let mut kern_offset = None;
140        let mut gsub_offset = None;
141
142        for i in 0..num_tables {
143            let entry_offset = 12 + i * 16;
144            let tag = &bytes[entry_offset..entry_offset + 4];
145            let offset = read_u32_be(bytes, entry_offset + 8).unwrap() as usize;
146
147            match tag {
148                b"head" => head_offset = Some(offset),
149                b"hhea" => hhea_offset = Some(offset),
150                b"maxp" => maxp_offset = Some(offset),
151                b"OS/2" => os2_offset = Some(offset),
152                b"hmtx" => hmtx_offset = Some(offset),
153                b"cmap" => cmap_offset = Some(offset),
154                b"kern" => kern_offset = Some(offset),
155                b"GSUB" => gsub_offset = Some(offset),
156                _ => {}
157            }
158        }
159
160        let head_off = head_offset.ok_or(OpenTypeParseError::TableNotFound("head"))?;
161        let hhea_off = hhea_offset.ok_or(OpenTypeParseError::TableNotFound("hhea"))?;
162        let hmtx_off = hmtx_offset.ok_or(OpenTypeParseError::TableNotFound("hmtx"))?;
163        let cmap_off = cmap_offset.ok_or(OpenTypeParseError::TableNotFound("cmap"))?;
164
165        // 1. Read 'head'
166        let units_per_em = read_u16_be(bytes, head_off + 18).unwrap_or(1000).max(16);
167        let mac_style = read_u16_be(bytes, head_off + 44).unwrap_or(0);
168        let head_bold = (mac_style & 1) != 0;
169        let head_italic = (mac_style & 2) != 0;
170
171        // 2. Read 'hhea'
172        let ascender = read_i16_be(bytes, hhea_off + 4).unwrap_or(units_per_em as i16 * 4 / 5);
173        let descender = read_i16_be(bytes, hhea_off + 6).unwrap_or(-(units_per_em as i16 / 5));
174        let line_gap = read_i16_be(bytes, hhea_off + 8).unwrap_or(0);
175        let number_of_h_metrics = read_u16_be(bytes, hhea_off + 34).unwrap_or(1);
176
177        // 3. Read 'maxp'
178        let num_glyphs = if let Some(off) = maxp_offset {
179            read_u16_be(bytes, off + 4).unwrap_or(1)
180        } else {
181            number_of_h_metrics
182        };
183
184        // 4. Read 'OS/2' (if present)
185        let mut weight_class = if head_bold { 700 } else { 400 };
186        let mut is_italic = head_italic;
187        let mut is_monospace = false;
188        let mut typo_ascender = ascender;
189        let mut typo_descender = descender;
190        let mut typo_line_gap = line_gap;
191        let mut x_height = None;
192        let mut cap_height = None;
193
194        if let Some(off) = os2_offset {
195            if let Some(version) = read_u16_be(bytes, off) {
196                if let Some(w) = read_u16_be(bytes, off + 4) {
197                    if w > 0 {
198                        weight_class = w;
199                    }
200                }
201                if let Some(panose4) = bytes.get(off + 35) {
202                    if *panose4 == 9 {
203                        is_monospace = true;
204                    }
205                }
206                let use_typo_metrics = if let Some(sel) = read_u16_be(bytes, off + 62) {
207                    if (sel & 1) != 0 {
208                        is_italic = true;
209                    }
210                    (sel & 0x0080) != 0
211                } else {
212                    false
213                };
214                if let Some(t_asc) = read_i16_be(bytes, off + 68) {
215                    if (use_typo_metrics || typo_ascender == 0) && t_asc != 0 {
216                        typo_ascender = t_asc;
217                    }
218                }
219                if let Some(t_desc) = read_i16_be(bytes, off + 70) {
220                    if (use_typo_metrics || typo_descender == 0) && t_desc != 0 {
221                        typo_descender = t_desc;
222                    }
223                }
224                if let Some(t_gap) = read_i16_be(bytes, off + 72) {
225                    if use_typo_metrics || typo_line_gap == 0 {
226                        typo_line_gap = t_gap;
227                    }
228                }
229                if version >= 2 {
230                    if let Some(xh) = read_i16_be(bytes, off + 86) {
231                        if xh > 0 {
232                            x_height = Some(xh);
233                        }
234                    }
235                    if let Some(ch) = read_i16_be(bytes, off + 88) {
236                        if ch > 0 {
237                            cap_height = Some(ch);
238                        }
239                    }
240                }
241            }
242        }
243
244        // 5. Read 'cmap'
245        let num_cmap_subtables =
246            read_u16_be(bytes, cmap_off + 2).ok_or(OpenTypeParseError::UnexpectedEof)? as usize;
247        let mut chosen_subtable = None;
248        let mut chosen_format = 0;
249
250        for s in 0..num_cmap_subtables {
251            let record_off = cmap_off + 4 + s * 8;
252            let platform_id = read_u16_be(bytes, record_off).unwrap_or(0);
253            let encoding_id = read_u16_be(bytes, record_off + 2).unwrap_or(0);
254            let sub_off = cmap_off + read_u32_be(bytes, record_off + 4).unwrap_or(0) as usize;
255
256            let format = read_u16_be(bytes, sub_off).unwrap_or(0);
257            // Format 12 (Unicode 32-bit UCS-4) is preferred
258            if format == 12 && (platform_id == 0 || (platform_id == 3 && encoding_id == 10)) {
259                chosen_subtable = Some(sub_off);
260                chosen_format = 12;
261                break;
262            }
263            // Format 4 (Unicode 16-bit BMP)
264            if format == 4
265                && (platform_id == 0
266                    || (platform_id == 3 && (encoding_id == 1 || encoding_id == 0)))
267                && chosen_format != 12
268            {
269                chosen_subtable = Some(sub_off);
270                chosen_format = 4;
271            }
272        }
273
274        let (cmap_subtable_offset, cmap_format) = match chosen_subtable {
275            Some(off) => (off, chosen_format),
276            None => return Err(OpenTypeParseError::TableNotFound("cmap Unicode subtable")),
277        };
278
279        // 6. Read 'kern' table (Format 0 pair kerning)
280        let mut kern_subtable_offset = None;
281        if let Some(k_off) = kern_offset {
282            let version = read_u16_be(bytes, k_off).unwrap_or(1);
283            let n_tables = read_u16_be(bytes, k_off + 2).unwrap_or(0);
284            if version == 0 && n_tables > 0 {
285                let sub_off = k_off + 4;
286                let sub_version = read_u16_be(bytes, sub_off).unwrap_or(0);
287                let coverage = read_u16_be(bytes, sub_off + 4).unwrap_or(0);
288                // Format 0 (horizontal, kerning)
289                if sub_version == 0 && (coverage & 1) != 0 && (coverage >> 8) == 0 {
290                    kern_subtable_offset = Some(sub_off + 6);
291                }
292            }
293        }
294
295        // 7. Read 'GSUB' table (Glyph Substitution features: liga, calt, dlig, smcp)
296        let mut supported_features = Vec::new();
297        if let Some(gsub_off) = gsub_offset {
298            if let Some(feature_list_rel) = read_u16_be(bytes, gsub_off + 6) {
299                let feature_list_off = gsub_off + feature_list_rel as usize;
300                if let Some(feature_count) = read_u16_be(bytes, feature_list_off) {
301                    for fi in 0..feature_count as usize {
302                        let rec_off = feature_list_off + 2 + fi * 6;
303                        if rec_off + 4 <= bytes.len() {
304                            let tag: [u8; 4] = [
305                                bytes[rec_off],
306                                bytes[rec_off + 1],
307                                bytes[rec_off + 2],
308                                bytes[rec_off + 3],
309                            ];
310                            if !supported_features.contains(&tag) {
311                                supported_features.push(tag);
312                            }
313                        }
314                    }
315                }
316            }
317        }
318
319        Ok(Self {
320            data: Arc::from(bytes.to_vec()),
321            units_per_em,
322            ascender,
323            descender,
324            line_gap,
325            typo_ascender,
326            typo_descender,
327            typo_line_gap,
328            x_height,
329            cap_height,
330            weight_class,
331            is_italic,
332            is_monospace,
333            num_glyphs,
334            number_of_h_metrics,
335            hmtx_offset: hmtx_off,
336            cmap_subtable_offset,
337            cmap_format,
338            kern_subtable_offset,
339            gsub_offset,
340            supported_features,
341        })
342    }
343
344    /// Checks whether this font supports a specific OpenType feature tag (e.g. `*b"liga"`, `*b"calt"`, `*b"dlig"`, `*b"smcp"`).
345    #[inline]
346    pub fn has_feature(&self, tag: &[u8; 4]) -> bool {
347        self.supported_features.contains(tag)
348    }
349
350    /// Resolves character to glyph ID via cmap subtable.
351    pub fn glyph_id(&self, c: char) -> u16 {
352        let cp = c as u32;
353        if self.cmap_format == 12 {
354            // Format 12: 32-bit sequential groups
355            let num_groups =
356                read_u32_be(&self.data, self.cmap_subtable_offset + 12).unwrap_or(0) as usize;
357            let groups_start = self.cmap_subtable_offset + 16;
358
359            let mut low = 0;
360            let mut high = num_groups;
361            while low < high {
362                let mid = (low + high) / 2;
363                let entry_off = groups_start + mid * 12;
364                let start_char = read_u32_be(&self.data, entry_off).unwrap_or(u32::MAX);
365                let end_char = read_u32_be(&self.data, entry_off + 4).unwrap_or(0);
366                let start_glyph = read_u32_be(&self.data, entry_off + 8).unwrap_or(0);
367
368                if cp < start_char {
369                    high = mid;
370                } else if cp > end_char {
371                    low = mid + 1;
372                } else {
373                    return (start_glyph + (cp - start_char)) as u16;
374                }
375            }
376            0
377        } else if self.cmap_format == 4 {
378            if cp > 0xFFFF {
379                return 0;
380            }
381            let seg_count =
382                (read_u16_be(&self.data, self.cmap_subtable_offset + 6).unwrap_or(0) / 2) as usize;
383            if seg_count == 0 {
384                return 0;
385            }
386
387            let end_codes_start = self.cmap_subtable_offset + 14;
388            let start_codes_start = end_codes_start + seg_count * 2 + 2;
389            let id_deltas_start = start_codes_start + seg_count * 2;
390            let id_range_offsets_start = id_deltas_start + seg_count * 2;
391
392            for i in 0..seg_count {
393                let end_code = read_u16_be(&self.data, end_codes_start + i * 2).unwrap_or(0) as u32;
394                if end_code >= cp {
395                    let start_code =
396                        read_u16_be(&self.data, start_codes_start + i * 2).unwrap_or(0) as u32;
397                    if start_code <= cp {
398                        let id_delta =
399                            read_i16_be(&self.data, id_deltas_start + i * 2).unwrap_or(0) as i32;
400                        let id_range_offset =
401                            read_u16_be(&self.data, id_range_offsets_start + i * 2).unwrap_or(0)
402                                as usize;
403
404                        if id_range_offset == 0 {
405                            return ((cp as i32 + id_delta) & 0xFFFF) as u16;
406                        } else {
407                            let glyph_offset = id_range_offsets_start
408                                + i * 2
409                                + id_range_offset
410                                + (cp - start_code) as usize * 2;
411                            if let Some(glyph_id) = read_u16_be(&self.data, glyph_offset) {
412                                if glyph_id != 0 {
413                                    return ((glyph_id as i32 + id_delta) & 0xFFFF) as u16;
414                                }
415                            }
416                        }
417                    }
418                    break;
419                }
420            }
421            0
422        } else {
423            0
424        }
425    }
426
427    /// Retrieves glyph advance width in font design units from `hmtx`.
428    #[inline]
429    pub fn glyph_advance_units(&self, gid: u16) -> u16 {
430        if self.number_of_h_metrics == 0 {
431            return self.units_per_em;
432        }
433        if gid < self.number_of_h_metrics {
434            let offset = self.hmtx_offset + (gid as usize) * 4;
435            read_u16_be(&self.data, offset).unwrap_or(self.units_per_em)
436        } else {
437            let offset = self.hmtx_offset + (self.number_of_h_metrics as usize - 1) * 4;
438            read_u16_be(&self.data, offset).unwrap_or(self.units_per_em)
439        }
440    }
441
442    /// Advance width in ems (fraction of font size).
443    #[inline]
444    pub fn glyph_advance_em(&self, gid: u16) -> f32 {
445        self.glyph_advance_units(gid) as f32 / self.units_per_em.max(1) as f32
446    }
447
448    /// Advance width in CSS pixels for a given font size.
449    #[inline]
450    pub fn glyph_advance(&self, gid: u16, font_size: f32) -> f32 {
451        self.glyph_advance_em(gid) * font_size
452    }
453
454    /// Computes advance width in CSS pixels for a character.
455    #[inline]
456    pub fn char_advance(&self, c: char, font_size: f32) -> f32 {
457        let gid = self.glyph_id(c);
458        self.glyph_advance(gid, font_size)
459    }
460
461    /// Retrieves pair kerning adjustment between two glyphs in font design units.
462    pub fn pair_kerning_units(&self, left_gid: u16, right_gid: u16) -> i16 {
463        let sub_off = match self.kern_subtable_offset {
464            Some(off) => off,
465            None => return 0,
466        };
467
468        let n_pairs = read_u16_be(&self.data, sub_off).unwrap_or(0) as usize;
469        let pairs_start = sub_off + 8;
470        let target_pair = ((left_gid as u32) << 16) | (right_gid as u32);
471
472        let mut low = 0;
473        let mut high = n_pairs;
474        while low < high {
475            let mid = (low + high) / 2;
476            let pair_off = pairs_start + mid * 6;
477            let pair = read_u32_be(&self.data, pair_off).unwrap_or(u32::MAX);
478            if pair < target_pair {
479                low = mid + 1;
480            } else if pair > target_pair {
481                high = mid;
482            } else {
483                return read_i16_be(&self.data, pair_off + 4).unwrap_or(0);
484            }
485        }
486        0
487    }
488
489    /// Pair kerning adjustment in ems.
490    #[inline]
491    pub fn pair_kerning_em(&self, left_gid: u16, right_gid: u16) -> f32 {
492        self.pair_kerning_units(left_gid, right_gid) as f32 / self.units_per_em.max(1) as f32
493    }
494
495    /// Pair kerning adjustment in CSS pixels for a given font size.
496    #[inline]
497    pub fn pair_kerning(&self, left_gid: u16, right_gid: u16, font_size: f32) -> f32 {
498        self.pair_kerning_em(left_gid, right_gid) * font_size
499    }
500
501    /// Generates exact `FontMetrics` scaled to CSS pixels.
502    pub fn font_metrics(&self, font_size: f32) -> FontMetrics {
503        let scale = font_size / self.units_per_em.max(1) as f32;
504        let ascent = ((self.typo_ascender as f32 * scale).max(0.0) * LayoutUnit::SCALE).round()
505            / LayoutUnit::SCALE;
506        let descent = (((-self.typo_descender).max(0) as f32 * scale) * LayoutUnit::SCALE).round()
507            / LayoutUnit::SCALE;
508        let line_gap = ((self.typo_line_gap.max(0) as f32 * scale) * LayoutUnit::SCALE).round()
509            / LayoutUnit::SCALE;
510
511        let x_height = match self.x_height {
512            Some(xh) if xh > 0 => {
513                ((xh as f32 * scale) * LayoutUnit::SCALE).round() / LayoutUnit::SCALE
514            }
515            _ => (ascent * 0.52 * LayoutUnit::SCALE).round() / LayoutUnit::SCALE,
516        };
517
518        let cap_height = match self.cap_height {
519            Some(ch) if ch > 0 => {
520                ((ch as f32 * scale) * LayoutUnit::SCALE).round() / LayoutUnit::SCALE
521            }
522            _ => (ascent * 0.72 * LayoutUnit::SCALE).round() / LayoutUnit::SCALE,
523        };
524
525        FontMetrics {
526            ascent: LayoutUnit::from_f32(ascent),
527            descent: LayoutUnit::from_f32(descent),
528            line_gap: LayoutUnit::from_f32(line_gap),
529            x_height: LayoutUnit::from_f32(x_height),
530            cap_height: LayoutUnit::from_f32(cap_height),
531            units_per_em: self.units_per_em,
532            font_size,
533        }
534    }
535}
536
537/// Global Thread-Safe Font Database managing OpenType font faces.
538pub struct FontDatabase {
539    fonts: RwLock<HashMap<(String, u16, bool), Arc<OpenTypeFont>>>,
540}
541
542impl Default for FontDatabase {
543    fn default() -> Self {
544        Self::new()
545    }
546}
547
548impl FontDatabase {
549    pub fn new() -> Self {
550        let db = Self {
551            fonts: RwLock::new(HashMap::new()),
552        };
553        db.load_standard_system_fonts();
554        db
555    }
556
557    /// Registers font data for a specific family name.
558    pub fn register_font_data(
559        &self,
560        family: &str,
561        data: &[u8],
562    ) -> Result<Arc<OpenTypeFont>, OpenTypeParseError> {
563        let font = Arc::new(OpenTypeFont::parse(data)?);
564        let key = (family.to_lowercase(), font.weight_class, font.is_italic);
565        if let Ok(mut lock) = self.fonts.write() {
566            lock.insert(key, font.clone());
567        }
568        Ok(font)
569    }
570
571    /// Queries the best matching OpenType font face for family, weight, and style.
572    pub fn query_font(
573        &self,
574        family_name: &str,
575        weight: FontWeight,
576        style: FontStyle,
577    ) -> Option<Arc<OpenTypeFont>> {
578        let target_weight = match weight {
579            FontWeight::Thin => 100,
580            FontWeight::ExtraLight => 200,
581            FontWeight::Light => 300,
582            FontWeight::Normal => 400,
583            FontWeight::Medium => 500,
584            FontWeight::SemiBold => 600,
585            FontWeight::Bold => 700,
586            FontWeight::ExtraBold => 800,
587            FontWeight::Black => 900,
588        };
589        let is_italic = matches!(style, FontStyle::Italic | FontStyle::Oblique);
590        let family_lower = family_name.to_lowercase();
591
592        if let Ok(lock) = self.fonts.read() {
593            // Exact match
594            if let Some(font) = lock.get(&(family_lower.clone(), target_weight, is_italic)) {
595                return Some(font.clone());
596            }
597
598            // Closest weight match with same italic
599            let mut best_match: Option<(u16, Arc<OpenTypeFont>)> = None;
600            for ((fam, w, it), font) in lock.iter() {
601                if fam == &family_lower && *it == is_italic {
602                    let diff = (*w as i32 - target_weight as i32).unsigned_abs() as u16;
603                    match best_match {
604                        Some((best_diff, _)) if diff < best_diff => {
605                            best_match = Some((diff, font.clone()));
606                        }
607                        None => {
608                            best_match = Some((diff, font.clone()));
609                        }
610                        _ => {}
611                    }
612                }
613            }
614            if let Some((_, font)) = best_match {
615                return Some(font);
616            }
617
618            // Fallback: any font for family
619            for ((fam, _, _), font) in lock.iter() {
620                if fam == &family_lower {
621                    return Some(font.clone());
622                }
623            }
624        }
625
626        // Try dynamically loading from disk
627        if let Some(font) = self.try_load_system_font(&family_lower, target_weight, is_italic) {
628            return Some(font);
629        }
630
631        None
632    }
633
634    fn try_load_system_font(
635        &self,
636        family: &str,
637        target_weight: u16,
638        is_italic: bool,
639    ) -> Option<Arc<OpenTypeFont>> {
640        let is_bold = target_weight >= 600;
641        let candidates = match family {
642            "dejavu sans" | "sans-serif" | "sans" => {
643                if is_bold && is_italic {
644                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"]
645                } else if is_bold {
646                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]
647                } else if is_italic {
648                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf"]
649                } else {
650                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
651                }
652            }
653            "dejavu sans mono" | "monospace" | "mono" => {
654                if is_bold {
655                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"]
656                } else {
657                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"]
658                }
659            }
660            "dejavu serif" | "serif" => {
661                if is_bold {
662                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf"]
663                } else {
664                    vec!["/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf"]
665                }
666            }
667            _ => vec![],
668        };
669
670        for path in candidates {
671            if let Ok(bytes) = std::fs::read(path) {
672                if let Ok(font) = self.register_font_data(family, &bytes) {
673                    return Some(font);
674                }
675            }
676        }
677        None
678    }
679
680    fn load_standard_system_fonts(&self) {
681        let system_fonts = [
682            (
683                "dejavu sans",
684                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
685            ),
686            (
687                "dejavu sans",
688                "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
689            ),
690            (
691                "dejavu sans mono",
692                "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
693            ),
694            (
695                "dejavu sans mono",
696                "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",
697            ),
698            (
699                "dejavu serif",
700                "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
701            ),
702            (
703                "dejavu serif",
704                "/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf",
705            ),
706        ];
707
708        for (family, path) in system_fonts {
709            if let Ok(bytes) = std::fs::read(path) {
710                let _ = self.register_font_data(family, &bytes);
711            }
712        }
713    }
714}
715
716/// Global shared font database instance.
717static GLOBAL_FONT_DATABASE: OnceLock<FontDatabase> = OnceLock::new();
718
719/// Returns reference to the global font database.
720pub fn font_database() -> &'static FontDatabase {
721    GLOBAL_FONT_DATABASE.get_or_init(FontDatabase::new)
722}
723
724/// Helper to lookup an OpenType font for an AtomId font family.
725pub fn lookup_font_for_style(
726    family: AtomId,
727    weight: FontWeight,
728    style: FontStyle,
729) -> Option<Arc<OpenTypeFont>> {
730    let db = font_database();
731    if let Some(family_name) = strata_primitives::atom::resolve(family) {
732        if let Some(font) = db.query_font(&family_name, weight, style) {
733            return Some(font);
734        }
735    }
736
737    if family == AtomId::FONT_MONO {
738        if let Some(font) = db.query_font("dejavu sans mono", weight, style) {
739            return Some(font);
740        }
741    }
742
743    db.query_font("dejavu sans", weight, style)
744}