markdown2pdf 1.0.0

Create PDF with Markdown files (a md to pdf transpiler)
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Font metrics cache for the renderer.
//!
//! Two paths live here side by side:
//!
//! - **Built-in path**: printpdf 0.9's PDF Type 1 built-ins
//!   (Helvetica / Times / Courier and their bold / italic variants).
//!   Zero file I/O. ASCII-only because lopdf 0.39's WinAnsiEncoding
//!   handling falls through to a raw UTF-8 byte passthrough — see
//!   `to_win1252` in `layout.rs` for the gory detail. Used as the
//!   fallback whenever no external font is configured.
//!
//! - **External path**: a real TTF/OTF parsed via `ttf-parser` (for
//!   glyph metrics + cmap walking) *and* via `printpdf::ParsedFont`
//!   (for PDF embedding). Full Unicode rendering, glyph-ID encoded
//!   text. Selected when [`FontConfig`](crate::fonts::FontConfig)
//!   resolves to a [`FontSource::File`](crate::fonts::FontSource) or
//!   [`FontSource::System`](crate::fonts::FontSource) that we can
//!   locate.
//!
//! For measurement (line wrapping) both paths produce point-width
//! values via [`VariantMetrics::measure`]. For emission, the layout
//! engine asks [`FontSet::handle_for`] which font handle and which
//! transliteration policy to use.

use std::collections::BTreeMap;
use std::path::PathBuf;

use printpdf::{BuiltinFont, FontId, PdfDocument, PdfFontHandle};
use ttf_parser::Face;

use super::ir::{RunFlags, VariantUsage};
use crate::fonts::{FontConfig, FontSource, find_system_font};

/// The set of built-in PDF fonts the renderer can fall back to when
/// no external Unicode font is loaded. Body / emphasis runs map to a
/// Helvetica variant; monospace runs map to Courier.
#[derive(Debug, Clone, Copy)]
pub enum FontVariant {
    HelveticaRegular,
    HelveticaBold,
    HelveticaItalic,
    HelveticaBoldItalic,
    CourierRegular,
    CourierBold,
    CourierItalic,
    CourierBoldItalic,
}

impl FontVariant {
    /// Pick the variant that matches a run's [`RunFlags`].
    pub fn for_flags(flags: RunFlags) -> Self {
        match (flags.monospace, flags.bold, flags.italic) {
            (true, true, true) => FontVariant::CourierBoldItalic,
            (true, true, false) => FontVariant::CourierBold,
            (true, false, true) => FontVariant::CourierItalic,
            (true, false, false) => FontVariant::CourierRegular,
            (false, true, true) => FontVariant::HelveticaBoldItalic,
            (false, true, false) => FontVariant::HelveticaBold,
            (false, false, true) => FontVariant::HelveticaItalic,
            (false, false, false) => FontVariant::HelveticaRegular,
        }
    }

    /// printpdf's [`BuiltinFont`] handle for emission.
    pub fn builtin(self) -> BuiltinFont {
        match self {
            FontVariant::HelveticaRegular => BuiltinFont::Helvetica,
            FontVariant::HelveticaBold => BuiltinFont::HelveticaBold,
            FontVariant::HelveticaItalic => BuiltinFont::HelveticaOblique,
            FontVariant::HelveticaBoldItalic => BuiltinFont::HelveticaBoldOblique,
            FontVariant::CourierRegular => BuiltinFont::Courier,
            FontVariant::CourierBold => BuiltinFont::CourierBold,
            FontVariant::CourierItalic => BuiltinFont::CourierOblique,
            FontVariant::CourierBoldItalic => BuiltinFont::CourierBoldOblique,
        }
    }
}

/// Per-variant glyph-width data extracted from the embedded TTF.
///
/// `unscaled_widths[c as usize]` is the advance width in font units
/// (typically 1/1000 em) for characters U+0000..=U+00FF. Anything
/// outside ASCII/Latin-1 falls back to the average width — the
/// built-in subsets only cover Win-1252 anyway, so unsupported
/// characters won't render correctly in the PDF either way.
pub struct VariantMetrics {
    pub units_per_em: u16,
    pub unscaled_widths: Box<[u16; 256]>,
    pub fallback_width: u16,
}

