forme-pdf 0.9.1

A page-native PDF rendering engine. Layout INTO pages, not onto an infinite canvas.
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
//! # Font Management
//!
//! Loading, parsing, and subsetting fonts for PDF embedding.
//!
//! For v1, we support the 14 standard PDF fonts (Helvetica, Times, Courier, etc.)
//! which don't require embedding. Custom font support via ttf-parser comes next.

pub mod builtin;
pub mod fallback;
pub mod metrics;
pub mod subset;

pub use metrics::{unicode_to_winansi, StandardFontMetrics};
use std::collections::HashMap;

/// A font registry that maps font family + weight + style to font data.
pub struct FontRegistry {
    fonts: HashMap<FontKey, FontData>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct FontKey {
    pub family: String,
    pub weight: u32,
    pub italic: bool,
}

#[derive(Debug, Clone)]
pub enum FontData {
    /// One of the 14 standard PDF fonts. No embedding needed.
    Standard(StandardFont),
    /// A TrueType/OpenType font that needs to be embedded.
    Custom {
        data: Vec<u8>,
        /// Glyph IDs that are actually used (for subsetting).
        used_glyphs: Vec<u16>,
        /// Parsed metrics from ttf-parser, if available.
        metrics: Option<CustomFontMetrics>,
    },
}

/// Parsed metrics from a TrueType/OpenType font via ttf-parser.
#[derive(Debug, Clone)]
pub struct CustomFontMetrics {
    pub units_per_em: u16,
    pub advance_widths: HashMap<char, u16>,
    pub default_advance: u16,
    pub ascender: i16,
    pub descender: i16,
    /// Maps characters to their glyph IDs in the original font.
    pub glyph_ids: HashMap<char, u16>,
}

impl CustomFontMetrics {
    /// Get the advance width of a character in points.
    pub fn char_width(&self, ch: char, font_size: f64) -> f64 {
        let w = self
            .advance_widths
            .get(&ch)
            .copied()
            .unwrap_or(self.default_advance);
        (w as f64 / self.units_per_em as f64) * font_size
    }

    /// Parse metrics from font data using ttf-parser.
    pub fn from_font_data(data: &[u8]) -> Option<Self> {
        let face = ttf_parser::Face::parse(data, 0).ok()?;
        let units_per_em = face.units_per_em();
        let ascender = face.ascender();
        let descender = face.descender();

        let mut advance_widths = HashMap::new();
        let mut glyph_ids = HashMap::new();
        let mut default_advance = 0u16;

        // Sample common characters to build width and glyph ID maps
        for code in 32u32..=0xFFFF {
            if let Some(ch) = char::from_u32(code) {
                if let Some(glyph_id) = face.glyph_index(ch) {
                    let advance = face.glyph_hor_advance(glyph_id).unwrap_or(0);
                    advance_widths.insert(ch, advance);
                    glyph_ids.insert(ch, glyph_id.0);
                    if ch == ' ' {
                        default_advance = advance;
                    }
                }
            }
        }

        if default_advance == 0 {
            default_advance = units_per_em / 2;
        }

        Some(CustomFontMetrics {
            units_per_em,
            advance_widths,
            default_advance,
            ascender,
            descender,
            glyph_ids,
        })
    }
}

/// The 14 standard PDF fonts.
#[derive(Debug, Clone, Copy)]
pub enum StandardFont {
    Helvetica,
    HelveticaBold,
    HelveticaOblique,
    HelveticaBoldOblique,
    TimesRoman,
    TimesBold,
    TimesItalic,
    TimesBoldItalic,
    Courier,
    CourierBold,
    CourierOblique,
    CourierBoldOblique,
    Symbol,
    ZapfDingbats,
}

impl FontData {
    /// Check whether this font has a glyph for the given character.
    pub fn has_char(&self, ch: char) -> bool {
        match self {
            FontData::Custom {
                metrics: Some(m), ..
            } => m.glyph_ids.contains_key(&ch),
            FontData::Custom { metrics: None, .. } => false,
            FontData::Standard(_) => {
                unicode_to_winansi(ch).is_some() || (ch as u32) >= 32 && (ch as u32) <= 255
            }
        }
    }
}

impl StandardFont {
    /// The PDF name for this font.
    pub fn pdf_name(&self) -> &'static str {
        match self {
            Self::Helvetica => "Helvetica",
            Self::HelveticaBold => "Helvetica-Bold",
            Self::HelveticaOblique => "Helvetica-Oblique",
            Self::HelveticaBoldOblique => "Helvetica-BoldOblique",
            Self::TimesRoman => "Times-Roman",
            Self::TimesBold => "Times-Bold",
            Self::TimesItalic => "Times-Italic",
            Self::TimesBoldItalic => "Times-BoldItalic",
            Self::Courier => "Courier",
            Self::CourierBold => "Courier-Bold",
            Self::CourierOblique => "Courier-Oblique",
            Self::CourierBoldOblique => "Courier-BoldOblique",
            Self::Symbol => "Symbol",
            Self::ZapfDingbats => "ZapfDingbats",
        }
    }
}

