normordis-pdf 2.5.1

Institutional PDF generation for Portuguese public administration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use std::collections::HashMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::{NormaxisPdfError, Result};

// ── FontFallbackChain ─────────────────────────────────────────────────────────

/// Font fallback chain for missing glyphs or unregistered font names.
///
/// When the primary font for a paragraph is not registered, the engine tries
/// each name in `fonts` in order.  The first registered one wins.
/// If none resolve, the document default is used.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FontFallbackChain {
    pub fonts: Vec<String>,
}

impl FontFallbackChain {
    pub fn new(fonts: Vec<&str>) -> Self {
        Self { fonts: fonts.into_iter().map(|s| s.to_string()).collect() }
    }
}

// Libertinus Serif — kept for backward compatibility.
const LIBERTINUS_SERIF_REGULAR: &[u8] =
    include_bytes!("../assets/fonts/LibertinusSerif-Regular.ttf");
const LIBERTINUS_SERIF_BOLD: &[u8] =
    include_bytes!("../assets/fonts/LibertinusSerif-Bold.ttf");
const LIBERTINUS_SERIF_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LibertinusSerif-Italic.ttf");
const LIBERTINUS_SERIF_BOLD_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LibertinusSerif-BoldItalic.ttf");

// Liberation Sans — metrically identical to Arial/Calibri.
const LIBERATION_SANS_REGULAR: &[u8] =
    include_bytes!("../assets/fonts/LiberationSans-Regular.ttf");
const LIBERATION_SANS_BOLD: &[u8] =
    include_bytes!("../assets/fonts/LiberationSans-Bold.ttf");
const LIBERATION_SANS_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationSans-Italic.ttf");
const LIBERATION_SANS_BOLD_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationSans-BoldItalic.ttf");

// Liberation Serif — Times New Roman equivalent.
const LIBERATION_SERIF_REGULAR: &[u8] =
    include_bytes!("../assets/fonts/LiberationSerif-Regular.ttf");
const LIBERATION_SERIF_BOLD: &[u8] =
    include_bytes!("../assets/fonts/LiberationSerif-Bold.ttf");
const LIBERATION_SERIF_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationSerif-Italic.ttf");
const LIBERATION_SERIF_BOLD_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationSerif-BoldItalic.ttf");

// Liberation Mono — Courier New equivalent.
const LIBERATION_MONO_REGULAR: &[u8] =
    include_bytes!("../assets/fonts/LiberationMono-Regular.ttf");
const LIBERATION_MONO_BOLD: &[u8] =
    include_bytes!("../assets/fonts/LiberationMono-Bold.ttf");
const LIBERATION_MONO_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationMono-Italic.ttf");
const LIBERATION_MONO_BOLD_ITALIC: &[u8] =
    include_bytes!("../assets/fonts/LiberationMono-BoldItalic.ttf");

// ── ShapedGlyph ───────────────────────────────────────────────────────────────

/// Single glyph produced by the rustybuzz shaping pipeline.
#[derive(Debug, Clone)]
pub struct ShapedGlyph {
    pub glyph_id: u16,
    /// Horizontal advance in font design units.
    pub x_advance: i32,
    pub x_offset: i32,
    pub y_offset: i32,
    /// UTF-8 byte index of the source cluster in the input string.
    pub cluster: u32,
}

// ── FontData ──────────────────────────────────────────────────────────────────

/// A single font variant — raw TTF/OTF bytes + parsed metrics.
///
/// Replaces `FontVariant` from v1.3.x.  Use [`FontVariants`] to group the four
/// weight/style variants of a family together.
pub struct FontData {
    pub bytes: Vec<u8>,
    pub units_per_em: u16,
}

impl FontData {
    /// Load a font from a TTF/OTF file on disk.
    pub fn from_file(path: &Path) -> Result<Self> {
        let bytes = std::fs::read(path).map_err(NormaxisPdfError::IoError)?;
        Self::from_bytes(bytes)
    }