impl VariantMetrics {
    fn load(variant: FontVariant) -> Self {
        let subset = variant.builtin().get_subset_font();
        // The built-in subsets are uncompressed TTF bytes ready for parsing.
        let face = Face::parse(&subset.bytes, 0).expect("built-in subset font must parse");

        let units_per_em = face.units_per_em();
        let mut widths = Box::new([0u16; 256]);

        for (i, slot) in widths.iter_mut().enumerate() {
            let ch = char::from_u32(i as u32).unwrap_or('\0');
            *slot = face
                .glyph_index(ch)
                .and_then(|gid| face.glyph_hor_advance(gid))
                .unwrap_or(0);
        }

        // The embedded Helvetica subset is missing the glyph for
        // U+0020 (space) — `face.glyph_index(' ')` returns None. PDF
        // viewers render built-in fonts using the Adobe Type 1
        // metrics (Helvetica space = 278/1000 em), so our wrapping
        // needs the same value or every space causes the measured
        // x-position to drift relative to the actual rendered
        // position. Backfill from a hardcoded AFM table, scaled to
        // the subset's units_per_em.
        backfill_afm_widths(variant, units_per_em, &mut widths);

        // Compute the average advance for missing-codepoint fallback.
        let (sum, count) = widths.iter().fold((0u64, 0u64), |(s, c), w| {
            if *w > 0 {
                (s + *w as u64, c + 1)
            } else {
                (s, c)
            }
        });
        let fallback_width = if count > 0 {
            (sum / count) as u16
        } else {
            500
        };

        VariantMetrics {
            units_per_em,
            unscaled_widths: widths,
            fallback_width,
        }
    }

    /// Advance width of `text` at `font_size_pt`, in points.
    #[allow(dead_code)]
    pub fn units_per_em(&self) -> u16 {
        self.units_per_em
    }

    /// Advance width of `text` at `font_size_pt`, in points.
    pub fn measure(&self, text: &str, font_size_pt: f32) -> f32 {
        let mut unscaled: u64 = 0;
        for c in text.chars() {
            let w = if (c as u32) < 256 {
                self.unscaled_widths[c as usize]
            } else {
                0
            };
            let w = if w == 0 { self.fallback_width } else { w };
            unscaled += w as u64;
        }
        unscaled as f32 * font_size_pt / self.units_per_em as f32
    }
}

/// Cache of [`VariantMetrics`] for every built-in variant the
/// renderer can pick. Built once per render call. The 8 variants
/// combined are a few KiB.
pub struct FontMetricsCache {
    helvetica_regular: VariantMetrics,
    helvetica_bold: VariantMetrics,
    helvetica_italic: VariantMetrics,
    helvetica_bold_italic: VariantMetrics,
    courier_regular: VariantMetrics,
    courier_bold: VariantMetrics,
    courier_italic: VariantMetrics,
    courier_bold_italic: VariantMetrics,
}

impl FontMetricsCache {
    pub fn new() -> Self {
        Self {
            helvetica_regular: VariantMetrics::load(FontVariant::HelveticaRegular),
            helvetica_bold: VariantMetrics::load(FontVariant::HelveticaBold),
            helvetica_italic: VariantMetrics::load(FontVariant::HelveticaItalic),
            helvetica_bold_italic: VariantMetrics::load(FontVariant::HelveticaBoldItalic),
            courier_regular: VariantMetrics::load(FontVariant::CourierRegular),
            courier_bold: VariantMetrics::load(FontVariant::CourierBold),
            courier_italic: VariantMetrics::load(FontVariant::CourierItalic),
            courier_bold_italic: VariantMetrics::load(FontVariant::CourierBoldItalic),
        }
    }