impl Default for FontRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl FontRegistry {
    pub fn new() -> Self {
        let mut fonts = HashMap::new();

        let standard_mappings = vec![
            (("Helvetica", 400, false), StandardFont::Helvetica),
            (("Helvetica", 700, false), StandardFont::HelveticaBold),
            (("Helvetica", 400, true), StandardFont::HelveticaOblique),
            (("Helvetica", 700, true), StandardFont::HelveticaBoldOblique),
            (("Times", 400, false), StandardFont::TimesRoman),
            (("Times", 700, false), StandardFont::TimesBold),
            (("Times", 400, true), StandardFont::TimesItalic),
            (("Times", 700, true), StandardFont::TimesBoldItalic),
            (("Courier", 400, false), StandardFont::Courier),
            (("Courier", 700, false), StandardFont::CourierBold),
            (("Courier", 400, true), StandardFont::CourierOblique),
            (("Courier", 700, true), StandardFont::CourierBoldOblique),
        ];

        for ((family, weight, italic), font) in standard_mappings {
            fonts.insert(
                FontKey {
                    family: family.to_string(),
                    weight,
                    italic,
                },
                FontData::Standard(font),
            );
        }

        let mut registry = Self { fonts };
        builtin::register_builtin_fonts(&mut registry);
        registry
    }

    /// Look up a font by family name (or comma-separated fallback chain),
    /// falling back to Helvetica if none match.
    ///
    /// Supports CSS-style font family lists: `"Inter, Helvetica"` tries Inter
    /// first, then Helvetica. Quoted families are unquoted automatically.
    pub fn resolve(&self, families: &str, weight: u32, italic: bool) -> &FontData {
        let snapped_weight = if weight >= 600 { 700 } else { 400 };

        for family in families.split(',') {
            let family = family.trim().trim_matches('"').trim_matches('\'');
            if family.is_empty() {
                continue;
            }

            // Try exact weight
            let key = FontKey {
                family: family.to_string(),
                weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                return font;
            }

            // Try with normalized weight (snap to 400 or 700)
            let key = FontKey {
                family: family.to_string(),
                weight: snapped_weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                return font;
            }

            // Try opposite weight (400 if bold requested, 700 if regular requested)
            let opposite_weight = if snapped_weight == 700 { 400 } else { 700 };
            let key = FontKey {
                family: family.to_string(),
                weight: opposite_weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                return font;
            }
        }

        // Final fallback: Helvetica
        let key = FontKey {
            family: "Helvetica".to_string(),
            weight: snapped_weight,
            italic,
        };
        self.fonts.get(&key).unwrap_or_else(|| {
            self.fonts
                .get(&FontKey {
                    family: "Helvetica".to_string(),
                    weight: 400,
                    italic: false,
                })
                .expect("Helvetica must be registered")
        })
    }

    /// Resolve a font for a specific character from a comma-separated fallback chain.
    ///
    /// Walks the families in order, returning the first font that has a glyph for `ch`.
    /// Falls back to Helvetica if no font covers the character.
    /// Returns a tuple of (font_data, resolved_single_family_name).
    pub fn resolve_for_char(
        &self,
        families: &str,
        ch: char,
        weight: u32,
        italic: bool,
    ) -> (&FontData, String) {
        let snapped_weight = if weight >= 600 { 700 } else { 400 };

        for family in families.split(',') {
            let family = family.trim().trim_matches('"').trim_matches('\'');
            if family.is_empty() {
                continue;
            }

            // Try exact weight
            let key = FontKey {
                family: family.to_string(),
                weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                if font.has_char(ch) {
                    return (font, family.to_string());
                }
            }

            // Try with normalized weight
            let key = FontKey {
                family: family.to_string(),
                weight: snapped_weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                if font.has_char(ch) {
                    return (font, family.to_string());
                }
            }

            // Try opposite weight (400 if bold requested, 700 if regular requested)
            let opposite_weight = if snapped_weight == 700 { 400 } else { 700 };
            let key = FontKey {
                family: family.to_string(),
                weight: opposite_weight,
                italic,
            };
            if let Some(font) = self.fonts.get(&key) {
                if font.has_char(ch) {
                    return (font, family.to_string());
                }
            }
        }

        // Try builtin Unicode font (Noto Sans) before Helvetica
        let builtin_key = FontKey {
            family: "Noto Sans".to_string(),
            weight: snapped_weight,
            italic: false,
        };
        if let Some(font) = self.fonts.get(&builtin_key) {
            if font.has_char(ch) {
                return (font, "Noto Sans".to_string());
            }
        }

        // Final fallback: Helvetica
        let key = FontKey {
            family: "Helvetica".to_string(),
            weight: snapped_weight,
            italic,
        };
        let font = self.fonts.get(&key).unwrap_or_else(|| {
            self.fonts
                .get(&FontKey {
                    family: "Helvetica".to_string(),
                    weight: 400,
                    italic: false,
                })
                .expect("Helvetica must be registered")
        });
        (font, "Helvetica".to_string())
    }

