rustium-pdf 0.1.3

Pure-Rust PDF page-primitive extraction and rendering: glyphs with geometry, vector paths, images.
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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
//! Fonts: mapping character codes to advances, Unicode and glyph outlines.
//!
//! Three shapes of font reach this module and they differ in how a string becomes glyphs:
//!
//! * **Simple** (Type1, TrueType, MMType1) — one byte per code, and an encoding table maps each
//!   code to a glyph *name*.
//! * **Type0** (composite) — a CMap splits the string into codes of one to four bytes and maps
//!   each to a CID, which the descendant font turns into a glyph.
//! * **Type3** — glyphs are content streams; the page interpreter draws them, so this module
//!   only supplies the encoding, the font matrix and the procedure streams.

pub mod cmap;
pub mod encoding;
pub mod glyph;
mod metrics;
pub mod system;
mod type1;

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::document::Document;
use crate::geom::Matrix;
use crate::object::{Dict, Object};

use cmap::CMap;
use encoding::{base_encoding_name, glyph_name_to_unicode, Encoding};
use glyph::{Outline, OutlineBuilder};

/// Typeface properties, from the font descriptor's `/Flags` plus the corroborating entries.
///
/// A descriptor's flags alone are unreliable — publisher toolchains routinely ship bold faces
/// with the bold bit clear and italic faces with a zero `/ItalicAngle` — so each accessor
/// corroborates the bit with the font's weight, angle or name before answering.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FontFlags(pub u32);

impl FontFlags {
    pub const FIXED_PITCH: u32 = 1 << 0;
    pub const SERIF: u32 = 1 << 1;
    pub const SYMBOLIC: u32 = 1 << 2;
    pub const CURSIVE: u32 = 1 << 3;
    pub const ITALIC: u32 = 1 << 4;
    pub const ALL_CAPS: u32 = 1 << 5;
    pub const SMALL_CAPS: u32 = 1 << 6;
    pub const BOLD: u32 = 1 << 7;
    /// Set when the descriptor's nonsymbolic bit is set or the serif bit is clear; a font is
    /// never both this and [`FontFlags::SERIF`].
    pub const SANS_SERIF: u32 = 1 << 8;

    pub fn has(self, flag: u32) -> bool {
        self.0 & flag != 0
    }

    fn set(&mut self, flag: u32, on: bool) {
        if on {
            self.0 |= flag;
        } else {
            self.0 &= !flag;
        }
    }

    pub fn is_bold(self) -> bool {
        self.has(Self::BOLD)
    }

    pub fn is_italic(self) -> bool {
        self.has(Self::ITALIC)
    }

    pub fn is_serif(self) -> bool {
        self.has(Self::SERIF)
    }

    pub fn is_fixed_pitch(self) -> bool {
        self.has(Self::FIXED_PITCH)
    }

    pub fn is_symbolic(self) -> bool {
        self.has(Self::SYMBOLIC)
    }
}

/// Bit positions in a font descriptor's `/Flags`, per the PDF specification's table.
mod desc_flag {
    pub const FIXED_PITCH: i64 = 1 << 0;
    pub const SERIF: i64 = 1 << 1;
    pub const SYMBOLIC: i64 = 1 << 2;
    pub const SCRIPT: i64 = 1 << 3;
    pub const NONSYMBOLIC: i64 = 1 << 5;
    pub const ITALIC: i64 = 1 << 6;
    pub const ALL_CAP: i64 = 1 << 16;
    pub const SMALL_CAP: i64 = 1 << 17;
    pub const FORCE_BOLD: i64 = 1 << 18;
}