    pub fn for_variant(&self, v: FontVariant) -> &VariantMetrics {
        match v {
            FontVariant::HelveticaRegular => &self.helvetica_regular,
            FontVariant::HelveticaBold => &self.helvetica_bold,
            FontVariant::HelveticaItalic => &self.helvetica_italic,
            FontVariant::HelveticaBoldItalic => &self.helvetica_bold_italic,
            FontVariant::CourierRegular => &self.courier_regular,
            FontVariant::CourierBold => &self.courier_bold,
            FontVariant::CourierItalic => &self.courier_italic,
            FontVariant::CourierBoldItalic => &self.courier_bold_italic,
        }
    }
}

/// One user-supplied external font, registered with the PDF document.
///
/// Holds the printpdf [`FontId`] for emission plus a glyph-width
/// table for measurement. The font is the same one whether the run
/// has bold / italic flags or not — synthetic weights aren't faked
/// today, so bold / italic flags only affect text *color* (when
/// linked) but not the visual weight when an external font is used.
/// Per-weight external variants are a phase-8 follow-up.
pub struct ExternalFont {
    pub font_id: FontId,
    units_per_em: u16,
    /// codepoint -> glyph advance width in `units_per_em`.
    advance_by_codepoint: BTreeMap<u32, u16>,
    /// Average glyph width, used as fallback for unmapped codepoints.
    fallback_advance: u16,
}

impl ExternalFont {
    /// Measure the advance of `text` at `font_size_pt`.
    pub fn measure(&self, text: &str, font_size_pt: f32) -> f32 {
        let mut unscaled: u64 = 0;
        for c in text.chars() {
            let w = self
                .advance_by_codepoint
                .get(&(c as u32))
                .copied()
                .unwrap_or(self.fallback_advance);
            unscaled += w as u64;
        }
        unscaled as f32 * font_size_pt / self.units_per_em as f32
    }
}

/// The complete font set for one render call: built-ins always
/// available, plus optional external default-body and code fonts.
///
/// Each external family has up to four weight slots; `regular` is
/// the anchor (loaded from whatever path the user pointed at), and
/// the others are discovered by searching sibling files in the
/// same directory (`Georgia.ttf` -> `Georgia Bold.ttf`,
/// `Georgia Italic.ttf`, `Georgia Bold Italic.ttf`). Missing slots
/// fall back to `regular` at resolve time.
pub struct FontSet {
    pub builtin: FontMetricsCache,
    pub external_body: ExternalFamily,
    pub external_code: ExternalFamily,
}

/// Up to four weight slots for an external font family.
#[derive(Default)]
pub struct ExternalFamily {
    pub regular: Option<ExternalFont>,
    pub bold: Option<ExternalFont>,
    pub italic: Option<ExternalFont>,
    pub bold_italic: Option<ExternalFont>,
}

impl ExternalFamily {
    /// Best match for the given flags. Falls back through
    /// bold_italic -> bold -> italic -> regular as variants are
    /// missing.
    pub fn pick(&self, flags: RunFlags) -> Option<&ExternalFont> {
        match (flags.bold, flags.italic) {
            (true, true) => self
                .bold_italic
                .as_ref()
                .or(self.bold.as_ref())
                .or(self.italic.as_ref())
                .or(self.regular.as_ref()),
            (true, false) => self.bold.as_ref().or(self.regular.as_ref()),
            (false, true) => self.italic.as_ref().or(self.regular.as_ref()),
            (false, false) => self.regular.as_ref(),
        }
    }

    /// Any external slot is filled — used to decide whether to take
    /// the external path at all.
    pub fn is_loaded(&self) -> bool {
        self.regular.is_some()
            || self.bold.is_some()
            || self.italic.is_some()
            || self.bold_italic.is_some()
    }
}

/// How a variant resolves at emit time.
pub enum FontResolution<'a> {
    /// Use a built-in PDF font. Text must pass through
    /// `to_win1252` transliteration before reaching `Op::ShowText`.
    Builtin {
        handle: PdfFontHandle,
        metrics: &'a VariantMetrics,
    },
    /// Use a user-supplied external TTF. `Op::ShowText` accepts
    /// full Unicode; printpdf does codepoint -> glyph lookup
    /// using the registered [`ParsedFont`].
    External {
        handle: PdfFontHandle,
        font: &'a ExternalFont,
    },
}

