pdf-interpret 0.5.7

A crate for interpreting PDF files.
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
use crate::FontResolverFn;
use crate::font::blob::{CffFontBlob, OpenTypeFontBlob};
use crate::font::generated::{glyph_names, metrics, standard, symbol, zapf_dings};
use crate::font::true_type::{Width, read_encoding, read_widths};
use crate::font::{
    Encoding, FontData, FontQuery, glyph_name_to_unicode, normalized_glyph_name, stretch_glyph,
    strip_subset_prefix,
};
use kurbo::BezPath;
use pdf_syntax::object::Dict;
use pdf_syntax::object::Name;
use pdf_syntax::object::dict::keys::{
    BASE_FONT, FONT_DESC, FONT_FAMILY, FONT_WEIGHT, ITALIC_ANGLE, MISSING_WIDTH,
};
use skrifa::raw::TableProvider;
use skrifa::{GlyphId, GlyphId16};
use std::cell::RefCell;
use std::collections::HashMap;

/// The 14 standard fonts of PDF.
#[derive(Copy, Clone, Debug)]
pub enum StandardFont {
    /// Helvetica.
    Helvetica,
    /// Helvetica Bold.
    HelveticaBold,
    /// Helvetica Oblique.
    HelveticaOblique,
    /// Helvetica Bold Oblique.
    HelveticaBoldOblique,
    /// Courier.
    Courier,
    /// Courier Bold.
    CourierBold,
    /// Courier Oblique.
    CourierOblique,
    /// Courier Bold Oblique.
    CourierBoldOblique,
    /// Times Roman.
    TimesRoman,
    /// Times Bold.
    TimesBold,
    /// Times Italic.
    TimesItalic,
    /// Times Bold Italic.
    TimesBoldItalic,
    /// Zapf Dingbats - a decorative symbol font.
    ZapfDingBats,
    /// Symbol - a mathematical symbol font.
    Symbol,
}