/// Derives typeface properties from a descriptor and the `/BaseFont` name.
fn derive_flags(doc: &Document, descriptor: Option<&Dict>, base_font: &str) -> FontFlags {
    let num = |key: &str| {
        descriptor
            .and_then(|d| doc.dict_get(d, key))
            .and_then(|o| o.as_f32())
    };
    let raw = descriptor
        .and_then(|d| doc.dict_get(d, "Flags"))
        .and_then(|o| o.as_int())
        .unwrap_or(0);

    // The style suffix on a subset name (`ABCDEF+Times-BoldItalic`) is often the only honest
    // record of the face, so it corroborates every heuristic below.
    let name = base_font
        .split('+')
        .next_back()
        .unwrap_or(base_font)
        .to_ascii_lowercase();

    let mut flags = FontFlags::default();

    // A font is symbolic when it says so and does not also claim to be nonsymbolic; producers
    // that set both mean nonsymbolic, which is the more conservative reading.
    let symbolic = raw & desc_flag::SYMBOLIC != 0 && raw & desc_flag::NONSYMBOLIC == 0;
    flags.set(FontFlags::SYMBOLIC, symbolic);

    let serif = raw & desc_flag::SERIF != 0
        || [
            "times", "roman", "georgia", "garamond", "minion", "cambria", "book",
        ]
        .iter()
        .any(|f| name.contains(f));
    flags.set(FontFlags::SERIF, serif);
    flags.set(FontFlags::SANS_SERIF, !serif && !symbolic);

    flags.set(
        FontFlags::FIXED_PITCH,
        raw & desc_flag::FIXED_PITCH != 0 || name.contains("courier") || name.contains("mono"),
    );

    // `/ItalicAngle` is the strongest signal: an upright face has angle zero.
    let italic = raw & desc_flag::ITALIC != 0
        || num("ItalicAngle").is_some_and(|a| a.abs() > 0.5)
        || name.contains("italic")
        || name.contains("oblique");
    flags.set(FontFlags::ITALIC, italic);

    // The descriptor's bold bit alone misses faces that are bold by weight but not by flag,
    // which is common in publisher-typeset PDFs. `/StemV` above ~120 is a bold stem width.
    let bold = raw & desc_flag::FORCE_BOLD != 0
        || num("FontWeight").is_some_and(|w| w >= 600.0)
        || num("StemV").is_some_and(|s| s >= 120.0)
        || name.contains("bold")
        || name.contains("black")
        || name.contains("heavy");
    flags.set(FontFlags::BOLD, bold);

    flags.set(
        FontFlags::CURSIVE,
        raw & desc_flag::SCRIPT != 0 || name.contains("script"),
    );
    flags.set(FontFlags::ALL_CAPS, raw & desc_flag::ALL_CAP != 0);
    flags.set(FontFlags::SMALL_CAPS, raw & desc_flag::SMALL_CAP != 0);
    flags
}

/// One character code decoded from a PDF string.
#[derive(Debug, Clone)]
pub struct CodeItem {
    /// The raw character code, as assembled from one or more bytes.
    pub code: u32,
    /// The glyph selector: the code itself for simple fonts, the CID for composite ones.
    pub cid: u32,
    /// The text this code contributes, when it can be determined.
    pub unicode: Option<String>,
    /// Horizontal advance in glyph space, where 1000 units is one em.
    pub width: f32,
    /// True only for a single-byte code 32, which is what `Tw` word spacing applies to.
    pub is_word_space: bool,
}

/// An embedded font program.
enum Program {
    /// TrueType or OpenType — anything with an sfnt table directory.
    Sfnt(Arc<[u8]>),
    /// A bare CFF program (`/FontFile3` with subtype `Type1C` or `CIDFontType0C`).
    Cff(Arc<[u8]>),
    /// A Type1 program (`/FontFile`). Its charstrings are eexec-encrypted and are not
    /// interpreted, so it yields no outlines — but its cleartext header carries the builtin
    /// `/Encoding`, which for a symbolic font is the only record of what each code means.
    Type1(Arc<[u8]>),
    /// No embedded program at all.
    None,
}

impl Program {
    /// The encoding the program declares for itself, where the format exposes one.
    fn builtin_encoding(&self) -> Option<type1::Builtin> {
        match self {
            Program::Type1(data) => type1::builtin_encoding(data),
            _ => None,
        }
    }
}

/// Advance widths, in the form the font type declares them.
enum Widths {
    /// Simple fonts: an array indexed from `first`, with a fallback for codes outside it.
    Simple {
        first: u32,
        widths: Vec<f32>,
        missing: Option<f32>,
    },
    /// CID fonts: sparse per-CID widths over a default.
    Cid {
        default: f32,
        map: HashMap<u32, f32>,
    },
}

/// The parts specific to a composite (Type0) font.
struct Composite {
    /// Maps character codes to CIDs and defines the codespace.
    cmap: CMap,
    /// `/CIDToGIDMap` as a stream: two big-endian bytes of glyph id per CID.
    cid_to_gid: Option<Arc<[u8]>>,
}

/// A loaded font, ready to decode strings and produce outlines.
///
/// Outlines are cached behind a mutex, so a `Font` shared across threads stays correct and only
/// pays for each glyph once.
pub struct Font {
    pub base_font: String,
    /// Typeface properties, corroborated from the descriptor, weight, angle and name.
    pub flags: FontFlags,
    pub is_type3: bool,
    /// Glyph space to text space. `0.001` scale for every font type except Type3, which
    /// declares its own.
    pub font_matrix: Matrix,
    /// Code to glyph name, 256 entries, for simple and Type3 fonts. Empty for Type0.
    names: Vec<String>,
    /// A symbolic font's built-in encoding takes precedence over any standard one.
    symbolic: bool,
    composite: Option<Composite>,
    to_unicode: Option<CMap>,
    widths: Widths,
    program: Program,
    /// Type3 `/CharProcs`.
    char_procs: Dict,
    outline_cache: Mutex<HashMap<u32, Option<Arc<Outline>>>>,
    /// The substitute face, resolved on the first glyph that needs one.
    substitute: std::sync::OnceLock<Option<Arc<[u8]>>>,
    /// CID to glyph id for a CID-keyed CFF program, inverted from its charset on first use.
    /// Empty for a program that is not CID-keyed.
    cff_cid_to_gid: std::sync::OnceLock<HashMap<u16, u16>>,
}