    /// Parse a font from raw bytes (e.g., `include_bytes!`).
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        let face = ttf_parser::Face::parse(&bytes, 0)
            .map_err(|e| NormaxisPdfError::FontLoadError(e.to_string()))?;
        let units_per_em = face.units_per_em();
        Ok(Self { bytes, units_per_em })
    }

    /// Shape `text` with the given OpenType features and return per-glyph metrics.
    ///
    /// Creates an ephemeral `rustybuzz::Face` per call to avoid lifetime issues.
    pub fn shape(&self, text: &str, features: &[rustybuzz::Feature]) -> Vec<ShapedGlyph> {
        let face = match rustybuzz::Face::from_slice(&self.bytes, 0) {
            Some(f) => f,
            None => return vec![],
        };
        let mut buffer = rustybuzz::UnicodeBuffer::new();
        buffer.push_str(text);
        let output = rustybuzz::shape(&face, features, buffer);
        let infos = output.glyph_infos();
        let positions = output.glyph_positions();
        infos
            .iter()
            .zip(positions.iter())
            .map(|(info, pos)| ShapedGlyph {
                glyph_id: info.glyph_id as u16,
                x_advance: pos.x_advance,
                x_offset: pos.x_offset,
                y_offset: pos.y_offset,
                cluster: info.cluster,
            })
            .collect()
    }

    /// Advance width of `text` in mm at `font_size` points (72 pt/inch).
    pub fn measure_text_mm(&self, text: &str, font_size: f64) -> f64 {
        if text.is_empty() {
            return 0.0;
        }
        let glyphs = self.shape(text, &[]);
        let total_advance: i32 = glyphs.iter().map(|g| g.x_advance).sum();
        let advance_pts =
            (total_advance as f64 / self.units_per_em as f64) * font_size;
        advance_pts / 72.0 * 25.4
    }

    /// Line height in mm for `font_size` (pt) and a multiplier.
    pub fn line_height_mm(&self, font_size: f64, multiplier: f64) -> f64 {
        (font_size / 72.0 * 25.4) * multiplier
    }
}

impl Clone for FontData {
    fn clone(&self) -> Self {
        Self {
            bytes: self.bytes.clone(),
            units_per_em: self.units_per_em,
        }
    }
}

impl std::fmt::Debug for FontData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FontData")
            .field("bytes_len", &self.bytes.len())
            .field("units_per_em", &self.units_per_em)
            .finish()
    }
}

// ── FontVariants ──────────────────────────────────────────────────────────────

/// A font family with up to four weight/style variants.
///
/// Replaces `FontFamily` from v1.3.x.
#[derive(Debug, Clone)]
pub struct FontVariants {
    pub name: String,
    pub regular: FontData,
    pub bold: Option<FontData>,
    pub italic: Option<FontData>,
    pub bold_italic: Option<FontData>,
}

impl FontVariants {
    /// Load a family from raw bytes (e.g., `include_bytes!`).
    pub fn from_bytes(
        name: impl Into<String>,
        regular: Vec<u8>,
        bold: Option<Vec<u8>>,
        italic: Option<Vec<u8>>,
        bold_italic: Option<Vec<u8>>,
    ) -> Result<Self> {
        Ok(Self {
            name: name.into(),
            regular: FontData::from_bytes(regular)?,
            bold: bold.map(FontData::from_bytes).transpose()?,
            italic: italic.map(FontData::from_bytes).transpose()?,
            bold_italic: bold_italic.map(FontData::from_bytes).transpose()?,
        })
    }

    /// Load a family from TTF/OTF file paths.
    pub fn from_files(
        name: impl Into<String>,
        regular: &Path,
        bold: Option<&Path>,
        italic: Option<&Path>,
        bold_italic: Option<&Path>,
    ) -> Result<Self> {
        let read = |p: &Path| -> Result<Vec<u8>> {
            std::fs::read(p).map_err(NormaxisPdfError::IoError)
        };
        Self::from_bytes(
            name,
            read(regular)?,
            bold.map(read).transpose()?,
            italic.map(read).transpose()?,
            bold_italic.map(read).transpose()?,
        )
    }