    /// Register a custom font.
    pub fn register(&mut self, family: &str, weight: u32, italic: bool, data: Vec<u8>) {
        let metrics = CustomFontMetrics::from_font_data(&data);
        self.fonts.insert(
            FontKey {
                family: family.to_string(),
                weight,
                italic,
            },
            FontData::Custom {
                data,
                used_glyphs: Vec::new(),
                metrics,
            },
        );
    }

    /// Iterate over all registered fonts.
    pub fn iter(&self) -> impl Iterator<Item = (&FontKey, &FontData)> {
        self.fonts.iter()
    }
}

/// Shared font context used by layout and PDF serialization.
/// Provides text measurement with real glyph metrics.
pub struct FontContext {
    registry: FontRegistry,
    /// Number of digits to use when measuring page number sentinel width.
    /// Default 2 ("00"). Updated by the two-pass render loop after the
    /// first layout reveals the actual page count.
    sentinel_digit_count: u32,
}

impl Default for FontContext {
    fn default() -> Self {
        Self::new()
    }
}

impl FontContext {
    pub fn new() -> Self {
        Self {
            registry: FontRegistry::new(),
            sentinel_digit_count: 2,
        }
    }

    /// Get the current sentinel digit count.
    pub fn sentinel_digit_count(&self) -> u32 {
        self.sentinel_digit_count
    }

    /// Set the number of digits used to measure page number sentinel width.
    pub fn set_sentinel_digit_count(&mut self, count: u32) {
        self.sentinel_digit_count = count;
    }

    /// Get the advance width of a single character in points.
    ///
    /// When `family` contains a comma (font fallback chain), resolves the
    /// best font for this specific character before measuring.
    pub fn char_width(
        &self,
        ch: char,
        family: &str,
        weight: u32,
        italic: bool,
        font_size: f64,
    ) -> f64 {
        // Page placeholder sentinels: measure as the width of N zeros
        // where N = sentinel_digit_count (set by the two-pass render loop)
        if ch == crate::layout::PAGE_NUMBER_SENTINEL || ch == crate::layout::TOTAL_PAGES_SENTINEL {
            return self.char_width('0', family, weight, italic, font_size)
                * self.sentinel_digit_count as f64;
        }

        // Fast path: single font family — try primary font first,
        // fall back to per-char resolution only when the char isn't covered
        let font_data = if !family.contains(',') {
            let primary = self.registry.resolve(family, weight, italic);
            if ch.is_whitespace() || primary.has_char(ch) {
                primary
            } else {
                let (data, _) = self.registry.resolve_for_char(family, ch, weight, italic);
                data
            }
        } else {
            let (data, _) = self.registry.resolve_for_char(family, ch, weight, italic);
            data
        };
        match font_data {
            FontData::Standard(std_font) => std_font.metrics().char_width(ch, font_size),
            FontData::Custom {
                metrics: Some(m), ..
            } => m.char_width(ch, font_size),
            FontData::Custom { metrics: None, .. } => {
                StandardFont::Helvetica.metrics().char_width(ch, font_size)
            }
        }
    }

    /// Measure the width of a string in points.
    pub fn measure_string(
        &self,
        text: &str,
        family: &str,
        weight: u32,
        italic: bool,
        font_size: f64,
        letter_spacing: f64,
    ) -> f64 {
        let mut width = 0.0;
        for ch in text.chars() {
            width += self.char_width(ch, family, weight, italic, font_size) + letter_spacing;
        }
        width
    }

    /// Resolve a font key to its font data.
    pub fn resolve(&self, family: &str, weight: u32, italic: bool) -> &FontData {
        self.registry.resolve(family, weight, italic)
    }

    /// Access the underlying font registry.
    pub fn registry(&self) -> &FontRegistry {
        &self.registry
    }

    /// Access the underlying font registry mutably.
    pub fn registry_mut(&mut self) -> &mut FontRegistry {
        &mut self.registry
    }

    /// Get the raw font data bytes for a custom font.
    /// Returns `None` for standard fonts or if the font isn't found.
    pub fn font_data(&self, family: &str, weight: u32, italic: bool) -> Option<&[u8]> {
        let font_data = self.registry.resolve(family, weight, italic);
        match font_data {
            FontData::Custom { data, .. } => Some(data),
            FontData::Standard(_) => None,
        }
    }