impl std::fmt::Debug for Font {
    /// Deliberately shallow: the caches and program bytes are noise in a glyph dump, and a
    /// `Glyph` holding an `Arc<Font>` is printed once per character.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Font")
            .field("base_font", &self.base_font)
            .field("flags", &self.flags)
            .field("is_type3", &self.is_type3)
            .finish_non_exhaustive()
    }
}

impl Font {
    /// Builds a font from a `/Font` resource dictionary.
    ///
    /// Malformed entries degrade rather than fail: a font that cannot be understood still
    /// decodes codes and reports advances, because dropping the text entirely is worse than
    /// reporting it with approximate metrics.
    pub fn load(doc: &Document, dict: &Dict) -> Font {
        let subtype = dict.get("Subtype").and_then(|o| o.as_name()).unwrap_or("");
        let base_font = doc
            .dict_get(dict, "BaseFont")
            .as_ref()
            .and_then(|o| o.as_name())
            .unwrap_or("")
            .to_string();

        match subtype {
            "Type0" => Self::load_type0(doc, dict, base_font),
            "Type3" => Self::load_type3(doc, dict, base_font),
            _ => Self::load_simple(doc, dict, base_font),
        }
    }

    // ---- constructors per font type ---------------------------------------------------------

    fn load_simple(doc: &Document, dict: &Dict, base_font: String) -> Font {
        let descriptor = doc
            .dict_get(dict, "FontDescriptor")
            .and_then(|o| o.as_dict().cloned());
        let flags = derive_flags(doc, descriptor.as_ref(), &base_font);
        let symbolic = flags.is_symbolic();

        // The program is loaded first: a symbolic font that names no encoding falls back to the
        // one the program declares for itself.
        let program = load_program(doc, descriptor.as_ref());
        let names = build_encoding(doc, dict, &base_font, symbolic, &program);
        let widths = simple_widths(doc, dict, descriptor.as_ref());

        Font {
            base_font,
            flags,
            is_type3: false,
            font_matrix: Matrix::scale(0.001, 0.001),
            names,
            symbolic,
            composite: None,
            to_unicode: load_to_unicode(doc, dict),
            widths,
            program,
            char_procs: Dict::new(),
            outline_cache: Mutex::new(HashMap::new()),
            substitute: std::sync::OnceLock::new(),
            cff_cid_to_gid: std::sync::OnceLock::new(),
        }
    }

    fn load_type0(doc: &Document, dict: &Dict, base_font: String) -> Font {
        // The encoding CMap turns bytes into CIDs.
        let cmap = match doc.dict_get(dict, "Encoding") {
            Some(Object::Name(n)) => {
                if n.starts_with("Identity") {
                    CMap::identity()
                } else {
                    // A predefined non-identity CMap needs Adobe's CMap files, which are not
                    // bundled; identity keeps the codespace right for the two-byte majority.
                    CMap::identity()
                }
            }
            Some(obj) => obj
                .as_stream()
                .and_then(|s| doc.file.decode_stream(s).ok())
                .map(|d| CMap::parse(&d.data))
                .unwrap_or_else(CMap::identity),
            None => CMap::identity(),
        };

        // Metrics and the glyph program live on the descendant.
        let descendant = doc
            .dict_get(dict, "DescendantFonts")
            .and_then(|o| match o {
                Object::Array(items) => items.first().map(|i| doc.resolve(i)),
                other => Some(other),
            })
            .and_then(|o| o.as_dict().cloned())
            .unwrap_or_default();
        let descriptor = doc
            .dict_get(&descendant, "FontDescriptor")
            .and_then(|o| o.as_dict().cloned());

        let cid_to_gid = match doc.dict_get(&descendant, "CIDToGIDMap") {
            Some(Object::Stream(s)) => doc
                .file
                .decode_stream(&s)
                .ok()
                .map(|d| Arc::from(d.data.as_slice())),
            // `/Identity` (or absent) means the CID is the glyph id.
            _ => None,
        };

        Font {
            flags: derive_flags(doc, descriptor.as_ref(), &base_font),
            base_font,
            is_type3: false,
            font_matrix: Matrix::scale(0.001, 0.001),
            names: Vec::new(),
            symbolic: true,
            composite: Some(Composite { cmap, cid_to_gid }),
            to_unicode: load_to_unicode(doc, dict),
            widths: cid_widths(doc, &descendant),
            program: load_program(doc, descriptor.as_ref()),
            char_procs: Dict::new(),
            outline_cache: Mutex::new(HashMap::new()),
            substitute: std::sync::OnceLock::new(),
            cff_cid_to_gid: std::sync::OnceLock::new(),
        }
    }