impl StandardFont {
    pub(crate) fn code_to_name(&self, code: u8) -> Option<&'static str> {
        match self {
            Self::Symbol => symbol::get(code),
            // Note that this font does not return postscript character names,
            // but instead has a custom encoding.
            Self::ZapfDingBats => zapf_dings::get(code),
            _ => standard::get(code),
        }
    }

    pub(crate) fn get_width(&self, mut name: &str) -> Option<f32> {
        // <https://github.com/apache/pdfbox/blob/129aafe26548c1ff935af9c55cb40a996186c35f/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDSimpleFont.java#L340>
        if name == ".notdef" {
            return Some(250.0);
        }

        name = normalized_glyph_name(name);

        match self {
            Self::Helvetica => metrics::HELVETICA.get(name).copied(),
            Self::HelveticaBold => metrics::HELVETICA_BOLD.get(name).copied(),
            Self::HelveticaOblique => metrics::HELVETICA_OBLIQUE.get(name).copied(),
            Self::HelveticaBoldOblique => metrics::HELVETICA_BOLD_OBLIQUE.get(name).copied(),
            Self::Courier => metrics::COURIER.get(name).copied(),
            Self::CourierBold => metrics::COURIER_BOLD.get(name).copied(),
            Self::CourierOblique => metrics::COURIER_OBLIQUE.get(name).copied(),
            Self::CourierBoldOblique => metrics::COURIER_BOLD_OBLIQUE.get(name).copied(),
            Self::TimesRoman => metrics::TIMES_ROMAN.get(name).copied(),
            Self::TimesBold => metrics::TIMES_BOLD.get(name).copied(),
            Self::TimesItalic => metrics::TIMES_ITALIC.get(name).copied(),
            Self::TimesBoldItalic => metrics::TIMES_BOLD_ITALIC.get(name).copied(),
            Self::ZapfDingBats => metrics::ZAPF_DING_BATS.get(name).copied(),
            Self::Symbol => metrics::SYMBOL.get(name).copied(),
        }
    }

    pub(crate) fn as_str(&self) -> &'static str {
        match self {
            Self::Helvetica => "Helvetica",
            Self::HelveticaBold => "Helvetica Bold",
            Self::HelveticaOblique => "Helvetica Oblique",
            Self::HelveticaBoldOblique => "Helvetica Bold Oblique",
            Self::Courier => "Courier",
            Self::CourierBold => "Courier Bold",
            Self::CourierOblique => "Courier Oblique",
            Self::CourierBoldOblique => "Courier Bold Oblique",
            Self::TimesRoman => "Times Roman",
            Self::TimesBold => "Times Bold",
            Self::TimesItalic => "Times Italic",
            Self::TimesBoldItalic => "Times Bold Italic",
            Self::ZapfDingBats => "Zapf Dingbats",
            Self::Symbol => "Symbol",
        }
    }

    /// Return the postscrit name of the font.
    pub fn postscript_name(&self) -> &'static str {
        match self {
            Self::Helvetica => "Helvetica",
            Self::HelveticaBold => "Helvetica-Bold",
            Self::HelveticaOblique => "Helvetica-Oblique",
            Self::HelveticaBoldOblique => "Helvetica-BoldOblique",
            Self::Courier => "Courier",
            Self::CourierBold => "Courier-Bold",
            Self::CourierOblique => "Courier-Oblique",
            Self::CourierBoldOblique => "Courier-BoldOblique",
            Self::TimesRoman => "Times-Roman",
            Self::TimesBold => "Times-Bold",
            Self::TimesItalic => "Times-Italic",
            Self::TimesBoldItalic => "Times-BoldItalic",
            Self::ZapfDingBats => "ZapfDingbats",
            Self::Symbol => "Symbol",
        }
    }

    pub(crate) fn is_bold(&self) -> bool {
        matches!(
            self,
            Self::HelveticaBold
                | Self::HelveticaBoldOblique
                | Self::CourierBold
                | Self::CourierBoldOblique
                | Self::TimesBold
                | Self::TimesBoldItalic
        )
    }

    pub(crate) fn is_italic(&self) -> bool {
        matches!(
            self,
            Self::HelveticaOblique
                | Self::HelveticaBoldOblique
                | Self::CourierOblique
                | Self::CourierBoldOblique
                | Self::TimesItalic
                | Self::TimesBoldItalic
        )
    }

    pub(crate) fn is_serif(&self) -> bool {
        matches!(
            self,
            Self::TimesRoman | Self::TimesBold | Self::TimesItalic | Self::TimesBoldItalic
        )
    }

    pub(crate) fn is_monospace(&self) -> bool {
        matches!(
            self,
            Self::Courier | Self::CourierBold | Self::CourierOblique | Self::CourierBoldOblique
        )
    }

    /// Canonical vertical font metrics for the PDF Standard-14 faces, in /1000
    /// em. Returns `(ascent, descent, cap_height, x_height)` where `ascent` is
    /// positive (above the baseline) and `descent` is negative (below it).
    ///
    /// Source: the Adobe Core-14 AFM files (`Ascender` / `Descender` /
    /// `CapHeight` / `XHeight` global keys; obliques share their upright face's
    /// vertical metrics). Symbol and ZapfDingbats declare no letterform metrics
    /// in their AFM, so `cap_height` / `x_height` are `None` and ascent/descent
    /// are taken from the AFM `FontBBox` vertical extents.
    ///
    /// Used only as a fallback when no embedded font binary provides skrifa
    /// metrics — embedded font metrics always take precedence.
    pub(crate) fn canonical_metrics(&self) -> Option<(f64, f64, Option<f64>, Option<f64>)> {
        match self {
            Self::Helvetica => Some((718.0, -207.0, Some(718.0), Some(523.0))),
            Self::HelveticaBold => Some((718.0, -207.0, Some(718.0), Some(532.0))),
            Self::HelveticaOblique => Some((718.0, -207.0, Some(718.0), Some(523.0))),
            Self::HelveticaBoldOblique => Some((718.0, -207.0, Some(718.0), Some(532.0))),
            Self::Courier => Some((629.0, -157.0, Some(562.0), Some(426.0))),
            Self::CourierBold => Some((629.0, -157.0, Some(562.0), Some(439.0))),
            Self::CourierOblique => Some((629.0, -157.0, Some(562.0), Some(426.0))),
            Self::CourierBoldOblique => Some((629.0, -157.0, Some(562.0), Some(439.0))),
            Self::TimesRoman => Some((683.0, -217.0, Some(662.0), Some(450.0))),
            Self::TimesBold => Some((683.0, -217.0, Some(676.0), Some(461.0))),
            Self::TimesItalic => Some((683.0, -217.0, Some(653.0), Some(441.0))),
            Self::TimesBoldItalic => Some((683.0, -217.0, Some(669.0), Some(462.0))),
            Self::ZapfDingBats => Some((820.0, -143.0, None, None)),
            Self::Symbol => Some((1010.0, -293.0, None, None)),
        }
    }

    /// Return suitable font data for the given standard font.
    ///
    /// Currently, this will return the corresponding Foxit font, which is a set of permissibly
    /// licensed fonts that is also very light-weight.
    ///
    /// You can use the result of this method in your implementation of [`FontResolverFn`].
    ///
    /// [`FontResolverFn`]: crate::FontResolverFn
    #[cfg(feature = "embed-fonts")]
    pub fn get_font_data(&self) -> (FontData, u32) {
        use std::sync::Arc;

        let data = match self {
            Self::Helvetica => &include_bytes!("../../assets/FoxitSans.pfb")[..],
            Self::HelveticaBold => &include_bytes!("../../assets/FoxitSansBold.pfb")[..],
            Self::HelveticaOblique => &include_bytes!("../../assets/FoxitSansItalic.pfb")[..],
            Self::HelveticaBoldOblique => {
                &include_bytes!("../../assets/FoxitSansBoldItalic.pfb")[..]
            }
            Self::Courier => &include_bytes!("../../assets/FoxitFixed.pfb")[..],
            Self::CourierBold => &include_bytes!("../../assets/FoxitFixedBold.pfb")[..],
            Self::CourierOblique => &include_bytes!("../../assets/FoxitFixedItalic.pfb")[..],
            Self::CourierBoldOblique => {
                &include_bytes!("../../assets/FoxitFixedBoldItalic.pfb")[..]
            }
            Self::TimesRoman => &include_bytes!("../../assets/FoxitSerif.pfb")[..],
            Self::TimesBold => &include_bytes!("../../assets/FoxitSerifBold.pfb")[..],
            Self::TimesItalic => &include_bytes!("../../assets/FoxitSerifItalic.pfb")[..],
            Self::TimesBoldItalic => &include_bytes!("../../assets/FoxitSerifBoldItalic.pfb")[..],
            Self::ZapfDingBats => &include_bytes!("../../assets/FoxitDingbats.pfb")[..],
            Self::Symbol => {
                include_bytes!("../../assets/FoxitSymbol.pfb")
            }
        };

        (Arc::new(data), 0)
    }
}