    /// Returns the best available variant for `(bold, italic)`, falling back to regular.
    pub fn get(&self, bold: bool, italic: bool) -> &FontData {
        match (bold, italic) {
            (true, true) => self
                .bold_italic
                .as_ref()
                .or(self.bold.as_ref())
                .or(self.italic.as_ref())
                .unwrap_or(&self.regular),
            (true, false) => self.bold.as_ref().unwrap_or(&self.regular),
            (false, true) => self.italic.as_ref().unwrap_or(&self.regular),
            (false, false) => &self.regular,
        }
    }

    /// Alias for [`get`](Self::get) — kept for backward compatibility with v1.3.x callers.
    pub fn get_variant(&self, bold: bool, italic: bool) -> &FontData {
        self.get(bold, italic)
    }

    /// Advance width of `text` in mm using the appropriate variant.
    pub fn measure_text_mm(&self, text: &str, font_size: f64, bold: bool, italic: bool) -> f64 {
        self.get(bold, italic).measure_text_mm(text, font_size)
    }

    /// Line height in mm for `font_size` (pt) and a multiplier.
    pub fn line_height_mm(&self, font_size: f64, line_height_multiplier: f64) -> f64 {
        self.regular.line_height_mm(font_size, line_height_multiplier)
    }
}

// Backward-compatibility aliases for v1.3.x callers.
pub type FontFamily = FontVariants;
pub type FontVariant = FontData;

// ── FontRegistry ──────────────────────────────────────────────────────────────

/// Registry of font families available in the document.
///
/// `FontRegistry::default()` embeds Liberation Sans, Serif, and Mono, with
/// common Word font aliases pre-configured.
#[derive(Debug, Clone)]
pub struct FontRegistry {
    families: HashMap<String, FontVariants>,
    /// Maps alias name → canonical family name (e.g. "Arial" → "LiberationSans").
    aliases: HashMap<String, String>,
    default_family: String,
    monospace_family: Option<String>,
}

impl FontRegistry {
    /// Creates a registry with the default embedded fonts (Liberation Sans/Serif/Mono).
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates an empty registry with no registered fonts.
    pub fn empty() -> Self {
        Self {
            families: HashMap::new(),
            aliases: HashMap::new(),
            default_family: String::new(),
            monospace_family: None,
        }
    }

    /// Register a font family from embedded `&'static [u8]` bytes.
    ///
    /// If this is the first family registered, it becomes the default.
    pub fn register_embedded(
        &mut self,
        name: &str,
        regular: &'static [u8],
        bold: Option<&'static [u8]>,
        italic: Option<&'static [u8]>,
        bold_italic: Option<&'static [u8]>,
    ) {
        let family = FontVariants::from_bytes(
            name,
            regular.to_vec(),
            bold.map(|b| b.to_vec()),
            italic.map(|b| b.to_vec()),
            bold_italic.map(|b| b.to_vec()),
        )
        .expect("embedded font bytes must be valid");
        if self.default_family.is_empty() {
            self.default_family = name.to_string();
        }
        self.families.insert(name.to_string(), family);
    }

    /// Map `alias` to an already-registered family name.
    ///
    /// Subsequent calls to `get_family(alias)` will resolve to the target family.
    pub fn add_alias(&mut self, alias: &str, target: &str) {
        self.aliases.insert(alias.to_string(), target.to_string());
    }

    /// Returns a family by name, resolving aliases transparently.
    ///
    /// Falls back to the default family when neither the name nor any alias matches.
    pub fn get_family(&self, name: &str) -> &FontVariants {
        if let Some(fam) = self.families.get(name) {
            return fam;
        }
        if let Some(target) = self.aliases.get(name) {
            if let Some(fam) = self.families.get(target.as_str()) {
                return fam;
            }
        }
        self.get_default()
    }

    /// Register a font family. Replaces any existing family with the same name.
    pub fn register(&mut self, family: FontVariants) {
        let name = family.name.clone();
        if self.default_family.is_empty() {
            self.default_family = name.clone();
        }
        self.families.insert(name, family);
    }