    fn load_type3(doc: &Document, dict: &Dict, base_font: String) -> Font {
        let font_matrix = doc
            .dict_get(dict, "FontMatrix")
            .as_ref()
            .and_then(|o| o.as_array())
            .map(|a| {
                let v: Vec<f32> = a.iter().filter_map(|o| o.as_f32()).collect();
                if v.len() >= 6 {
                    Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5])
                } else {
                    Matrix::scale(0.001, 0.001)
                }
            })
            .unwrap_or_else(|| Matrix::scale(0.001, 0.001));

        Font {
            // A Type3 font has no program and no descriptor worth trusting; its glyphs are
            // arbitrary procedures, which is exactly what the symbolic flag means.
            flags: FontFlags(FontFlags::SYMBOLIC),
            base_font,
            is_type3: true,
            font_matrix,
            // A Type3 font has no embedded program, so there is no builtin encoding to consult.
            names: build_encoding(doc, dict, "", true, &Program::None),
            symbolic: true,
            composite: None,
            to_unicode: load_to_unicode(doc, dict),
            widths: simple_widths(doc, dict, None),
            program: Program::None,
            char_procs: doc
                .dict_get(dict, "CharProcs")
                .and_then(|o| o.as_dict().cloned())
                .unwrap_or_default(),
            outline_cache: Mutex::new(HashMap::new()),
            substitute: std::sync::OnceLock::new(),
            cff_cid_to_gid: std::sync::OnceLock::new(),
        }
    }

    // ---- decoding ---------------------------------------------------------------------------

    /// Splits a PDF string into character codes with their advances and text.
    pub fn decode(&self, bytes: &[u8]) -> Vec<CodeItem> {
        match &self.composite {
            Some(comp) => comp
                .cmap
                .codespace
                .decode(bytes)
                .into_iter()
                .map(|code| {
                    let cid = comp.cmap.cid(code);
                    CodeItem {
                        code,
                        cid,
                        unicode: self.unicode_for(code),
                        width: self.width_for(code, cid),
                        // Word spacing is defined only for single-byte code 32, which a
                        // composite font's codespace does not produce in practice.
                        is_word_space: false,
                    }
                })
                .collect(),
            None => bytes
                .iter()
                .map(|&b| {
                    let code = u32::from(b);
                    CodeItem {
                        code,
                        cid: code,
                        unicode: self.unicode_for(code),
                        width: self.width_for(code, code),
                        is_word_space: b == 32,
                    }
                })
                .collect(),
        }
    }

    /// The text a code contributes: `/ToUnicode` first, then the glyph name it is encoded to.
    fn unicode_for(&self, code: u32) -> Option<String> {
        if let Some(map) = &self.to_unicode {
            if let Some(s) = map.unicode(code) {
                return Some(undo_symbol_pua(&s));
            }
        }
        glyph_name_to_unicode(self.glyph_name(code))
    }

    /// The glyph name a simple font encodes `code` to, or `""`.
    fn glyph_name(&self, code: u32) -> &str {
        self.names
            .get(code as usize)
            .map(String::as_str)
            .unwrap_or("")
    }

    fn width_for(&self, code: u32, cid: u32) -> f32 {
        match &self.widths {
            Widths::Simple {
                first,
                widths,
                missing,
            } => {
                if let Some(w) = code
                    .checked_sub(*first)
                    .and_then(|i| widths.get(i as usize))
                    .copied()
                {
                    // A zero width in the array is legitimate (combining marks), so it is only
                    // overridden when the array is absent entirely.
                    return w;
                }
                // For one of the 14 standard fonts the built-in metrics are authoritative. For
                // any other font `/MissingWidth` is the descriptor's own answer and outranks a
                // guess made from a look-alike standard face.
                let standard = metrics::is_standard_font(&self.base_font);
                if standard {
                    if let Some(w) = metrics::base14_width(&self.base_font, self.glyph_name(code)) {
                        return w;
                    }
                }
                missing
                    .or_else(|| metrics::base14_width(&self.base_font, self.glyph_name(code)))
                    .unwrap_or(500.0)
            }
            Widths::Cid { default, map } => map.get(&cid).copied().unwrap_or(*default),
        }
    }

    // ---- outlines ---------------------------------------------------------------------------

    /// The outline for a decoded code, in glyph space (1000 units per em).
    ///
    /// `None` when the font has no interpretable program or the glyph is absent — the caller
    /// still has geometry and text, which is what extraction needs; only rendering needs this.
    pub fn outline(&self, item: &CodeItem) -> Option<Arc<Outline>> {
        if let Some(hit) = self.outline_cache.lock().unwrap().get(&item.cid) {
            return hit.clone();
        }
        let built = self.build_outline(item).map(Arc::new);
        self.outline_cache
            .lock()
            .unwrap()
            .insert(item.cid, built.clone());
        built
    }

    fn build_outline(&self, item: &CodeItem) -> Option<Outline> {
        self.embedded_outline(item)
            .or_else(|| self.substitute_outline(item))
    }

    /// Draws the glyph from a substitute system face, keeping the document's own advance.
    ///
    /// Reached when a font embeds no program — the standard 14 typically do not — or embeds one
    /// this crate cannot interpret. Without it those pages render with no text at all.
    fn substitute_outline(&self, item: &CodeItem) -> Option<Outline> {
        if self.is_type3 {
            return None;
        }
        let data = self.substitute.get_or_init(|| {
            system::substitute(system::Style {
                serif: self.flags.is_serif(),
                fixed_pitch: self.flags.is_fixed_pitch(),
                bold: self.flags.is_bold(),
                italic: self.flags.is_italic(),
            })
        });
        let face = ttf_parser::Face::parse(data.as_ref()?, 0).ok()?;
        // A substitute has its own glyph order, so the only durable key into it is Unicode.
        let ch = item.unicode.as_deref()?.chars().next()?;
        let gid = face.glyph_index(ch)?;
        let mut sink = Sink::default();
        face.outline_glyph(gid, &mut sink)?;
        let upem = f32::from(face.units_per_em()).max(1.0);
        Some(Outline {
            is_substitute: true,
            ..sink.finish(1000.0 / upem, item.width)
        })
    }

    fn embedded_outline(&self, item: &CodeItem) -> Option<Outline> {
        match &self.program {
            Program::Sfnt(data) => {
                let face = ttf_parser::Face::parse(data, 0).ok()?;
                let gid = self.sfnt_glyph_id(&face, item)?;
                let mut sink = Sink::default();
                face.outline_glyph(gid, &mut sink)?;
                // Font units per em vary (1000 for CFF-flavoured, 2048 for most TrueType);
                // normalise so callers only ever see glyph space.
                let upem = f32::from(face.units_per_em()).max(1.0);
                Some(sink.finish(1000.0 / upem, item.width))
            }
            Program::Cff(data) => {
                let table = ttf_parser::cff::Table::parse(data)?;
                let gid = self.cff_glyph_id(&table, item)?;
                let mut sink = Sink::default();
                table.outline(gid, &mut sink).ok()?;
                // A CFF font matrix is usually 1/1000, but subsetters do emit others.
                let scale = table.matrix().sx * 1000.0;
                Some(sink.finish(if scale.abs() < 1e-6 { 1.0 } else { scale }, item.width))
            }
            Program::Type1(_) | Program::None => None,
        }
    }

    /// Resolves a code to a glyph id in an sfnt program.
    fn sfnt_glyph_id(
        &self,
        face: &ttf_parser::Face,
        item: &CodeItem,
    ) -> Option<ttf_parser::GlyphId> {
        if self.composite.is_some() {
            return Some(ttf_parser::GlyphId(self.composite_gid(item.cid)));
        }
        let name = self.glyph_name(item.code);

        // A symbolic font's own cmap is authoritative and is keyed by the raw code — often in
        // the (3,0) subtable at 0xF000 + code, which is where symbol fonts hide.
        if self.symbolic {
            if let Some(gid) = symbol_cmap_lookup(face, item.code) {
                return Some(gid);
            }
        }
        if !name.is_empty() {
            if let Some(gid) = face.glyph_index_by_name(name) {
                return Some(gid);
            }
            if let Some(ch) = glyph_name_to_unicode(name).and_then(|s| s.chars().next()) {
                if let Some(gid) = face.glyph_index(ch) {
                    return Some(gid);
                }
            }
        }
        if !self.symbolic {
            if let Some(gid) = symbol_cmap_lookup(face, item.code) {
                return Some(gid);
            }
        }
        // Subset fonts with no usable cmap are conventionally indexed by code.
        Some(ttf_parser::GlyphId(item.code as u16))
    }

    /// Resolves a code to a glyph id in a bare CFF program.
    fn cff_glyph_id(
        &self,
        table: &ttf_parser::cff::Table,
        item: &CodeItem,
    ) -> Option<ttf_parser::GlyphId> {
        if self.composite.is_some() {
            // A CID-keyed CFF records its own CID for each glyph in its charset, and the
            // identity `/CIDToGIDMap` describes does not apply to it — that entry is a
            // CIDFontType2 mechanism. Taking the CID as a glyph id draws whichever glyph
            // happens to sit at that index. The text still comes out right, because text comes
            // from the encoding, so the only symptom is that every reported glyph box is some
            // other letter's — which is enough to make a heading look like it has a space in it.
            if let Some(gid) = self.cff_cid_to_gid(table, item.cid) {
                return Some(ttf_parser::GlyphId(gid));
            }
            return Some(ttf_parser::GlyphId(self.composite_gid(item.cid)));
        }
        let name = self.glyph_name(item.code);
        if !name.is_empty() {
            if let Some(gid) = table.glyph_index_by_name(name) {
                return Some(gid);
            }
        }
        if let Ok(code) = u8::try_from(item.code) {
            if let Some(gid) = table.glyph_index(code) {
                return Some(gid);
            }
        }
        Some(ttf_parser::GlyphId(item.cid as u16))
    }

    /// Inverts a CID-keyed CFF's charset to map a CID to its glyph id.
    ///
    /// The charset only runs glyph id to CID, so the whole table is walked once and cached.
    /// `None` when the program is not CID-keyed, which is also what leaves the map empty.
    fn cff_cid_to_gid(&self, table: &ttf_parser::cff::Table, cid: u32) -> Option<u16> {
        let map = self.cff_cid_to_gid.get_or_init(|| {
            let mut map = HashMap::new();
            for gid in 0..table.number_of_glyphs() {
                if let Some(cid) = table.glyph_cid(ttf_parser::GlyphId(gid)) {
                    // A duplicated CID is malformed; the first glyph claiming it wins.
                    map.entry(cid).or_insert(gid);
                }
            }
            map
        });
        map.get(&u16::try_from(cid).ok()?).copied()
    }

    /// A composite font's CID to glyph id, through `/CIDToGIDMap` when one is present.
    fn composite_gid(&self, cid: u32) -> u16 {
        let Some(map) = self.composite.as_ref().and_then(|c| c.cid_to_gid.as_ref()) else {
            return cid as u16;
        };
        let i = cid as usize * 2;
        match (map.get(i), map.get(i + 1)) {
            (Some(&hi), Some(&lo)) => u16::from_be_bytes([hi, lo]),
            // Past the end of the map means unmapped, which is glyph 0.
            _ => 0,
        }
    }

    // ---- Type3 ------------------------------------------------------------------------------

    /// The content stream that draws `code`, for a Type3 font.
    pub fn type3_proc(&self, doc: &Document, code: u32) -> Option<Object> {
        let name = self.glyph_name(code);
        if name.is_empty() {
            return None;
        }
        doc.dict_get(&self.char_procs, name)
    }
}