impl FontSet {
    /// Build the font set for a render call.
    ///
    /// `used_codepoints` should be every distinct character that
    /// appears in the document. `usage` tells us which weight
    /// variants are actually referenced so we don't embed
    /// bold/italic/bold-italic faces that the document never asks
    /// for. Regular is always loaded; the optional weights are
    /// loaded only when `usage` flags them.
    pub fn load(
        font_config: Option<&FontConfig>,
        used_codepoints: &[char],
        usage: VariantUsage,
        doc: &mut PdfDocument,
    ) -> Self {
        let builtin = FontMetricsCache::new();
        let body_variants = BodyVariantNeed {
            bold: usage.body_bold || usage.body_bold_italic,
            italic: usage.body_italic || usage.body_bold_italic,
            bold_italic: usage.body_bold_italic,
        };
        let code_variants = BodyVariantNeed {
            bold: usage.mono_bold || usage.mono_bold_italic,
            italic: usage.mono_italic || usage.mono_bold_italic,
            bold_italic: usage.mono_bold_italic,
        };
        let external_body = font_config
            .and_then(|c| load_external_family(default_source(c), used_codepoints, body_variants, doc))
            .unwrap_or_default();
        // If the user picked an external body font but didn't specify
        // a code font, try a sensible system monospace fallback. Mixing
        // an external Unicode body font with the built-in Type 1 Courier
        // for inline code makes the inline-code space glyph ~2× wider
        // than the surrounding body spaces (Courier 600/1000 em vs e.g.
        // Georgia ~280/1000 em), which shows up as a visible gap and a
        // jumpy baseline at every font transition.
        let user_code_src = font_config.and_then(code_source);
        let code_src = match user_code_src {
            Some(src) => Some(src),
            None if external_body.is_loaded() => default_monospace_source(),
            None => None,
        };
        let external_code = load_external_family(code_src, used_codepoints, code_variants, doc)
            .unwrap_or_default();
        Self {
            builtin,
            external_body,
            external_code,
        }
    }

    /// Resolve a [`RunFlags`] to a concrete font choice.
    pub fn resolve(&self, flags: RunFlags) -> FontResolution<'_> {
        if flags.monospace {
            if let Some(ext) = self.external_code.pick(flags) {
                return FontResolution::External {
                    handle: PdfFontHandle::External(ext.font_id.clone()),
                    font: ext,
                };
            }
        } else if let Some(ext) = self.external_body.pick(flags) {
            return FontResolution::External {
                handle: PdfFontHandle::External(ext.font_id.clone()),
                font: ext,
            };
        }
        let variant = FontVariant::for_flags(flags);
        FontResolution::Builtin {
            handle: PdfFontHandle::Builtin(variant.builtin()),
            metrics: self.builtin.for_variant(variant),
        }
    }

    pub fn measure(&self, flags: RunFlags, text: &str, size_pt: f32) -> f32 {
        match self.resolve(flags) {
            FontResolution::Builtin { metrics, .. } => metrics.measure(text, size_pt),
            FontResolution::External { font, .. } => font.measure(text, size_pt),
        }
    }

    pub fn handle(&self, flags: RunFlags) -> PdfFontHandle {
        match self.resolve(flags) {
            FontResolution::Builtin { handle, .. } | FontResolution::External { handle, .. } => {
                handle
            }
        }
    }

    /// `true` if text emitted via this variant has to pass through
    /// the `to_win1252` ASCII transliterator (because the built-in
    /// font path can't survive non-ASCII bytes).
    pub fn needs_transliteration(&self, flags: RunFlags) -> bool {
        matches!(self.resolve(flags), FontResolution::Builtin { .. })
    }
}

fn default_source(c: &FontConfig) -> Option<FontSource> {
    if let Some(src) = c.default_font_source.clone() {
        return Some(src);
    }
    c.default_font.as_deref().map(name_to_external_source)
}