    pub fn set_default(&mut self, name: &str) -> Result<()> {
        if self.families.contains_key(name) {
            self.default_family = name.to_string();
            Ok(())
        } else {
            Err(NormaxisPdfError::FontLoadError(format!(
                "font family '{name}' not registered"
            )))
        }
    }

    pub fn set_monospace(&mut self, name: &str) -> Result<()> {
        if self.families.contains_key(name) {
            self.monospace_family = Some(name.to_string());
            Ok(())
        } else {
            Err(NormaxisPdfError::FontLoadError(format!(
                "font family '{name}' not registered"
            )))
        }
    }

    /// Iterates over all registered families.
    pub fn families(&self) -> impl Iterator<Item = (&str, &FontVariants)> {
        self.families.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Name of the default font family.
    pub fn default_family_name(&self) -> &str {
        &self.default_family
    }

    /// Returns the named family, or `None` if not registered (does NOT resolve aliases).
    pub fn get(&self, name: &str) -> Option<&FontVariants> {
        self.families.get(name)
    }

    /// Returns the default font family (always valid).
    pub fn get_default(&self) -> &FontVariants {
        self.families
            .get(&self.default_family)
            .expect("default_family must be registered")
    }

    /// Returns the monospace family, or the default if none is set.
    pub fn get_monospace(&self) -> &FontVariants {
        self.monospace_family
            .as_deref()
            .and_then(|n| self.families.get(n))
            .unwrap_or_else(|| self.get_default())
    }

    /// Measures text using the named family (resolves aliases, falls back to default).
    pub fn measure_text_mm(
        &self,
        text: &str,
        family: &str,
        font_size: f64,
        bold: bool,
        italic: bool,
    ) -> f64 {
        self.get_family(family).measure_text_mm(text, font_size, bold, italic)
    }

    // ── v2.1.3 additions ─────────────────────────────────────────────────────

    /// Registers a font family from TTF/OTF files on disk.
    ///
    /// Only `regular_path` is required; bold/italic/bold_italic are optional.
    /// Missing variants fall back to regular at render time.
    pub fn register_file(
        &mut self,
        name: &str,
        regular_path: impl AsRef<Path>,
        bold_path: Option<impl AsRef<Path>>,
        italic_path: Option<impl AsRef<Path>>,
        bold_italic_path: Option<impl AsRef<Path>>,
    ) -> Result<()> {
        let family = FontVariants::from_files(
            name,
            regular_path.as_ref(),
            bold_path.as_ref().map(|p| p.as_ref()),
            italic_path.as_ref().map(|p| p.as_ref()),
            bold_italic_path.as_ref().map(|p| p.as_ref()),
        )?;
        self.register(family);
        Ok(())
    }

    /// Registers a font family from byte slices already in memory.
    ///
    /// Useful for fonts loaded from a database or network source.
    pub fn register_bytes(
        &mut self,
        name: &str,
        regular: &[u8],
        bold: Option<&[u8]>,
        italic: Option<&[u8]>,
        bold_italic: Option<&[u8]>,
    ) -> Result<()> {
        let family = FontVariants::from_bytes(
            name,
            regular.to_vec(),
            bold.map(|b| b.to_vec()),
            italic.map(|b| b.to_vec()),
            bold_italic.map(|b| b.to_vec()),
        )?;
        self.register(family);
        Ok(())
    }

    /// Registers a single font file without bold/italic variants.
    pub fn register_single(&mut self, name: &str, path: impl AsRef<Path>) -> Result<()> {
        self.register_file(name, path, None::<&Path>, None::<&Path>, None::<&Path>)
    }

    /// Registers a single font from bytes without bold/italic variants.
    pub fn register_single_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<()> {
        self.register_bytes(name, bytes, None, None, None)
    }

    /// Resolves a font name through the alias chain (max 8 hops).
    ///
    /// Returns `None` when the font is not registered (even after alias
    /// resolution).  Use `resolve()` for a version that always returns a family.
    pub fn try_resolve(&self, name: &str, depth: u8) -> Option<&FontVariants> {
        if depth > 8 {
            eprintln!("WARNING: font alias cycle detected for '{name}'");
            return None;
        }
        if let Some(family) = self.families.get(name) {
            return Some(family);
        }
        if let Some(target) = self.aliases.get(name) {
            return self.try_resolve(target, depth + 1);
        }
        None
    }

    /// Resolves a font name through the alias chain.
    ///
    /// Never returns `None` — always falls back to the default family.
    pub fn resolve(&self, name: &str) -> &FontVariants {
        self.try_resolve(name, 0).unwrap_or_else(|| self.get_default())
    }

    /// Returns `true` if the name resolves to a registered family (directly or via alias).
    pub fn contains(&self, name: &str) -> bool {
        self.try_resolve(name, 0).is_some() || self.aliases.contains_key(name)
    }

    /// Returns the names of all directly registered font families.
    pub fn registered_families(&self) -> Vec<&str> {
        self.families.keys().map(|s| s.as_str()).collect()
    }

    /// Loads all TTF/OTF fonts from a directory into this registry.
    ///
    /// Files are grouped by the stem prefix before the last separator (`-`, `_`, ` `).
    /// Recognised variant suffixes: `Regular`, `Bold`, `Italic`, `BoldItalic`.
    /// Returns the number of families added.
    pub fn load_dir(&mut self, dir: impl AsRef<Path>) -> Result<usize> {
        let dir = dir.as_ref();
        if !dir.is_dir() {
            return Err(NormaxisPdfError::FontLoadError(
                format!("not a directory: {}", dir.display()),
            ));
        }

        let mut map: HashMap<String, [Option<Vec<u8>>; 4]> = HashMap::new();

        for entry in std::fs::read_dir(dir).map_err(NormaxisPdfError::IoError)? {
            let path = entry.map_err(NormaxisPdfError::IoError)?.path();
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !matches!(ext.to_lowercase().as_str(), "ttf" | "otf") {
                continue;
            }
            let stem = match path.file_stem().and_then(|s| s.to_str()) {
                Some(s) => s.to_string(),
                None => continue,
            };
            let (family, variant) = detect_variant_suffix(&stem);
            let bytes = std::fs::read(&path).map_err(NormaxisPdfError::IoError)?;
            let slot = map.entry(family).or_insert([None, None, None, None]);
            match variant.to_lowercase().as_str() {
                "regular" => slot[0] = Some(bytes),
                "bold" => slot[1] = Some(bytes),
                "italic" => slot[2] = Some(bytes),
                "bolditalic" | "bold_italic" | "bold italic" => slot[3] = Some(bytes),
                _ => {}
            }
        }

        let count = map.len();
        for (name, [regular, bold, italic, bold_italic]) in map {
            if let Some(reg_bytes) = regular {
                let fam = FontVariants::from_bytes(name.clone(), reg_bytes, bold, italic, bold_italic)?;
                self.register(fam);
            }
        }
        Ok(count)
    }
}

/// Detects variant suffix in a font filename stem.
///
/// `"MyFont-Bold"` → `("MyFont", "Bold")`, `"MyFont"` → `("MyFont", "Regular")`.
fn detect_variant_suffix(stem: &str) -> (String, String) {
    const VARIANTS: &[&str] = &[
        "BoldItalic", "Bold Italic", "Bold_Italic",
        "Bold", "Italic", "Regular", "Light", "Medium",
        "Thin", "ExtraBold", "Black", "SemiBold",
    ];
    for sep in &['-', '_', ' '] {
        if let Some(pos) = stem.rfind(*sep) {
            let suffix = &stem[pos + 1..];
            if VARIANTS.iter().any(|v| v.eq_ignore_ascii_case(suffix)) {
                return (stem[..pos].to_string(), suffix.to_string());
            }
        }
    }
    (stem.to_string(), "Regular".to_string())
}

impl FontRegistry {
    /// Load a [`FontRegistry`] from a directory of TTF/OTF font files.
    ///
    /// Files are grouped into families by the stem prefix before the last `-`.
    /// Variant suffixes recognised (case-insensitive): `Regular`, `Bold`,
    /// `Italic`, `BoldItalic`.  At least one family with a `Regular` variant
    /// must exist; unknown-suffix files are silently skipped.
    pub fn from_dir(dir: &Path) -> crate::Result<FontRegistry> {
        let mut map: HashMap<String, [Option<Vec<u8>>; 4]> = HashMap::new();

        let entries = std::fs::read_dir(dir).map_err(NormaxisPdfError::IoError)?;
        for entry in entries {
            let path = entry.map_err(NormaxisPdfError::IoError)?.path();
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !matches!(ext.to_lowercase().as_str(), "ttf" | "otf") {
                continue;
            }
            let stem = match path.file_stem().and_then(|s| s.to_str()) {
                Some(s) => s.to_string(),
                None => continue,
            };
            let dash = match stem.rfind('-') {
                Some(p) => p,
                None => continue,
            };
            let family = stem[..dash].to_string();
            let variant = stem[dash + 1..].to_lowercase();
            let bytes = std::fs::read(&path).map_err(NormaxisPdfError::IoError)?;
            let slot = map.entry(family).or_insert([None, None, None, None]);
            match variant.as_str() {
                "regular" => slot[0] = Some(bytes),
                "bold" => slot[1] = Some(bytes),
                "italic" => slot[2] = Some(bytes),
                "bolditalic" | "bold_italic" => slot[3] = Some(bytes),
                _ => {}
            }
        }

        let mut families = HashMap::new();
        let mut default_family = String::new();
        for (name, [regular, bold, italic, bold_italic]) in map {
            if let Some(reg_bytes) = regular {
                let fam =
                    FontVariants::from_bytes(name.clone(), reg_bytes, bold, italic, bold_italic)?;
                if default_family.is_empty() {
                    default_family = name.clone();
                }
                families.insert(name, fam);
            }
        }

        if families.is_empty() {
            return Err(NormaxisPdfError::FontLoadError(format!(
                "no valid font families found in {}",
                dir.display()
            )));
        }

        Ok(FontRegistry { families, aliases: HashMap::new(), default_family, monospace_family: None })
    }