enum StandardFontFamily {
    Helvetica,
    Courier,
    Times,
}

/// PostScript-name aliases commonly produced by Office/iText/etc. that refer
/// to fonts the reader is expected to substitute with the corresponding
/// Standard-14 font. Matched after subset-prefix stripping and after the
/// literal Standard-14 names, but before the keyword-based heuristic.
///
/// Aliases are intentionally exact (case-sensitive) matches — the keyword
/// heuristic below already catches free-form variants like "ArialNarrow-Bold".
fn standard_font_alias(name: &str) -> Option<StandardFont> {
    match name {
        // Arial family → Helvetica
        "ArialMT" | "Arial" => Some(StandardFont::Helvetica),
        "Arial-BoldMT" | "Arial,Bold" | "Arial-Bold" => Some(StandardFont::HelveticaBold),
        "Arial-ItalicMT" | "Arial,Italic" | "Arial-Italic" => Some(StandardFont::HelveticaOblique),
        "Arial-BoldItalicMT" | "Arial,BoldItalic" | "Arial-BoldItalic" => {
            Some(StandardFont::HelveticaBoldOblique)
        }
        // Times New Roman family → Times
        "TimesNewRomanPSMT" | "TimesNewRoman" | "TimesNewRomanPS" => Some(StandardFont::TimesRoman),
        "TimesNewRomanPS-BoldMT"
        | "TimesNewRoman-Bold"
        | "TimesNewRomanPS-Bold"
        | "TimesNewRoman,Bold" => Some(StandardFont::TimesBold),
        "TimesNewRomanPS-ItalicMT"
        | "TimesNewRoman-Italic"
        | "TimesNewRomanPS-Italic"
        | "TimesNewRoman,Italic" => Some(StandardFont::TimesItalic),
        "TimesNewRomanPS-BoldItalicMT"
        | "TimesNewRoman-BoldItalic"
        | "TimesNewRomanPS-BoldItalic"
        | "TimesNewRoman,BoldItalic" => Some(StandardFont::TimesBoldItalic),
        // Courier New family → Courier
        "CourierNewPSMT" | "CourierNew" => Some(StandardFont::Courier),
        "CourierNewPS-BoldMT" | "CourierNew-Bold" | "CourierNewPS-Bold" => {
            Some(StandardFont::CourierBold)
        }
        "CourierNewPS-ItalicMT" | "CourierNew-Italic" | "CourierNewPS-Italic" => {
            Some(StandardFont::CourierOblique)
        }
        "CourierNewPS-BoldItalicMT" | "CourierNew-BoldItalic" | "CourierNewPS-BoldItalic" => {
            Some(StandardFont::CourierBoldOblique)
        }
        _ => None,
    }
}