/// Looks a raw code up in the cmap subtables symbol fonts use.
fn symbol_cmap_lookup(face: &ttf_parser::Face, code: u32) -> Option<ttf_parser::GlyphId> {
    use ttf_parser::PlatformId;
    let cmap = face.tables().cmap?;
    for sub in cmap.subtables {
        match sub.platform_id {
            // (3,0) Windows Symbol: codes live in the 0xF000 private-use page, but broken
            // producers write the bare code too.
            PlatformId::Windows if sub.encoding_id == 0 => {
                for candidate in [0xF000 + (code & 0xFF), code] {
                    if let Some(gid) = sub.glyph_index(candidate) {
                        return Some(gid);
                    }
                }
            }
            // (1,0) Macintosh Roman: a straight byte lookup.
            PlatformId::Macintosh if sub.encoding_id == 0 => {
                if let Some(gid) = sub.glyph_index(code) {
                    return Some(gid);
                }
            }
            _ => {}
        }
    }
    None
}

/// Rewrites Microsoft's symbol-font private-use characters as the symbols they stand for.
///
/// A font with a `(3, 0)` symbol `cmap` addresses its glyphs at `0xF000 + code`, and producers —
/// Word above all — write `/ToUnicode` maps that hand those private-use code points straight
/// back out. The result is text made of U+F0xx: an equation reading `α = β` extracts as three
/// characters from a range that means nothing to anyone.
///
/// The low byte is the original character code, so it is read through the Symbol encoding. Only
/// U+F020..=U+F0FF is touched, which is the range that convention covers, and only when the
/// lookup actually yields something — a font using the private-use area for its own purposes
/// keeps whatever it had.
fn undo_symbol_pua(text: &str) -> String {
    if !text.chars().any(|c| ('\u{F020}'..='\u{F0FF}').contains(&c)) {
        return text.to_string();
    }
    text.chars()
        .map(|c| {
            if !('\u{F020}'..='\u{F0FF}').contains(&c) {
                return c.to_string();
            }
            let code = (u32::from(c) & 0xFF) as u8;
            let name = base_encoding_name(Encoding::Symbol, code);
            glyph_name_to_unicode(name).unwrap_or_else(|| c.to_string())
        })
        .collect()
}