fn code_source(c: &FontConfig) -> Option<FontSource> {
    if let Some(src) = c.code_font_source.clone() {
        return Some(src);
    }
    c.code_font.as_deref().map(name_to_external_source)
}

/// Walk a per-OS list of likely-installed system monospace fonts and
/// return the first one we can locate. Used when an external body font
/// is configured but the user didn't specify a code font — keeps both
/// paths on the same external Unicode renderer so inline code shares a
/// baseline with surrounding body text.
fn default_monospace_source() -> Option<FontSource> {
    #[cfg(target_os = "macos")]
    const CANDIDATES: &[&str] = &["Menlo", "Monaco", "Courier New"];
    #[cfg(target_os = "windows")]
    const CANDIDATES: &[&str] = &["Consolas", "Cascadia Code", "Courier New", "Lucida Console"];
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    const CANDIDATES: &[&str] = &[
        "DejaVu Sans Mono",
        "Liberation Mono",
        "Noto Sans Mono",
        "Ubuntu Mono",
    ];
    for name in CANDIDATES {
        if find_system_font(name).is_some() {
            return Some(FontSource::System((*name).to_string()));
        }
    }
    None
}

/// Resolve a user-supplied font name to a source the external
/// loader can consume.
///
/// `crate::fonts::resolve_font_source` maps friendly names like
/// "Arial" -> `Builtin("Helvetica")` because at the type-1 level
/// they're interchangeable — but the built-in path is ASCII-only,
/// so honoring that alias defeats Unicode rendering. Here we bias
/// toward a real system font lookup: path-like names go straight
/// to `File`, everything else goes to `System`. Falling back to a
/// built-in still happens, but only when the system lookup fails.
fn name_to_external_source(name: &str) -> FontSource {
    if name.contains('/')
        || name.contains('\\')
        || name.ends_with(".ttf")
        || name.ends_with(".otf")
    {
        return FontSource::File(name.into());
    }
    FontSource::System(name.to_string())
}

/// Resolve a `FontSource` to a regular-weight path (if any) and the
/// font bytes. The path is what we use for sibling-variant discovery.
fn resolve_regular(source: FontSource) -> Option<(Option<PathBuf>, Vec<u8>)> {
    match source {
        FontSource::Builtin(_) => None,
        FontSource::Bytes(b) => Some((None, b.to_vec())),
        FontSource::File(path) => {
            let bytes = read_font_file(&path)?;
            Some((Some(path), bytes))
        }
        FontSource::System(name) => {
            let path = find_system_font(&name).or_else(|| {
                log::warn!("could not locate system font {:?}", name);
                None
            })?;
            let bytes = read_font_file(&path)?;
            Some((Some(path), bytes))
        }
    }
}

/// Which weight variants the family loader should bother searching
/// for and embedding. Regular is always loaded if the family loads
/// at all; the optional weights are gated by document usage so we
/// don't embed (typically ~25 KB per variant after subsetting) for
/// weights the document never references.
#[derive(Debug, Clone, Copy, Default)]
pub struct BodyVariantNeed {
    pub bold: bool,
    pub italic: bool,
    pub bold_italic: bool,
}