pub(crate) fn select_standard_font(
    dict: &Dict<'_>,
    descriptor: &Dict<'_>,
) -> Option<(StandardFont, bool)> {
    let base_font = dict.get::<Name>(BASE_FONT)?;
    let name = strip_subset_prefix(base_font.as_str());

    // First try whether it matches literally.
    match name {
        "Helvetica" => return Some((StandardFont::Helvetica, true)),
        "Helvetica-Bold" => return Some((StandardFont::HelveticaBold, true)),
        "Helvetica-Oblique" => return Some((StandardFont::HelveticaOblique, true)),
        "Helvetica-BoldOblique" => return Some((StandardFont::HelveticaBoldOblique, true)),
        "Courier" => return Some((StandardFont::Courier, true)),
        "Courier-Bold" => return Some((StandardFont::CourierBold, true)),
        "Courier-Oblique" => return Some((StandardFont::CourierOblique, true)),
        "Courier-BoldOblique" => return Some((StandardFont::CourierBoldOblique, true)),
        "Times-Roman" => return Some((StandardFont::TimesRoman, true)),
        "Times-Bold" => return Some((StandardFont::TimesBold, true)),
        "Times-Italic" => return Some((StandardFont::TimesItalic, true)),
        "Times-BoldItalic" => return Some((StandardFont::TimesBoldItalic, true)),
        "Symbol" => return Some((StandardFont::Symbol, true)),
        "ZapfDingbats" => return Some((StandardFont::ZapfDingBats, true)),
        _ => {}
    }

    // PostScript-name aliases commonly emitted by Office/iText/etc. for
    // unembedded Standard-14-equivalent fonts (e.g. ArialMT → Helvetica).
    // Treated as non-exact so glyph-width fallback in StandardKind still
    // consults the supplied Widths array when present.
    if let Some(alias) = standard_font_alias(name) {
        return Some((alias, false));
    }

    // Now, we bruteforce, trying to determine a suitable font based on the
    // keywords that appear in the name and the descriptor.
    let lower = name.to_ascii_lowercase();

    // FontFamily (descriptor) captures the human-readable family, which is
    // often present even when BaseFont is an opaque subset name. PDF 1.7 §9.8.1
    // specifies it as a text string, but producers in the wild use name
    // objects too; fetch as Name (covers both via implicit conversion).
    let family_field = descriptor
        .get::<Name>(FONT_FAMILY)
        .map(|n| n.as_str().to_ascii_lowercase())
        .unwrap_or_default();

    // PDF spec §9.8.2 Table 120: FontWeight is a number in {100, 200, … 900};
    // 400 is normal and 700 is bold. Adobe considers weights ≥ 600 (SemiBold,
    // DemiBold) as "bold" for substitution purposes — matching that lowers
    // the threshold from 700 to 600 so fonts like "HelveticaNeue-Medium"
    // (weight 500) stay regular but "*-SemiBold" (600) map to the bold face.
    let is_bold = descriptor.get::<u32>(FONT_WEIGHT).is_some_and(|w| w >= 600)
        || lower.contains("bold")
        || lower.contains("demi")
        || family_field.contains("bold")
        || family_field.contains("demi");
    // PDF spec §9.8.2 Table 120: ItalicAngle is the angle, in counter-clockwise
    // degrees, of the dominant vertical strokes. Italic/oblique faces are
    // negative (typically -10° to -20°). Previously we accepted any non-zero
    // value, which mis-classified upright fonts that shipped with tiny
    // rounding noise (e.g. -0.1). The stricter −5° threshold follows what
    // PDF.js and PDFBox use and avoids that false-positive.
    let is_italic = descriptor
        .get::<f32>(ITALIC_ANGLE)
        .is_some_and(|a| !(-5.0..=5.0).contains(&a))
        || lower.contains("italic")
        || lower.contains("oblique")
        || family_field.contains("italic")
        || family_field.contains("oblique");

    // Keyword/family heuristic. Prefer BaseFont; fall back to FontFamily.
    let haystack = if family_field.is_empty() {
        lower.clone()
    } else {
        format!("{lower} {family_field}")
    };

    // Keyword/family heuristic (last resort — only reached when the font name
    // did not match any Standard-14 alias above).
    //
    // `exact` controls whether the caller should trust PDF /Widths entries or
    // fall back to Standard-14 AFM metrics:
    //   exact=true  → AFM metrics used; PDF /Widths ignored (safe for genuine
    //                 Standard-14 faces whose names survived case folding here)
    //   exact=false → PDF /Widths respected when present; AFM is only fallback
    //                 (correct for non-Standard-14 lookalikes like "ArialMT")
    //
    // GL-QA38 regression note: setting exact=false for ALL heuristic matches
    // caused 116 SSIM regressions in gate-5k-04 because many PDFs that contained
    // "helvetica" or "times" in the font name ARE genuine Standard-14 and their
    // /Widths arrays (when present) are less accurate than Standard-14 AFM.
    // The corrected approach: treat Standard-14 keyword matches (helvetica,
    // courier, times) as exact=true; treat clear non-Standard-14 keywords
    // (arial, sans, mono, serif without "times") as exact=false so we respect
    // their embedded /Widths.
    let (family, exact) = if haystack.contains("helvetica") {
        (Some(StandardFontFamily::Helvetica), true) // likely genuine Helvetica — use AFM
    } else if haystack.contains("arial") || haystack.contains("sans") {
        (Some(StandardFontFamily::Helvetica), false) // Arial/generic sans — respect /Widths
    } else if haystack.contains("courier") {
        (Some(StandardFontFamily::Courier), true) // likely genuine Courier — use AFM
    } else if haystack.contains("mono") {
        (Some(StandardFontFamily::Courier), false) // generic monospace — respect /Widths
    } else if haystack.contains("times") {
        (Some(StandardFontFamily::Times), true) // likely genuine Times — use AFM
    } else if haystack.contains("serif") {
        (Some(StandardFontFamily::Times), false) // generic serif — respect /Widths
    } else if haystack.contains("zapfdingbats") || haystack.contains("dingbats") {
        return Some((StandardFont::ZapfDingBats, false));
    } else {
        (None, false)
    };

    let font = match (family?, is_bold, is_italic) {
        (StandardFontFamily::Helvetica, false, false) => StandardFont::Helvetica,
        (StandardFontFamily::Helvetica, true, false) => StandardFont::HelveticaBold,
        (StandardFontFamily::Helvetica, false, true) => StandardFont::HelveticaOblique,
        (StandardFontFamily::Helvetica, true, true) => StandardFont::HelveticaBoldOblique,
        (StandardFontFamily::Courier, false, false) => StandardFont::Courier,
        (StandardFontFamily::Courier, true, false) => StandardFont::CourierBold,
        (StandardFontFamily::Courier, false, true) => StandardFont::CourierOblique,
        (StandardFontFamily::Courier, true, true) => StandardFont::CourierBoldOblique,
        (StandardFontFamily::Times, false, false) => StandardFont::TimesRoman,
        (StandardFontFamily::Times, true, false) => StandardFont::TimesBold,
        (StandardFontFamily::Times, false, true) => StandardFont::TimesItalic,
        (StandardFontFamily::Times, true, true) => StandardFont::TimesBoldItalic,
    };

    Some((font, exact))
}