/// Bridges `ttf-parser`'s outline callbacks into our own path builder.
#[derive(Default)]
struct Sink {
    builder: OutlineBuilder,
}

impl Sink {
    fn finish(self, scale: f32, advance: f32) -> Outline {
        let mut cmds = self.builder.finish();
        if (scale - 1.0).abs() > 1e-6 {
            for cmd in &mut cmds {
                scale_cmd(cmd, scale);
            }
        }
        Outline {
            cmds,
            advance,
            is_substitute: false,
        }
    }
}

fn scale_cmd(cmd: &mut glyph::PathCmd, s: f32) {
    use glyph::PathCmd::*;
    let scale_point = |p: &mut crate::geom::Point| {
        p.x *= s;
        p.y *= s;
    };
    match cmd {
        MoveTo(p) | LineTo(p) => scale_point(p),
        CurveTo(a, b, c) => {
            scale_point(a);
            scale_point(b);
            scale_point(c);
        }
        Close => {}
    }
}

impl ttf_parser::OutlineBuilder for Sink {
    fn move_to(&mut self, x: f32, y: f32) {
        self.builder.move_to(x, y);
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.builder.line_to(x, y);
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        // Elevate the quadratic to a cubic so the path type stays uniform: the cubic controls
        // sit two thirds of the way from each endpoint toward the quadratic control point.
        let (x0, y0) = (self.builder.x, self.builder.y);
        self.builder.curve_to(
            x0 + 2.0 / 3.0 * (x1 - x0),
            y0 + 2.0 / 3.0 * (y1 - y0),
            x + 2.0 / 3.0 * (x1 - x),
            y + 2.0 / 3.0 * (y1 - y),
            x,
            y,
        );
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        self.builder.curve_to(x1, y1, x2, y2, x, y);
    }