/// Load the regular weight plus the discoverable variants that the
/// document actually uses. Returns `None` only if even the regular
/// weight failed to load.
fn load_external_family(
    source: Option<FontSource>,
    used_codepoints: &[char],
    need: BodyVariantNeed,
    doc: &mut PdfDocument,
) -> Option<ExternalFamily> {
    let source = source?;
    let (anchor_path, regular_bytes) = resolve_regular(source)?;
    let regular = parse_and_register(regular_bytes, "regular", used_codepoints, doc)?;

    let mut family = ExternalFamily {
        regular: Some(regular),
        ..ExternalFamily::default()
    };

    if let Some(path) = anchor_path {
        let candidates: &[(VariantKind, &[&str], bool)] = &[
            (VariantKind::Bold, &["Bold"], need.bold),
            (VariantKind::Italic, &["Italic", "Oblique"], need.italic),
            (
                VariantKind::BoldItalic,
                &["Bold Italic", "BoldItalic", "Bold-Italic", "BoldOblique"],
                need.bold_italic,
            ),
        ];
        for (kind, names, wanted) in candidates {
            if !wanted {
                continue;
            }
            if let Some(variant_path) = find_variant_path(&path, names) {
                if let Some(bytes) = read_font_file(&variant_path) {
                    if let Some(parsed) =
                        parse_and_register(bytes, kind.label(), used_codepoints, doc)
                    {
                        match kind {
                            VariantKind::Bold => family.bold = Some(parsed),
                            VariantKind::Italic => family.italic = Some(parsed),
                            VariantKind::BoldItalic => family.bold_italic = Some(parsed),
                        }
                    }
                }
            }
        }
    }

    if family.is_loaded() { Some(family) } else { None }
}

#[derive(Clone, Copy)]
enum VariantKind {
    Bold,
    Italic,
    BoldItalic,
}

impl VariantKind {
    fn label(self) -> &'static str {
        match self {
            VariantKind::Bold => "bold",
            VariantKind::Italic => "italic",
            VariantKind::BoldItalic => "bold-italic",
        }
    }
}

/// Given the regular-weight font's path, return a sibling file
/// matching one of the variant name patterns
/// (`Foo Bold.ttf`, `Foo-Bold.ttf`, `FooBold.ttf`, plus `.otf`).
fn find_variant_path(anchor: &std::path::Path, variant_names: &[&str]) -> Option<PathBuf> {
    let parent = anchor.parent()?;
    let stem = anchor.file_stem()?.to_string_lossy().to_string();
    for variant in variant_names {
        for sep in [" ", "-", ""] {
            for ext in ["ttf", "otf"] {
                let candidate = parent.join(format!("{}{}{}.{}", stem, sep, variant, ext));
                if candidate.exists() {
                    return Some(candidate);
                }
            }
        }
    }
    None
}

/// Code points the renderer might synthesize at layout time even if
/// they never appear in the source document — bullet glyphs,
/// task-list brackets, ordered-list digits, etc. Including them in
/// the subset prevents `.notdef` boxes from showing where the layout
/// pass inserts them.
const RENDERER_INJECTED_CHARS: &[char] = &[
    '\u{2022}', // bullet •
    '[', ']', 'x', ' ', '.',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    '(', ')', ':', '-',
];