#[derive(Debug)]
pub(crate) enum StandardFontBlob {
    Cff(CffFontBlob),
    Otf(OpenTypeFontBlob, HashMap<String, GlyphId>),
}

impl StandardFontBlob {
    pub(crate) fn from_data(data: FontData, index: u32) -> Option<Self> {
        if let Some(blob) = CffFontBlob::new(data.clone()) {
            Some(Self::new_cff(blob))
        } else {
            OpenTypeFontBlob::new(data, index).map(Self::new_otf)
        }
    }

    pub(crate) fn new_cff(blob: CffFontBlob) -> Self {
        Self::Cff(blob)
    }

    pub(crate) fn new_otf(blob: OpenTypeFontBlob) -> Self {
        let mut glyph_names = HashMap::new();

        if let Ok(post) = blob.font_ref().post() {
            for i in 0..blob.num_glyphs() {
                if let Some(str) = post.glyph_name(GlyphId16::new(i)) {
                    glyph_names.insert(str.to_string(), GlyphId::new(i as u32));
                }
            }
        }

        Self::Otf(blob, glyph_names)
    }
}

impl StandardFontBlob {
    pub(crate) fn name_to_glyph(&self, name: &str) -> Option<GlyphId> {
        match self {
            Self::Cff(blob) => blob
                .table()
                .glyph_index_by_name(name)
                .map(|g| GlyphId::new(g.0 as u32)),
            Self::Otf(_, glyph_names) => glyph_names.get(name).copied(),
        }
    }

    pub(crate) fn unicode_to_glyph(&self, code: u32) -> Option<GlyphId> {
        match self {
            Self::Cff(_) => None,
            Self::Otf(blob, _) => blob
                .font_ref()
                .cmap()
                .ok()
                .and_then(|c| c.map_codepoint(code)),
        }
    }

    pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option<f32> {
        match self {
            Self::Cff(_) => None,
            Self::Otf(blob, _) => blob.glyph_metrics().advance_width(glyph),
        }
    }

    pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {
        // Standard fonts have empty outlines for these, but in Liberation Sans
        // they are a .notdef rectangle.
        if glyph == GlyphId::NOTDEF {
            return BezPath::new();
        }

        match self {
            Self::Cff(blob) => blob.outline_glyph(glyph),
            Self::Otf(blob, _) => blob.outline_glyph(glyph),
        }
    }
}

#[derive(Debug)]
pub(crate) struct StandardKind {
    base_font: StandardFont,
    base_font_blob: StandardFontBlob,
    encoding: Encoding,
    widths: Vec<Width>,
    missing_width: Option<f32>,
    fallback: bool,
    glyph_to_code: RefCell<HashMap<GlyphId, u8>>,
    encodings: HashMap<u8, String>,
}

impl StandardKind {
    pub(crate) fn new(dict: &Dict<'_>, resolver: &FontResolverFn) -> Option<Self> {
        let descriptor = dict.get::<Dict<'_>>(FONT_DESC).unwrap_or_default();
        let (font, exact) = select_standard_font(dict, &descriptor)?;
        Self::new_with_standard(dict, font, !exact, resolver)
    }