    /// Get the units-per-em for a font. Returns 1000 for standard fonts.
    pub fn units_per_em(&self, family: &str, weight: u32, italic: bool) -> u16 {
        let font_data = self.registry.resolve(family, weight, italic);
        match font_data {
            FontData::Custom {
                metrics: Some(m), ..
            } => m.units_per_em,
            FontData::Custom { metrics: None, .. } => 1000,
            FontData::Standard(_) => 1000,
        }
    }
}

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

    #[test]
    fn test_font_context_helvetica() {
        let ctx = FontContext::new();
        let w = ctx.char_width(' ', "Helvetica", 400, false, 12.0);
        assert!((w - 3.336).abs() < 0.001);
    }

    #[test]
    fn test_font_context_bold_wider() {
        let ctx = FontContext::new();
        let regular = ctx.char_width('A', "Helvetica", 400, false, 12.0);
        let bold = ctx.char_width('A', "Helvetica", 700, false, 12.0);
        assert!(bold > regular, "Bold A should be wider than regular A");
    }

    #[test]
    fn test_font_context_measure_string() {
        let ctx = FontContext::new();
        let w = ctx.measure_string("Hello", "Helvetica", 400, false, 12.0, 0.0);
        assert!(w > 0.0);
    }

    #[test]
    fn test_font_context_fallback() {
        let ctx = FontContext::new();
        let w1 = ctx.char_width('A', "Helvetica", 400, false, 12.0);
        let w2 = ctx.char_width('A', "UnknownFont", 400, false, 12.0);
        assert!((w1 - w2).abs() < 0.001);
    }

    #[test]
    fn test_font_context_weight_resolution() {
        let ctx = FontContext::new();
        let w700 = ctx.char_width('A', "Helvetica", 700, false, 12.0);
        let w800 = ctx.char_width('A', "Helvetica", 800, false, 12.0);
        assert!((w700 - w800).abs() < 0.001);
    }

    #[test]
    fn test_font_fallback_chain_first_match() {
        let ctx = FontContext::new();
        let w1 = ctx.char_width('A', "Times", 400, false, 12.0);
        let w2 = ctx.char_width('A', "Times, Helvetica", 400, false, 12.0);
        assert!((w1 - w2).abs() < 0.001, "Should use Times (first in chain)");
    }

    #[test]
    fn test_font_fallback_chain_second_match() {
        let ctx = FontContext::new();
        let w1 = ctx.char_width('A', "Helvetica", 400, false, 12.0);
        let w2 = ctx.char_width('A', "Missing, Helvetica", 400, false, 12.0);
        assert!((w1 - w2).abs() < 0.001, "Should fall back to Helvetica");
    }

    #[test]
    fn test_font_fallback_chain_all_missing() {
        let ctx = FontContext::new();
        // When all specified families are missing, resolve_for_char tries
        // builtin Noto Sans first, then Helvetica. 'A' is in Noto Sans,
        // so we get Noto Sans metrics (not Helvetica).
        let w = ctx.char_width('A', "Missing, AlsoMissing", 400, false, 12.0);
        assert!(w > 0.0, "Should still produce a valid width from fallback");
    }

    #[test]
    fn test_font_fallback_chain_quoted_families() {
        let ctx = FontContext::new();
        let w1 = ctx.char_width('A', "Times", 400, false, 12.0);
        let w2 = ctx.char_width('A', "'Times', \"Helvetica\"", 400, false, 12.0);
        assert!((w1 - w2).abs() < 0.001, "Should strip quotes and use Times");
    }

    #[test]
    fn test_builtin_noto_sans_registered() {
        let registry = FontRegistry::new();
        let font = registry.resolve("Noto Sans", 400, false);
        assert!(
            matches!(font, FontData::Custom { .. }),
            "Noto Sans should be registered as a custom font"
        );
        assert!(
            font.has_char('\u{041F}'),
            "Noto Sans should have Cyrillic П"
        );
        assert!(font.has_char('\u{03B1}'), "Noto Sans should have Greek α");
    }

    #[test]
    fn test_builtin_noto_sans_fallback_for_cyrillic() {
        let registry = FontRegistry::new();
        let (font, family) = registry.resolve_for_char("Helvetica", '\u{041F}', 400, false);
        assert_eq!(
            family, "Noto Sans",
            "Cyrillic should fall back to Noto Sans"
        );
        assert!(matches!(font, FontData::Custom { .. }));
    }

    #[test]
    fn test_font_fallback_single_family_unchanged() {
        let ctx = FontContext::new();
        let w1 = ctx.char_width('A', "Courier", 400, false, 12.0);
        let w2 = ctx.char_width('A', "Courier", 400, false, 12.0);
        assert!(
            (w1 - w2).abs() < 0.001,
            "Single family should work as before"
        );
    }
}