fn parse_and_register(
    bytes: Vec<u8>,
    label: &str,
    used_codepoints: &[char],
    doc: &mut PdfDocument,
) -> Option<ExternalFont> {
    let face = match Face::parse(&bytes, 0) {
        Ok(f) => f,
        Err(e) => {
            log::warn!("could not parse {} font face: {}", label, e);
            return None;
        }
    };
    let units_per_em = face.units_per_em();
    // Union of document codepoints + renderer-injected glyphs.
    // Deliberately *not* the whole BMP — keeping the keep-set small
    // is what makes the subset small.
    let mut codepoints: Vec<char> = used_codepoints.to_vec();
    codepoints.extend_from_slice(RENDERER_INJECTED_CHARS);
    codepoints.sort();
    codepoints.dedup();
    let used_codepoints = &codepoints[..];
    // Collect the original (pre-subset) glyph IDs we need along with
    // their advance widths in font units.
    let mut codepoint_to_orig_gid: BTreeMap<u32, u16> = BTreeMap::new();
    let mut orig_gid_advance: BTreeMap<u16, u16> = BTreeMap::new();
    for &ch in used_codepoints {
        let cp = ch as u32;
        if let Some(gid) = face.glyph_index(ch) {
            if let Some(w) = face.glyph_hor_advance(gid) {
                codepoint_to_orig_gid.insert(cp, gid.0);
                orig_gid_advance.insert(gid.0, w);
            }
        }
    }

    // Subset the font down to just those glyphs. `.notdef` (gid 0)
    // is included implicitly by the remapper, plus whatever the
    // subsetter pulls in for composite glyph dependencies and
    // required tables. If subsetting fails for any reason (CFF2
    // font, malformed font, etc.) we degrade gracefully to the full
    // font with original GIDs.
    let orig_gids: Vec<u16> = orig_gid_advance.keys().copied().collect();
    let remapper = subsetter::GlyphRemapper::new_from_glyphs_sorted(&orig_gids);
    let (subset_bytes, gid_remap): (Vec<u8>, Box<dyn Fn(u16) -> u16>) =
        match subsetter::subset(&bytes, 0, &remapper) {
            Ok(b) => (
                b,
                Box::new(move |old| remapper.get(old).unwrap_or(0)),
            ),
            Err(e) => {
                log::warn!(
                    "could not subset {} font: {:?}; embedding full font instead",
                    label,
                    e
                );
                (bytes.clone(), Box::new(|old| old))
            }
        };

    // Rebuild codepoint -> glyph and glyph -> width maps using the
    // *new* (post-subset) GIDs. printpdf looks up codepoints in
    // `codepoint_to_glyph` and emits those GIDs as the PDF byte
    // stream — they have to match the subset font's glyph table.
    let mut advance_by_codepoint: BTreeMap<u32, u16> = BTreeMap::new();
    let mut codepoint_to_glyph: BTreeMap<u32, u16> = BTreeMap::new();
    let mut glyph_widths: BTreeMap<u16, u16> = BTreeMap::new();
    let mut sum: u64 = 0;
    let mut count: u64 = 0;
    for (cp, orig_gid) in &codepoint_to_orig_gid {
        let new_gid = gid_remap(*orig_gid);
        let w = orig_gid_advance.get(orig_gid).copied().unwrap_or(0);
        codepoint_to_glyph.insert(*cp, new_gid);
        glyph_widths.insert(new_gid, w);
        advance_by_codepoint.insert(*cp, w);
        if w > 0 {
            sum += w as u64;
            count += 1;
        }
    }
    let fallback_advance = if count > 0 {
        (sum / count) as u16
    } else {
        units_per_em / 2
    };

    // PDF spec (PDF 32000-1:2008 §9.8) requires /Ascent and /Descent
    // in glyph space normalized to 1000 units per em. printpdf 0.9
    // writes the FontMetrics values straight into the FontDescriptor,
    // so we have to pre-normalize here. Passing raw font units (1878
    // for Georgia at UPEM=2048) makes viewers compute selection
    // bounding boxes ~2× too tall, causing adjacent-line selection
    // rectangles to overlap.
    let ascent = normalize_to_1000_em(face.ascender(), units_per_em);
    let descent = normalize_to_1000_em(face.descender(), units_per_em);

    let parsed = printpdf::ParsedFont::with_glyph_data(
        subset_bytes,
        0,
        None,
        codepoint_to_glyph,
        glyph_widths,
        units_per_em,
        printpdf::FontMetrics { ascent, descent },
    );
    let font_id = doc.add_font(&parsed);

    Some(ExternalFont {
        font_id,
        units_per_em,
        advance_by_codepoint,
        fallback_advance,
    })
}

/// Rescale a metric expressed in font units into PDF's `/1000-em`
/// glyph space. Font-agnostic: works for any `units_per_em` from
/// 1 to 65535. The guard against zero avoids divide-by-zero on
/// pathologically malformed fonts.
fn normalize_to_1000_em(value: i16, units_per_em: u16) -> i16 {
    let upem = i32::from(units_per_em).max(1);
    let scaled = i32::from(value) * 1000 / upem;
    scaled.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
}

fn read_font_file(path: &std::path::Path) -> Option<Vec<u8>> {
    std::fs::read(path)
        .map_err(|e| log::warn!("could not read font {:?}: {}", path, e))
        .ok()
}