    /// Load a [`FontRegistry`] populated with all fonts found on the host system.
    ///
    /// Requires the `system-fonts` feature flag.
    #[cfg(feature = "system-fonts")]
    pub fn from_system() -> crate::Result<FontRegistry> {
        let mut db = fontdb::Database::new();
        db.load_system_fonts();

        let mut map: HashMap<String, [Option<Vec<u8>>; 4]> = HashMap::new();

        for face in db.faces() {
            let family = match face.families.first() {
                Some((f, _)) if !f.is_empty() => f.clone(),
                _ => continue,
            };
            let is_bold = face.weight.0 >= 600;
            let is_italic =
                matches!(face.style, fontdb::Style::Italic | fontdb::Style::Oblique);
            let bytes = match db.with_face_data(face.id, |data, _| data.to_vec()) {
                Some(b) => b,
                None => continue,
            };
            let slot = map.entry(family).or_insert([None, None, None, None]);
            let idx = match (is_bold, is_italic) {
                (false, false) => 0,
                (true, false) => 1,
                (false, true) => 2,
                (true, true) => 3,
            };
            if slot[idx].is_none() {
                slot[idx] = Some(bytes);
            }
        }

        let mut families = HashMap::new();
        let mut default_family = String::new();
        for (name, [regular, bold, italic, bold_italic]) in map {
            if let Some(reg_bytes) = regular {
                let fam =
                    FontVariants::from_bytes(name.clone(), reg_bytes, bold, italic, bold_italic)?;
                if default_family.is_empty() {
                    default_family = name.clone();
                }
                families.insert(name, fam);
            }
        }

        if families.is_empty() {
            return Err(NormaxisPdfError::FontLoadError(
                "no system fonts found".to_string(),
            ));
        }

        Ok(FontRegistry { families, aliases: HashMap::new(), default_family, monospace_family: None })
    }
}

impl Default for FontRegistry {
    /// Creates a registry with Liberation Sans (default), Serif, and Mono embedded,
    /// plus common Word font aliases pre-configured.
    fn default() -> Self {
        let mut registry = FontRegistry::empty();

        // Liberation Sans — default (metrically identical to Arial/Calibri)
        registry.register_embedded(
            "LiberationSans",
            LIBERATION_SANS_REGULAR,
            Some(LIBERATION_SANS_BOLD),
            Some(LIBERATION_SANS_ITALIC),
            Some(LIBERATION_SANS_BOLD_ITALIC),
        );

        // Liberation Serif — Times New Roman equivalent
        registry.register_embedded(
            "LiberationSerif",
            LIBERATION_SERIF_REGULAR,
            Some(LIBERATION_SERIF_BOLD),
            Some(LIBERATION_SERIF_ITALIC),
            Some(LIBERATION_SERIF_BOLD_ITALIC),
        );

        // Liberation Mono — Courier New equivalent
        registry.register_embedded(
            "LiberationMono",
            LIBERATION_MONO_REGULAR,
            Some(LIBERATION_MONO_BOLD),
            Some(LIBERATION_MONO_ITALIC),
            Some(LIBERATION_MONO_BOLD_ITALIC),
        );

        // Libertinus Serif — also available for explicit use
        registry.register_embedded(
            "LibertinusSerif",
            LIBERTINUS_SERIF_REGULAR,
            Some(LIBERTINUS_SERIF_BOLD),
            Some(LIBERTINUS_SERIF_ITALIC),
            Some(LIBERTINUS_SERIF_BOLD_ITALIC),
        );

        // Word font aliases → Liberation equivalents
        registry.add_alias("Arial",           "LiberationSans");
        registry.add_alias("Calibri",         "LiberationSans");
        registry.add_alias("Helvetica",       "LiberationSans");
        registry.add_alias("Times New Roman", "LiberationSerif");
        registry.add_alias("Cambria",         "LiberationSerif");
        registry.add_alias("Georgia",         "LiberationSerif");
        registry.add_alias("Courier New",     "LiberationMono");
        registry.add_alias("Consolas",        "LiberationMono");

        let _ = registry.set_default("LiberationSans");
        let _ = registry.set_monospace("LiberationMono");
        registry
    }
}

/// Pre-built [`FontVariants`] for Liberation Sans from embedded bytes.
pub fn liberation_sans_family() -> crate::Result<FontVariants> {
    FontVariants::from_bytes(
        "LiberationSans",
        LIBERATION_SANS_REGULAR.to_vec(),
        Some(LIBERATION_SANS_BOLD.to_vec()),
        Some(LIBERATION_SANS_ITALIC.to_vec()),
        Some(LIBERATION_SANS_BOLD_ITALIC.to_vec()),
    )
}

/// Pre-built [`FontVariants`] for Liberation Serif from embedded bytes.
pub fn liberation_serif_family() -> crate::Result<FontVariants> {
    FontVariants::from_bytes(
        "LiberationSerif",
        LIBERATION_SERIF_REGULAR.to_vec(),
        Some(LIBERATION_SERIF_BOLD.to_vec()),
        Some(LIBERATION_SERIF_ITALIC.to_vec()),
        Some(LIBERATION_SERIF_BOLD_ITALIC.to_vec()),
    )
}

/// Pre-built [`FontVariants`] for Liberation Mono from embedded bytes.
pub fn liberation_mono_family() -> crate::Result<FontVariants> {
    FontVariants::from_bytes(
        "LiberationMono",
        LIBERATION_MONO_REGULAR.to_vec(),
        Some(LIBERATION_MONO_BOLD.to_vec()),
        Some(LIBERATION_MONO_ITALIC.to_vec()),
        Some(LIBERATION_MONO_BOLD_ITALIC.to_vec()),
    )
}