    pub(crate) fn new_with_standard(
        dict: &Dict<'_>,
        base_font: StandardFont,
        fallback: bool,
        resolver: &FontResolverFn,
    ) -> Option<Self> {
        let descriptor = dict.get::<Dict<'_>>(FONT_DESC).unwrap_or_default();
        let (widths, missing_width) = read_widths(dict, &descriptor)?;
        let missing_width = descriptor
            .contains_key(MISSING_WIDTH)
            .then_some(missing_width);

        let (mut encoding, encoding_map) = read_encoding(dict);

        // See PDFJS-16464: Ignore encodings for non-embedded Type1 symbol fonts.
        if matches!(base_font, StandardFont::Symbol | StandardFont::ZapfDingBats) {
            encoding = Encoding::BuiltIn;
        }

        let (blob, index) = resolver(&FontQuery::Standard(base_font))?;
        let base_font_blob = StandardFontBlob::from_data(blob, index)?;

        Some(Self {
            base_font,
            base_font_blob,
            widths,
            missing_width,
            encodings: encoding_map,
            glyph_to_code: RefCell::new(HashMap::new()),
            fallback,
            encoding,
        })
    }

    fn code_to_ps_name(&self, code: u8) -> Option<&str> {
        let bf = self.base_font;

        self.encodings
            .get(&code)
            .map(String::as_str)
            .or_else(|| match self.encoding {
                Encoding::BuiltIn => bf.code_to_name(code),
                _ => self.encoding.map_code(code),
            })
    }

    pub(crate) fn map_code(&self, code: u8) -> GlyphId {
        let result = self
            .code_to_ps_name(code)
            .and_then(|c| {
                self.base_font_blob.name_to_glyph(c).or_else(|| {
                    // If the font doesn't have a POST table, try to map via unicode instead.
                    glyph_names::get(c).and_then(|c| {
                        self.base_font_blob
                            .unicode_to_glyph(c.chars().nth(0).unwrap() as u32)
                    })
                })
            })
            .unwrap_or(GlyphId::NOTDEF);
        self.glyph_to_code.borrow_mut().insert(result, code);

        result
    }

    pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath {
        let path = self.base_font_blob.outline_glyph(glyph);

        // If the font is not embedded, we might need to stretch it so that
        // it matches the metrics of the actual underlying font blob.

        if let Some(code) = self.glyph_to_code.borrow().get(&glyph).copied()
            && let Some(actual_width) = self.base_font_blob.advance_width(glyph).or_else(|| {
                self.code_to_ps_name(code)
                    .and_then(|name| self.base_font.get_width(name))
            })
        {
            // From my experiments: Most PDF viewers, if they detect a font is a
            // standard font, they completely ignore the widths array, even if
            // different widths are indicated there. So only if it's an unknown
            // font do we check the widths array. Otherwise, we always use the
            // base font metrics.
            let should_width = if self.fallback {
                if let Some(Width::Value(w)) = self.widths.get(code as usize).copied() {
                    w
                } else {
                    return path;
                }
            } else if let Some(w) = self
                .code_to_ps_name(code)
                .and_then(|name| self.base_font.get_width(name))
            {
                w
            } else {
                return path;
            };

            return stretch_glyph(path, should_width, actual_width);
        }

        path
    }

    pub(crate) fn glyph_width(&self, code: u8) -> Option<f32> {
        match self.widths.get(code as usize).copied() {
            Some(Width::Value(w)) => Some(w),
            Some(Width::Missing) => self.missing_width.or_else(|| {
                self.code_to_ps_name(code)
                    .and_then(|c| self.base_font.get_width(c))
            }),
            _ => self
                .code_to_ps_name(code)
                .and_then(|c| self.base_font.get_width(c)),
        }
    }

    pub(crate) fn char_code_to_unicode(&self, code: u8) -> Option<char> {
        self.code_to_ps_name(code).and_then(glyph_name_to_unicode)
    }

    pub(crate) fn is_italic(&self) -> bool {
        self.base_font.is_italic()
    }

    pub(crate) fn is_bold(&self) -> bool {
        self.base_font.is_bold()
    }

    pub(crate) fn is_serif(&self) -> bool {
        self.base_font.is_serif()
    }

    pub(crate) fn is_monospace(&self) -> bool {
        self.base_font.is_monospace()
    }