/// Fill in widths for code points that the embedded subset doesn't
/// provide. The values match Adobe's Standard 14 Type 1 metrics
/// (AFM) for the built-in PDF fonts, expressed per-1000-em and
/// scaled to the subset's actual `units_per_em` here.
///
/// Today only U+0020 (space) is missing across all variants. The
/// table is open to extension if other code points turn up missing
/// for the Times/Courier families.
fn backfill_afm_widths(variant: FontVariant, units_per_em: u16, widths: &mut [u16; 256]) {
    let space_per_1000 = match variant {
        FontVariant::HelveticaRegular
        | FontVariant::HelveticaBold
        | FontVariant::HelveticaItalic
        | FontVariant::HelveticaBoldItalic => 278u32,
        FontVariant::CourierRegular
        | FontVariant::CourierBold
        | FontVariant::CourierItalic
        | FontVariant::CourierBoldItalic => 600u32,
    };
    if widths[b' ' as usize] == 0 {
        let scaled = space_per_1000 * units_per_em as u32 / 1000;
        widths[b' ' as usize] = scaled.min(u16::MAX as u32) as u16;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn measures_helvetica_width_monotonic_in_text_length() {
        let cache = FontMetricsCache::new();
        let m = cache.for_variant(FontVariant::HelveticaRegular);
        let a = m.measure("a", 12.0);
        let aaa = m.measure("aaa", 12.0);
        assert!(aaa > a * 2.5);
        // Sanity: 'a' at 12pt is roughly 6 points wide in Helvetica.
        assert!(a > 1.0 && a < 12.0, "unexpected width: {}", a);
    }

    #[test]
    fn courier_is_monospace() {
        let cache = FontMetricsCache::new();
        let m = cache.for_variant(FontVariant::CourierRegular);
        let i = m.measure("i", 12.0);
        let w = m.measure("w", 12.0);
        assert!((i - w).abs() < 0.5, "courier should be monospace");
    }

    #[test]
    fn normalize_to_1000_em_is_font_agnostic() {
        // Georgia: UPEM 2048, ascender 1878 → 916.
        assert_eq!(normalize_to_1000_em(1878, 2048), 916);
        assert_eq!(normalize_to_1000_em(-449, 2048), -219);
        // Many CFF / OTF fonts have UPEM 1000 — identity transform.
        assert_eq!(normalize_to_1000_em(800, 1000), 800);
        assert_eq!(normalize_to_1000_em(-200, 1000), -200);
        // Common TTF UPEM 1024.
        assert_eq!(normalize_to_1000_em(819, 1024), 799);
        // Apple-style high-precision UPEM 4096.
        assert_eq!(normalize_to_1000_em(3000, 4096), 732);
        // Zero UPEM is malformed; guard prevents divide-by-zero.
        assert_eq!(normalize_to_1000_em(1000, 0), i16::MAX);
        // i16-overflow inputs saturate rather than wrap.
        assert_eq!(normalize_to_1000_em(i16::MAX, 1), i16::MAX);
        assert_eq!(normalize_to_1000_em(i16::MIN, 1), i16::MIN);
    }

    #[test]
    fn default_monospace_source_resolves_on_supported_oses() {
        // We don't assert *which* font wins — the per-OS candidate
        // list is what guarantees Menlo/Monaco/Consolas/DejaVu Mono
        // is found. The contract is just: at least one is locatable
        // on a typical developer machine.
        let src = default_monospace_source();
        if cfg!(any(target_os = "macos", target_os = "windows")) {
            assert!(
                src.is_some(),
                "expected a system monospace fallback on macOS/Windows"
            );
        }
        // On Linux containers without any monospace font installed,
        // None is the correct answer (graceful degradation to the
        // built-in Courier path).
    }

    #[test]
    fn for_flags_routes_correctly() {
        assert!(matches!(
            FontVariant::for_flags(RunFlags::default()),
            FontVariant::HelveticaRegular
        ));
        assert!(matches!(
            FontVariant::for_flags(RunFlags::default().with_bold()),
            FontVariant::HelveticaBold
        ));
        assert!(matches!(
            FontVariant::for_flags(RunFlags::default().with_monospace().with_bold()),
            FontVariant::CourierBold
        ));
    }
}