    fn close(&mut self) {
        self.builder.close();
    }
}

// ---- shared loading helpers -----------------------------------------------------------------

fn load_to_unicode(doc: &Document, dict: &Dict) -> Option<CMap> {
    let stream = doc.dict_get(dict, "ToUnicode")?;
    let decoded = doc.file.decode_stream(stream.as_stream()?).ok()?;
    let map = CMap::parse(&decoded.data);
    map.has_unicode().then_some(map)
}

/// Picks the embedded program out of a font descriptor.
fn load_program(doc: &Document, descriptor: Option<&Dict>) -> Program {
    let Some(desc) = descriptor else {
        return Program::None;
    };
    // `/FontFile` is Type1, whose eexec-encrypted charstrings are not interpreted here, so it
    // yields no outlines; its metrics come from `/Widths` and its encoding from its cleartext
    // header, so both text extraction and layout are unaffected.
    for key in ["FontFile2", "FontFile3", "FontFile"] {
        let Some(obj) = doc.dict_get(desc, key) else {
            continue;
        };
        let Some(stream) = obj.as_stream() else {
            continue;
        };
        let Ok(decoded) = doc.file.decode_stream(stream) else {
            continue;
        };
        let data: Arc<[u8]> = Arc::from(decoded.data.as_slice());
        let subtype = stream.dict.get("Subtype").and_then(|o| o.as_name());
        return match key {
            "FontFile2" => Program::Sfnt(data),
            "FontFile3" => match subtype {
                // An OpenType wrapper is a full sfnt; the bare CFF subtypes are not.
                Some("OpenType") => Program::Sfnt(data),
                _ => Program::Cff(data),
            },
            _ => Program::Type1(data),
        };
    }
    Program::None
}

/// Builds the 256-entry code to glyph-name table for a simple or Type3 font.
///
/// The base table is chosen in the order the specification lays down: the encoding the font
/// dictionary names, else the one the embedded program declares for itself, else a default
/// inferred from the font. `/Differences` is layered over whichever wins.
///
/// The middle step is not optional. A symbolic font may omit `/Encoding` altogether, and TeX's
/// Computer Modern does — `/Flags 4`, no `/Encoding`, no `/ToUnicode`. Skipping to the default
/// then leaves every slot empty, and an entire paper extracts as blank text while its glyphs sit
/// in exactly the right places.
fn build_encoding(
    doc: &Document,
    dict: &Dict,
    base_font: &str,
    symbolic: bool,
    program: &Program,
) -> Vec<String> {
    let encoding_obj = doc.dict_get(dict, "Encoding");

    let named = |n: &str| match n {
        "WinAnsiEncoding" => Some(Encoding::WinAnsi),
        "MacRomanEncoding" => Some(Encoding::MacRoman),
        "StandardEncoding" | "MacExpertEncoding" => Some(Encoding::Standard),
        _ => None,
    };

    let mut base = match &encoding_obj {
        Some(Object::Name(n)) => named(n),
        Some(obj) => obj
            .as_dict()
            .and_then(|d| d.get("BaseEncoding"))
            .and_then(|o| o.as_name())
            .and_then(named),
        None => None,
    };

    // What the program says about itself, consulted only where the dictionary stayed silent.
    let mut names = vec![String::new(); 256];
    let mut from_program = false;
    if base.is_none() {
        match program.builtin_encoding() {
            Some(type1::Builtin::Standard) => base = Some(Encoding::Standard),
            Some(type1::Builtin::Custom(builtin)) => {
                names = builtin;
                from_program = true;
            }
            None => {}
        }
    }

    if base.is_none() && !from_program {
        let lower = base_font.to_ascii_lowercase();
        if lower.contains("symbol") {
            base = Some(Encoding::Symbol);
        } else if !symbolic {
            // A nonsymbolic font with no stated encoding uses the standard one.
            base = Some(Encoding::Standard);
        }
    }

    if let Some(enc) = base {
        for (code, slot) in names.iter_mut().enumerate() {
            *slot = base_encoding_name(enc, code as u8).to_string();
        }
    }

    // `/Differences` is a flat array where each integer restarts the code counter and each name
    // assigns the current code, then advances it.
    if let Some(diffs) = encoding_obj
        .as_ref()
        .and_then(|o| o.as_dict())
        .and_then(|d| doc.dict_get(d, "Differences"))
        .as_ref()
        .and_then(|o| o.as_array())
    {
        let mut code: i64 = 0;
        for item in diffs {
            match doc.resolve(item) {
                Object::Int(i) => code = i,
                Object::Real(r) => code = r as i64,
                Object::Name(n) => {
                    if let Some(slot) = usize::try_from(code).ok().and_then(|c| names.get_mut(c)) {
                        *slot = n;
                    }
                    code += 1;
                }
                _ => {}
            }
        }
    }
    names
}