    /// PostScript name of the underlying standard-14 font.
    ///
    /// Always available because every `StandardKind` was constructed
    /// against a known [`StandardFont`].  Surfaced for the WASM
    /// `getTextPositions()` `fontName` field on non-embedded Type1
    /// runs (see `pdf-engine`).
    pub(crate) fn postscript_name(&self) -> &'static str {
        self.base_font.postscript_name()
    }

    /// Vertical font metrics from the Standard-14 AFM fallback table.
    pub(crate) fn font_metrics(&self) -> Option<(f64, f64, Option<f64>, Option<f64>)> {
        self.base_font.canonical_metrics()
    }
}

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

    fn build_widths(entries: &[(u8, f32)]) -> Vec<Width> {
        let mut widths = vec![Width::Missing; 256];
        for (code, width) in entries {
            widths[*code as usize] = Width::Value(*width);
        }
        widths
    }

    fn build_standard_kind(widths: Vec<Width>, missing_width: Option<f32>) -> StandardKind {
        let (data, index) = StandardFont::Helvetica.get_font_data();
        let base_font_blob =
            StandardFontBlob::from_data(data, index).expect("standard font data should parse");

        StandardKind {
            base_font: StandardFont::Helvetica,
            base_font_blob,
            encoding: Encoding::WinAnsi,
            widths,
            missing_width,
            fallback: true,
            glyph_to_code: RefCell::new(HashMap::new()),
            encodings: HashMap::new(),
        }
    }

    #[test]
    fn glyph_width_falls_back_to_base_metrics_when_missing_width_is_absent() {
        let font = build_standard_kind(build_widths(&[(b'A', 600.0)]), None);

        assert_eq!(font.glyph_width(b'A'), Some(600.0));
        assert_eq!(
            font.glyph_width(b'B'),
            StandardFont::Helvetica.get_width("B")
        );
    }

    #[test]
    fn glyph_width_respects_explicit_zero_missing_width() {
        let font = build_standard_kind(build_widths(&[(b'A', 600.0)]), Some(0.0));

        assert_eq!(font.glyph_width(b'A'), Some(600.0));
        assert_eq!(font.glyph_width(b'B'), Some(0.0));
    }

    #[test]
    fn arial_aliases_resolve_to_helvetica_family() {
        assert!(matches!(
            standard_font_alias("ArialMT"),
            Some(StandardFont::Helvetica)
        ));
        assert!(matches!(
            standard_font_alias("Arial-BoldMT"),
            Some(StandardFont::HelveticaBold)
        ));
        assert!(matches!(
            standard_font_alias("Arial-ItalicMT"),
            Some(StandardFont::HelveticaOblique)
        ));
        assert!(matches!(
            standard_font_alias("Arial-BoldItalicMT"),
            Some(StandardFont::HelveticaBoldOblique)
        ));
    }

    #[test]
    fn times_new_roman_aliases_resolve_to_times_family() {
        assert!(matches!(
            standard_font_alias("TimesNewRomanPSMT"),
            Some(StandardFont::TimesRoman)
        ));
        assert!(matches!(
            standard_font_alias("TimesNewRomanPS-BoldMT"),
            Some(StandardFont::TimesBold)
        ));
        assert!(matches!(
            standard_font_alias("TimesNewRomanPS-ItalicMT"),
            Some(StandardFont::TimesItalic)
        ));
        assert!(matches!(
            standard_font_alias("TimesNewRomanPS-BoldItalicMT"),
            Some(StandardFont::TimesBoldItalic)
        ));
    }

    #[test]
    fn courier_new_aliases_resolve_to_courier_family() {
        assert!(matches!(
            standard_font_alias("CourierNewPSMT"),
            Some(StandardFont::Courier)
        ));
        assert!(matches!(
            standard_font_alias("CourierNewPS-BoldMT"),
            Some(StandardFont::CourierBold)
        ));
        assert!(matches!(
            standard_font_alias("CourierNewPS-ItalicMT"),
            Some(StandardFont::CourierOblique)
        ));
        assert!(matches!(
            standard_font_alias("CourierNewPS-BoldItalicMT"),
            Some(StandardFont::CourierBoldOblique)
        ));
    }

    #[test]
    fn unknown_names_do_not_alias() {
        assert!(standard_font_alias("LiberationSans").is_none());
        assert!(standard_font_alias("CenturySchoolbook").is_none());
        assert!(standard_font_alias("").is_none());
    }

    // ── canonical_metrics tests ──

    #[test]
    fn helvetica_metrics() {
        let m = StandardFont::Helvetica.canonical_metrics().unwrap();
        assert_eq!(m.0, 718.0);
        assert_eq!(m.1, -207.0);
        assert_eq!(m.2, Some(718.0));
        assert_eq!(m.3, Some(523.0));
    }

    #[test]
    fn helvetica_bold_metrics() {
        let m = StandardFont::HelveticaBold.canonical_metrics().unwrap();
        assert_eq!(m.0, 718.0);
        assert_eq!(m.1, -207.0);
        assert_eq!(m.2, Some(718.0));
        assert_eq!(m.3, Some(532.0));
    }

    #[test]
    fn helvetica_oblique_metrics() {
        let m = StandardFont::HelveticaOblique.canonical_metrics().unwrap();
        assert_eq!(m.0, 718.0);
        assert_eq!(m.1, -207.0);
        assert_eq!(m.2, Some(718.0));
        assert_eq!(m.3, Some(523.0));
    }

    #[test]
    fn helvetica_bold_oblique_metrics() {
        let m = StandardFont::HelveticaBoldOblique
            .canonical_metrics()
            .unwrap();
        assert_eq!(m.0, 718.0);
        assert_eq!(m.1, -207.0);
        assert_eq!(m.2, Some(718.0));
        assert_eq!(m.3, Some(532.0));
    }

    #[test]
    fn courier_metrics() {
        let m = StandardFont::Courier.canonical_metrics().unwrap();
        assert_eq!(m.0, 629.0);
        assert_eq!(m.1, -157.0);
        assert_eq!(m.2, Some(562.0));
        assert_eq!(m.3, Some(426.0));
    }

    #[test]
    fn courier_bold_metrics() {
        let m = StandardFont::CourierBold.canonical_metrics().unwrap();
        assert_eq!(m.0, 629.0);
        assert_eq!(m.1, -157.0);
        assert_eq!(m.2, Some(562.0));
        assert_eq!(m.3, Some(439.0));
    }

    #[test]
    fn courier_oblique_metrics() {
        let m = StandardFont::CourierOblique.canonical_metrics().unwrap();
        assert_eq!(m.0, 629.0);
        assert_eq!(m.1, -157.0);
        assert_eq!(m.2, Some(562.0));
        assert_eq!(m.3, Some(426.0));
    }

    #[test]
    fn courier_bold_oblique_metrics() {
        let m = StandardFont::CourierBoldOblique
            .canonical_metrics()
            .unwrap();
        assert_eq!(m.0, 629.0);
        assert_eq!(m.1, -157.0);
        assert_eq!(m.2, Some(562.0));
        assert_eq!(m.3, Some(439.0));
    }

    #[test]
    fn times_roman_metrics() {
        let m = StandardFont::TimesRoman.canonical_metrics().unwrap();
        assert_eq!(m.0, 683.0);
        assert_eq!(m.1, -217.0);
        assert_eq!(m.2, Some(662.0));
        assert_eq!(m.3, Some(450.0));
    }

    #[test]
    fn times_bold_metrics() {
        let m = StandardFont::TimesBold.canonical_metrics().unwrap();
        assert_eq!(m.0, 683.0);
        assert_eq!(m.1, -217.0);
        assert_eq!(m.2, Some(676.0));
        assert_eq!(m.3, Some(461.0));
    }

    #[test]
    fn times_italic_metrics() {
        let m = StandardFont::TimesItalic.canonical_metrics().unwrap();
        assert_eq!(m.0, 683.0);
        assert_eq!(m.1, -217.0);
        assert_eq!(m.2, Some(653.0));
        assert_eq!(m.3, Some(441.0));
    }

    #[test]
    fn times_bold_italic_metrics() {
        let m = StandardFont::TimesBoldItalic.canonical_metrics().unwrap();
        assert_eq!(m.0, 683.0);
        assert_eq!(m.1, -217.0);
        assert_eq!(m.2, Some(669.0));
        assert_eq!(m.3, Some(462.0));
    }

    #[test]
    fn symbol_metrics_no_letterform_values() {
        let m = StandardFont::Symbol.canonical_metrics().unwrap();
        assert_eq!(m.0, 1010.0);
        assert_eq!(m.1, -293.0);
        assert!(m.2.is_none(), "Symbol has no cap_height");
        assert!(m.3.is_none(), "Symbol has no x_height");
    }

    #[test]
    fn zapf_dingbats_metrics_no_letterform_values() {
        let m = StandardFont::ZapfDingBats.canonical_metrics().unwrap();
        assert_eq!(m.0, 820.0);
        assert_eq!(m.1, -143.0);
        assert!(m.2.is_none(), "ZapfDingbats has no cap_height");
        assert!(m.3.is_none(), "ZapfDingbats has no x_height");
    }

    #[test]
    fn all_14_fonts_return_some() {
        let all = &[
            StandardFont::Helvetica,
            StandardFont::HelveticaBold,
            StandardFont::HelveticaOblique,
            StandardFont::HelveticaBoldOblique,
            StandardFont::Courier,
            StandardFont::CourierBold,
            StandardFont::CourierOblique,
            StandardFont::CourierBoldOblique,
            StandardFont::TimesRoman,
            StandardFont::TimesBold,
            StandardFont::TimesItalic,
            StandardFont::TimesBoldItalic,
            StandardFont::Symbol,
            StandardFont::ZapfDingBats,
        ];
        for font in all {
            assert!(
                font.canonical_metrics().is_some(),
                "font {:?} returned None",
                font
            );
        }
    }

    #[test]
    fn ascent_always_positive_descent_always_negative() {
        let all = &[
            StandardFont::Helvetica,
            StandardFont::HelveticaBold,
            StandardFont::HelveticaOblique,
            StandardFont::HelveticaBoldOblique,
            StandardFont::Courier,
            StandardFont::CourierBold,
            StandardFont::CourierOblique,
            StandardFont::CourierBoldOblique,
            StandardFont::TimesRoman,
            StandardFont::TimesBold,
            StandardFont::TimesItalic,
            StandardFont::TimesBoldItalic,
            StandardFont::Symbol,
            StandardFont::ZapfDingBats,
        ];
        for font in all {
            let (ascent, descent, _, _) = font.canonical_metrics().unwrap();
            assert!(
                ascent > 0.0,
                "font {:?} ascent {} not positive",
                font,
                ascent
            );
            assert!(
                descent < 0.0,
                "font {:?} descent {} not negative",
                font,
                descent
            );
        }
    }
}