fn simple_widths(doc: &Document, dict: &Dict, descriptor: Option<&Dict>) -> Widths {
    let first = doc
        .dict_get(dict, "FirstChar")
        .and_then(|o| o.as_int())
        .unwrap_or(0)
        .clamp(0, u32::MAX as i64) as u32;
    let widths: Vec<f32> = doc
        .dict_get(dict, "Widths")
        .as_ref()
        .and_then(|o| o.as_array())
        .map(|a| {
            a.iter()
                .map(|o| doc.resolve(o).as_f32().unwrap_or(0.0))
                .collect()
        })
        .unwrap_or_default();
    let missing = descriptor
        .and_then(|d| doc.dict_get(d, "MissingWidth"))
        .and_then(|o| o.as_f32());
    Widths::Simple {
        first,
        widths,
        missing,
    }
}

/// Parses a CID font's `/W` array: alternating `code [w w ...]` runs and `first last w` ranges.
fn cid_widths(doc: &Document, descendant: &Dict) -> Widths {
    const MAX_RANGE: u32 = 65_536;

    let default = doc
        .dict_get(descendant, "DW")
        .and_then(|o| o.as_f32())
        .unwrap_or(1000.0);
    let mut map = HashMap::new();

    if let Some(w) = doc
        .dict_get(descendant, "W")
        .as_ref()
        .and_then(|o| o.as_array())
    {
        let items: Vec<Object> = w.iter().map(|o| doc.resolve(o)).collect();
        let mut i = 0;
        while i < items.len() {
            let Some(start) = items[i].as_f32().map(|f| f.max(0.0) as u32) else {
                i += 1;
                continue;
            };
            match items.get(i + 1) {
                Some(Object::Array(list)) => {
                    for (k, item) in list.iter().enumerate() {
                        // A `/W` array starting near u32::MAX runs off the end of the CID space.
                        let Some(cid) = start.checked_add(k as u32) else {
                            break;
                        };
                        if let Some(width) = doc.resolve(item).as_f32() {
                            map.insert(cid, width);
                        }
                    }
                    i += 2;
                }
                Some(end_obj) => {
                    let end = end_obj.as_f32().map(|f| f.max(0.0) as u32).unwrap_or(start);
                    let width = items.get(i + 2).and_then(|o| o.as_f32()).unwrap_or(default);
                    // A corrupt range can span the whole CID space; cap the work it can cause.
                    for cid in start..=end.min(start.saturating_add(MAX_RANGE)) {
                        map.insert(cid, width);
                    }
                    i += 3;
                }
                None => break,
            }
        }
    }
    Widths::Cid { default, map }
}

#[cfg(test)]
mod symbol_pua_tests {
    use super::undo_symbol_pua;

    #[test]
    fn microsofts_symbol_range_becomes_real_characters() {
        // Word writes a /ToUnicode that hands back 0xF000 + code for a symbol font, so an
        // equation reading "α = β" arrives as three private-use code points.
        assert_eq!(undo_symbol_pua("\u{F061}"), "α");
        assert_eq!(undo_symbol_pua("\u{F062}"), "β");
        // The Adobe list maps the name `mu` to U+00B5 MICRO SIGN rather than to U+03BC GREEK
        // SMALL LETTER MU, and this follows it. The two render alike and NFKC folds one onto
        // the other, so a consumer comparing text should normalise.
        assert_eq!(undo_symbol_pua("\u{F06D}"), "\u{00B5}");
        assert_eq!(undo_symbol_pua("\u{F03D}"), "=");
        assert_eq!(undo_symbol_pua("\u{F061}\u{F03D}\u{F062}"), "α=β");
    }

    #[test]
    fn ordinary_text_is_untouched() {
        assert_eq!(undo_symbol_pua("hello"), "hello");
        assert_eq!(undo_symbol_pua("α = β"), "α = β");
        assert_eq!(undo_symbol_pua(""), "");
    }

    #[test]
    fn private_use_outside_the_symbol_range_is_left_alone() {
        // Fonts do legitimately use the private-use area for their own glyphs; only the
        // 0xF020..=0xF0FF band carries Microsoft's convention.
        assert_eq!(undo_symbol_pua("\u{E000}"), "\u{E000}");
        assert_eq!(undo_symbol_pua("\u{F8FF}"), "\u{F8FF}");
    }

    #[test]
    fn an_unmapped_symbol_slot_keeps_its_character() {
        // 0xF010 is below the band, and a slot the Symbol encoding does not name must not be
        // silently dropped.
        assert_eq!(undo_symbol_pua("\u{F010}"), "\u{F010}");
    }
}