xberg-native-pdf 1.1.2

PDF parsing, extraction and rendering -- the native PDF engine behind xberg.
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
//! TrueType/OpenType font parser for PDF embedding.
//!
//! This module wraps `skrifa` to extract the font data needed for embedding
//! TrueType fonts in PDF documents with full Unicode support.
//!
//! # Font Embedding in PDF
//!
//! Per PDF spec Section 9.6-9.8, embedded fonts require:
//! - FontDescriptor with metrics (ascender, descender, cap height, etc.)
//! - ToUnicode CMap for text extraction
//! - Font program data (FontFile2 for TrueType)
//! - CIDFont for Unicode (Type 0 composite fonts with Identity-H encoding)

use std::collections::{BTreeSet, HashMap};
use std::io::{self, Write};

use skrifa::instance::{LocationRef, Size};
use skrifa::metrics::{GlyphMetrics, Metrics};
use skrifa::raw::TableProvider;
use skrifa::raw::tables::os2::SelectionFlags;
use skrifa::{FontRef, GlyphId, MetadataProvider};

/// Error types for TrueType font parsing.
#[derive(Debug, thiserror::Error)]
pub enum TrueTypeError {
    /// Failed to parse font file
    #[error("Failed to parse font file: {0}")]
    ParseError(String),

    /// Font file is empty or invalid
    #[error("Font file is empty or invalid")]
    EmptyFont,

    /// Required table is missing
    #[error("Required font table is missing: {0}")]
    MissingTable(String),

    /// IO error during font operations
    #[error("IO error: {0}")]
    IoError(#[from] io::Error),

    /// Glyph not found
    #[error("Glyph not found for character: U+{0:04X}")]
    GlyphNotFound(u32),
}

/// Result type for TrueType operations.
pub type TrueTypeResult<T> = Result<T, TrueTypeError>;

/// Parsed TrueType font data for PDF embedding.
pub struct TrueTypeFont<'a> {
    /// The parsed font
    font: FontRef<'a>,
    /// Face-wide metrics in font units (`Size::unscaled`), resolved once.
    metrics: Metrics,
    /// OS/2 `fsSelection` BOLD bit.
    is_bold: bool,
    /// OS/2 `fsSelection` ITALIC bit, or a non-zero `post` italic angle.
    is_italic: bool,
    /// Original font data (needed for embedding)
    data: &'a [u8],
    /// Cached Unicode to glyph ID mapping
    unicode_to_glyph: HashMap<u32, u16>,
    /// Cached glyph widths (glyph ID -> width in font units)
    glyph_widths: HashMap<u16, u16>,
}

impl<'a> TrueTypeFont<'a> {
    /// Parse a TrueType/OpenType font from raw data.
    ///
    /// # Arguments
    /// * `data` - Raw font file bytes (TTF or OTF)
    ///
    /// # Returns
    /// A parsed TrueType font ready for PDF embedding.
    pub fn parse(data: &'a [u8]) -> TrueTypeResult<Self> {
        if data.is_empty() {
            return Err(TrueTypeError::EmptyFont);
        }

        let font = FontRef::new(data).map_err(|e| TrueTypeError::ParseError(e.to_string()))?;
        let metrics = Metrics::new(&font, Size::unscaled(), LocationRef::default());

        // ttf-parser reported these off OS/2 `fsSelection`, treating a non-zero
        // `post` italic angle as italic even when the bit is clear. Preserved
        // verbatim so embedded FontDescriptor flags do not shift. ~keep
        let selection = font.os2().ok().map(|os2| os2.fs_selection());
        let is_bold = selection.is_some_and(|f| f.contains(SelectionFlags::BOLD));
        let is_italic = selection.is_some_and(|f| f.contains(SelectionFlags::ITALIC)) || metrics.italic_angle != 0.0;

        let mut font = Self {
            font,
            metrics,
            is_bold,
            is_italic,
            data,
            unicode_to_glyph: HashMap::new(),
            glyph_widths: HashMap::new(),
        };

        font.build_unicode_map();
        font.build_width_table();

        Ok(font)
    }

    /// Build Unicode to glyph ID mapping from cmap table.
    fn build_unicode_map(&mut self) {
        // Basic Multilingual Plane (covers virtually all common scripts incl.
        // CJK) plus the emoji supplementary range (U+1F000..=U+1FAFF). Scanning
        // all 17 planes on every font parse would be wasteful and this runs in
        // the extraction hot path; the emoji range is the one supplementary
        // block that occurs routinely in user text (e.g. filled form fields). ~keep
        let charmap = self.font.charmap();
        let ranges = (0..=0xFFFF_u32).chain(0x1F000..=0x1FAFF);
        for codepoint in ranges {
            if let Some(char) = char::from_u32(codepoint)
                && let Some(glyph_id) = charmap.map(char)
            {
                self.unicode_to_glyph.insert(codepoint, glyph_id.to_u32() as u16);
            }
        }
    }

    /// Build glyph width table from hmtx table.
    fn build_width_table(&mut self) {
        let units_per_em = self.metrics.units_per_em;
        if units_per_em == 0 {
            return;
        }
        let glyph_metrics = GlyphMetrics::new(&self.font, Size::unscaled(), LocationRef::default());

        for glyph_id in 0..self.metrics.glyph_count {
            let advance = glyph_metrics
                .advance_width(GlyphId::from(glyph_id))
                .unwrap_or(0.0)
                .max(0.0) as u32;
            let width_1000 = (advance * 1000 / units_per_em as u32) as u16;
            self.glyph_widths.insert(glyph_id, width_1000);
        }
    }

    /// Get the font's PostScript name.
    pub fn postscript_name(&self) -> Option<String> {
        self.localized_name(skrifa::string::StringId::POSTSCRIPT_NAME)
    }

    fn localized_name(&self, id: skrifa::string::StringId) -> Option<String> {
        self.font
            .localized_strings(id)
            .next()
            .map(|name| name.chars().collect())
    }

    /// Get the font family name.
    pub fn family_name(&self) -> Option<String> {
        self.localized_name(skrifa::string::StringId::FAMILY_NAME)
    }

    /// Get units per em for this font.
    pub fn units_per_em(&self) -> u16 {
        self.metrics.units_per_em
    }

    /// Get the ascender in font units.
    pub fn ascender(&self) -> i16 {
        self.metrics.ascent as i16
    }

    /// Get the descender in font units (negative value).
    pub fn descender(&self) -> i16 {
        self.metrics.descent as i16
    }

    /// Get the cap height in font units.
    pub fn cap_height(&self) -> Option<i16> {
        self.metrics.cap_height.map(|v| v as i16)
    }

    /// Get the x-height in font units.
    pub fn x_height(&self) -> Option<i16> {
        self.metrics.x_height.map(|v| v as i16)
    }

    /// Get the italic angle.
    pub fn italic_angle(&self) -> f32 {
        self.metrics.italic_angle
    }

    /// Check if the font is bold.
    pub fn is_bold(&self) -> bool {
        self.is_bold
    }

    /// Check if the font is italic.
    pub fn is_italic(&self) -> bool {
        self.is_italic
    }

    /// Get the font bounding box.
    pub fn bbox(&self) -> (i16, i16, i16, i16) {
        self.metrics
            .bounds
            .map(|b| (b.x_min as i16, b.y_min as i16, b.x_max as i16, b.y_max as i16))
            .unwrap_or((0, 0, 0, 0))
    }

    /// Get glyph ID for a Unicode codepoint.
    pub fn glyph_id(&self, codepoint: u32) -> Option<u16> {
        self.unicode_to_glyph.get(&codepoint).copied()
    }

    /// Get glyph width in 1/1000 em units.
    pub fn glyph_width(&self, glyph_id: u16) -> u16 {
        self.glyph_widths.get(&glyph_id).copied().unwrap_or(500)
    }

    /// Get width for a Unicode character in 1/1000 em units.
    pub fn char_width(&self, codepoint: u32) -> u16 {
        self.glyph_id(codepoint).map(|gid| self.glyph_width(gid)).unwrap_or(500)
    }

    /// Get the number of glyphs in the font.
    pub fn num_glyphs(&self) -> u16 {
        self.metrics.glyph_count
    }

    /// Get the raw font data for embedding.
    pub fn raw_data(&self) -> &[u8] {
        self.data
    }

    /// Get all Unicode codepoints supported by this font.
    pub fn supported_codepoints(&self) -> Vec<u32> {
        let mut codepoints: Vec<_> = self.unicode_to_glyph.keys().copied().collect();
        codepoints.sort();
        codepoints
    }

    /// Calculate StemV (vertical stem width) - estimated from font weight.
    ///
    /// This is a heuristic since TrueType doesn't store StemV directly.
    pub fn stem_v(&self) -> i16 {
        if self.is_bold() { 140 } else { 80 }
    }

    /// Get font flags for PDF FontDescriptor.
    ///
    /// Returns flags per PDF spec Table 123:
    /// - Bit 1: FixedPitch
    /// - Bit 2: Serif (not easily determinable, assume false)
    /// - Bit 3: Symbolic (for Symbol/ZapfDingbats type fonts)
    /// - Bit 4: Script (cursive fonts)
    /// - Bit 6: Nonsymbolic (standard Latin text font)
    /// - Bit 7: Italic
    /// - Bit 17: AllCap
    /// - Bit 18: SmallCap
    /// - Bit 19: ForceBold
    pub fn font_flags(&self) -> u32 {
        let mut flags = 0u32;

        if self.metrics.is_monospace {
            flags |= 1 << 0;
        }

        // Bit 6: Nonsymbolic (standard text font)
        // Most TrueType fonts are nonsymbolic ~keep
        flags |= 1 << 5;

        if self.is_italic() {
            flags |= 1 << 6;
        }

        flags
    }

    /// Generate widths array for PDF CIDFont W entry.
    ///
    /// Format: [start_cid [w1 w2 ...] start_cid2 [w1 w2 ...] ...]
    /// For Identity-H encoding, CID = GID.
    pub fn generate_widths_array(&self, used_glyphs: &BTreeSet<u16>) -> Vec<u8> {
        let mut result = Vec::new();
        write!(result, "[").unwrap();

        let mut glyphs: Vec<_> = used_glyphs.iter().copied().collect();
        glyphs.sort();

        let mut i = 0;
        while i < glyphs.len() {
            let start = glyphs[i];
            let mut end = start;
            let mut widths = vec![self.glyph_width(start)];

            while i + 1 < glyphs.len() && glyphs[i + 1] == end + 1 {
                i += 1;
                end = glyphs[i];
                widths.push(self.glyph_width(end));
            }

            write!(result, "{} [", start).unwrap();
            for (j, w) in widths.iter().enumerate() {
                if j > 0 {
                    write!(result, " ").unwrap();
                }
                write!(result, "{}", w).unwrap();
            }
            write!(result, "]").unwrap();

            i += 1;
        }

        write!(result, "]").unwrap();
        result
    }

    /// Generate ToUnicode CMap for text extraction.
    ///
    /// This CMap maps GIDs (used as CIDs with Identity-H) back to Unicode
    /// so PDF readers can extract text from the generated PDF.
    pub fn generate_tounicode_cmap(&self, used_chars: &HashMap<u32, u16>) -> String {
        let mut cmap = String::new();

        cmap.push_str("/CIDInit /ProcSet findresource begin\n");
        cmap.push_str("12 dict begin\n");
        cmap.push_str("begincmap\n");
        cmap.push_str("/CIDSystemInfo <<\n");
        cmap.push_str("  /Registry (Adobe)\n");
        cmap.push_str("  /Ordering (UCS)\n");
        cmap.push_str("  /Supplement 0\n");
        cmap.push_str(">> def\n");
        cmap.push_str("/CMapName /Adobe-Identity-UCS def\n");
        cmap.push_str("/CMapType 2 def\n");
        cmap.push_str("1 begincodespacerange\n");
        cmap.push_str("<0000> <FFFF>\n");
        cmap.push_str("endcodespacerange\n");

        let mut mappings: Vec<(u16, u32)> = used_chars.iter().map(|(&unicode, &gid)| (gid, unicode)).collect();
        mappings.sort_by_key(|&(gid, _)| gid);

        // Write bfchar entries (max 100 per section per PDF spec) ~keep
        let chunks: Vec<_> = mappings.chunks(100).collect();
        for chunk in chunks {
            cmap.push_str(&format!("{} beginbfchar\n", chunk.len()));
            for &(gid, unicode) in chunk {
                if unicode <= 0xFFFF {
                    cmap.push_str(&format!("<{:04X}> <{:04X}>\n", gid, unicode));
                } else {
                    // Supplementary plane - encode as UTF-16 surrogate pair ~keep
                    let high = ((unicode - 0x10000) >> 10) + 0xD800;
                    let low = ((unicode - 0x10000) & 0x3FF) + 0xDC00;
                    cmap.push_str(&format!("<{:04X}> <{:04X}{:04X}>\n", gid, high, low));
                }
            }
            cmap.push_str("endbfchar\n");
        }

        cmap.push_str("endcmap\n");
        cmap.push_str("CMapName currentdict /CMap defineresource pop\n");
        cmap.push_str("end\n");
        cmap.push_str("end\n");

        cmap
    }
}

/// Font metrics extracted for PDF FontDescriptor.
#[derive(Debug, Clone)]
pub struct FontMetrics {
    /// PostScript name
    pub name: String,
    /// Family name
    pub family: String,
    /// Units per em
    pub units_per_em: u16,
    /// Ascender (positive)
    pub ascender: i16,
    /// Descender (negative)
    pub descender: i16,
    /// Cap height
    pub cap_height: i16,
    /// x-height
    pub x_height: i16,
    /// Italic angle
    pub italic_angle: f32,
    /// Bounding box (llx, lly, urx, ury)
    pub bbox: (i16, i16, i16, i16),
    /// Stem V (vertical stem width)
    pub stem_v: i16,
    /// Font flags
    pub flags: u32,
    /// Is bold
    pub is_bold: bool,
    /// Is italic
    pub is_italic: bool,
}

impl FontMetrics {
    /// Extract metrics from a parsed TrueType font.
    pub fn from_font(font: &TrueTypeFont) -> Self {
        Self {
            name: font.postscript_name().unwrap_or_else(|| "Unknown".to_string()),
            family: font.family_name().unwrap_or_else(|| "Unknown".to_string()),
            units_per_em: font.units_per_em(),
            ascender: font.ascender(),
            descender: font.descender(),
            cap_height: font.cap_height().unwrap_or(font.ascender()),
            x_height: font.x_height().unwrap_or((font.ascender() as f32 * 0.5) as i16),
            italic_angle: font.italic_angle(),
            bbox: font.bbox(),
            stem_v: font.stem_v(),
            flags: font.font_flags(),
            is_bold: font.is_bold(),
            is_italic: font.is_italic(),
        }
    }

    /// Convert a value from font units to PDF units (1/1000 em).
    pub fn to_pdf_units(&self, value: i16) -> i32 {
        (value as i32 * 1000) / self.units_per_em as i32
    }

    /// Get ascender in PDF units.
    pub fn pdf_ascender(&self) -> i32 {
        self.to_pdf_units(self.ascender)
    }

    /// Get descender in PDF units.
    pub fn pdf_descender(&self) -> i32 {
        self.to_pdf_units(self.descender)
    }

    /// Get cap height in PDF units.
    pub fn pdf_cap_height(&self) -> i32 {
        self.to_pdf_units(self.cap_height)
    }

    /// Get bounding box in PDF units.
    pub fn pdf_bbox(&self) -> (i32, i32, i32, i32) {
        (
            self.to_pdf_units(self.bbox.0),
            self.to_pdf_units(self.bbox.1),
            self.to_pdf_units(self.bbox.2),
            self.to_pdf_units(self.bbox.3),
        )
    }
}

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

    #[test]
    fn test_error_on_empty_data() {
        let result = TrueTypeFont::parse(&[]);
        assert!(matches!(result, Err(TrueTypeError::EmptyFont)));
    }

    #[test]
    fn test_error_on_invalid_data() {
        let result = TrueTypeFont::parse(b"not a font file");
        assert!(matches!(result, Err(TrueTypeError::ParseError(_))));
    }

    #[test]
    fn test_font_flags_nonsymbolic() {}

    #[test]
    fn test_tounicode_cmap_format() {
        let mut used_chars = HashMap::new();
        used_chars.insert(0x0041, 1_u16);
        used_chars.insert(0x0042, 2_u16);
    }

    /// Helper to load a font by trying bundled test fixtures first, then system paths.
    fn load_font(name: &str) -> Option<Vec<u8>> {
        let manifest = env!("CARGO_MANIFEST_DIR");
        let candidates = [
            format!("{manifest}/src/fonts/assets/{name}"),
            format!("{manifest}/tests/fixtures/fonts/{name}"),
            format!("/usr/share/fonts/truetype/dejavu/{name}"),
            format!("/usr/share/fonts/dejavu-sans-fonts/{name}"),
            format!("/usr/share/fonts/TTF/{name}"),
        ];
        for path in &candidates {
            if let Ok(data) = std::fs::read(path) {
                return Some(data);
            }
        }
        None
    }

    fn load_dejavu_sans() -> Option<Vec<u8>> {
        load_font("DejaVuSans.ttf")
    }

    fn load_dejavu_sans_bold() -> Option<Vec<u8>> {
        load_font("DejaVuSans-Bold.ttf")
    }

    fn load_dejavu_sans_mono() -> Option<Vec<u8>> {
        load_font("DejaVuSansMono.ttf")
    }

    #[test]
    fn test_parse_valid_font() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data);
        assert!(font.is_ok(), "Failed to parse DejaVu Sans: {:?}", font.err());
    }

    #[test]
    fn test_font_postscript_name() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let ps_name = font.postscript_name();
        if let Some(ref name) = ps_name {
            assert!(!name.is_empty(), "PostScript name should not be empty if present");
        }
    }

    #[test]
    fn test_font_family_name() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let family = font.family_name();
        if let Some(ref name) = family {
            assert!(!name.is_empty(), "Family name should not be empty if present");
        }
    }

    #[test]
    fn test_font_units_per_em() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let upem = font.units_per_em();
        assert!(upem > 0, "Units per em should be positive, got: {}", upem);
    }

    #[test]
    fn test_font_ascender_descender() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let asc = font.ascender();
        let desc = font.descender();
        assert!(asc > 0, "Ascender should be positive, got: {}", asc);
        assert!(desc < 0, "Descender should be negative, got: {}", desc);
    }

    #[test]
    fn test_font_cap_height() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        if let Some(cap_h) = font.cap_height() {
            assert!(cap_h > 0, "Cap height should be positive, got: {}", cap_h);
        }
    }

    #[test]
    fn test_font_x_height() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        if let Some(x_h) = font.x_height() {
            assert!(x_h > 0, "x-height should be positive, got: {}", x_h);
        }
    }

    #[test]
    fn test_font_bbox() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let (x_min, y_min, x_max, y_max) = font.bbox();
        assert!(x_max > x_min, "x_max ({}) should be > x_min ({})", x_max, x_min);
        assert!(y_max > y_min, "y_max ({}) should be > y_min ({})", y_max, y_min);
    }

    #[test]
    fn test_font_italic_angle_regular() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        assert_eq!(font.italic_angle(), 0.0, "Regular font should have italic angle 0");
    }

    #[test]
    fn test_font_is_not_bold_regular() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        assert!(!font.is_bold(), "DejaVu Sans (regular) should not be bold");
    }

    #[test]
    fn test_font_is_bold() {
        let data = match load_dejavu_sans_bold() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        assert!(font.is_bold(), "DejaVu Sans Bold should be bold");
    }

    #[test]
    fn test_font_is_not_italic_regular() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        assert!(!font.is_italic(), "DejaVu Sans (regular) should not be italic");
    }

    #[test]
    fn test_glyph_id_for_ascii() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let gid_a = font.glyph_id(0x0041);
        assert!(gid_a.is_some(), "Glyph for 'A' (U+0041) should exist");
        assert!(gid_a.unwrap() > 0, "GID for 'A' should be > 0 (0 is .notdef)");

        let gid_z = font.glyph_id(0x005A);
        assert!(gid_z.is_some(), "Glyph for 'Z' (U+005A) should exist");
    }

    #[test]
    fn test_glyph_id_nonexistent() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let gid = font.glyph_id(0xFFFD_u32.wrapping_add(1000));
        let _ = gid;
    }

    #[test]
    fn test_glyph_width() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        if let Some(gid) = font.glyph_id(0x0041) {
            let width = font.glyph_width(gid);
            assert!(width > 0, "Width for 'A' should be positive, got: {}", width);
        }
    }

    #[test]
    fn test_glyph_width_default_for_missing() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let width = font.glyph_width(u16::MAX);
        assert_eq!(width, 500, "Missing glyph should return default width 500");
    }

    #[test]
    fn test_char_width() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let w_a = font.char_width(0x0041);
        assert!(w_a > 0, "Width of 'A' should be positive");

        let w_space = font.char_width(0x0020);
        assert!(w_space > 0, "Width of space should be positive");

        let w_big = font.char_width(0x0057);
        let w_small = font.char_width(0x0069);
        assert!(
            w_big > w_small,
            "'W' width ({}) should be > 'i' width ({})",
            w_big,
            w_small
        );
    }

    #[test]
    fn test_num_glyphs() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let n = font.num_glyphs();
        assert!(n > 100, "DejaVu Sans should have many glyphs, got: {}", n);
    }

    #[test]
    fn test_raw_data() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        assert_eq!(font.raw_data().len(), data.len(), "raw_data should match input length");
        assert_eq!(font.raw_data(), data.as_slice(), "raw_data should match input bytes");
    }

    #[test]
    fn test_supported_codepoints() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let codepoints = font.supported_codepoints();
        assert!(
            codepoints.len() > 100,
            "DejaVu Sans should support many codepoints, got: {}",
            codepoints.len()
        );
        for w in codepoints.windows(2) {
            assert!(w[0] <= w[1], "Codepoints should be sorted");
        }
        assert!(codepoints.contains(&0x0041), "Should support 'A' (U+0041)");
    }

    #[test]
    fn test_stem_v_regular_vs_bold() {
        let data_regular = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let data_bold = match load_dejavu_sans_bold() {
            Some(d) => d,
            None => return,
        };
        let font_regular = TrueTypeFont::parse(&data_regular).unwrap();
        let font_bold = TrueTypeFont::parse(&data_bold).unwrap();

        let stem_regular = font_regular.stem_v();
        let stem_bold = font_bold.stem_v();
        assert!(
            stem_regular > 0,
            "Regular stem_v should be positive, got {}",
            stem_regular
        );
        assert!(
            stem_bold > stem_regular,
            "Bold stem_v ({}) should be greater than regular stem_v ({})",
            stem_bold,
            stem_regular
        );
    }

    #[test]
    fn test_font_flags_regular() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let flags = font.font_flags();

        assert!(
            flags & (1 << 5) != 0,
            "Nonsymbolic flag should be set, got flags: {}",
            flags
        );

        assert!(flags & (1 << 6) == 0, "Italic flag should not be set for regular font");
    }

    #[test]
    #[ignore = "DejaVuSansMono.ttf (343 KB) is not vendored in src/fonts/assets or \
                tests/fixtures/fonts, so this can never run against a published crate; \
                run manually with a local copy of the font and --include-ignored"]
    fn test_font_flags_monospace() {
        let data =
            load_dejavu_sans_mono().expect("DejaVuSansMono.ttf must be present locally to run this ignored test");
        let font = TrueTypeFont::parse(&data).unwrap();
        let flags = font.font_flags();

        assert!(
            flags & 1 != 0,
            "FixedPitch flag should be set for monospace font, got flags: {}",
            flags
        );
    }

    #[test]
    fn test_generate_widths_array() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let mut used = BTreeSet::new();
        if let Some(gid_a) = font.glyph_id(0x0041) {
            used.insert(gid_a);
        }
        if let Some(gid_b) = font.glyph_id(0x0042) {
            used.insert(gid_b);
        }
        if let Some(gid_c) = font.glyph_id(0x0043) {
            used.insert(gid_c);
        }

        let widths = font.generate_widths_array(&used);
        let widths_str = String::from_utf8(widths).expect("widths should be valid UTF-8");

        assert!(widths_str.starts_with('['), "Widths array should start with [");
        assert!(widths_str.ends_with(']'), "Widths array should end with ]");
        assert!(widths_str.len() > 2, "Widths array should not be empty");
    }

    #[test]
    fn test_generate_widths_array_empty() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let used = BTreeSet::new();
        let widths = font.generate_widths_array(&used);
        let widths_str = String::from_utf8(widths).expect("widths should be valid UTF-8");
        assert_eq!(widths_str, "[]", "Empty glyph set should produce []");
    }

    #[test]
    fn test_generate_tounicode_cmap_bmp() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let mut used_chars = HashMap::new();
        if let Some(gid) = font.glyph_id(0x0041) {
            used_chars.insert(0x0041_u32, gid);
        }
        if let Some(gid) = font.glyph_id(0x0042) {
            used_chars.insert(0x0042_u32, gid);
        }

        let cmap = font.generate_tounicode_cmap(&used_chars);

        assert!(cmap.contains("begincmap"), "CMap should contain begincmap");
        assert!(cmap.contains("endcmap"), "CMap should contain endcmap");
        assert!(cmap.contains("beginbfchar"), "CMap should contain beginbfchar");
        assert!(cmap.contains("endbfchar"), "CMap should contain endbfchar");
        assert!(cmap.contains("<0041>"), "CMap should contain Unicode for 'A'");
    }

    #[test]
    fn test_generate_tounicode_cmap_supplementary_plane() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let mut used_chars = HashMap::new();
        used_chars.insert(0x1F600_u32, 5000_u16);

        let cmap = font.generate_tounicode_cmap(&used_chars);

        assert!(cmap.contains("begincmap"), "CMap should contain begincmap");
        assert!(
            cmap.contains("<D83D"),
            "CMap should contain high surrogate for supplementary char"
        );
    }

    #[test]
    fn test_generate_tounicode_cmap_empty() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();

        let used_chars = HashMap::new();
        let cmap = font.generate_tounicode_cmap(&used_chars);

        assert!(cmap.contains("begincmap"), "CMap should contain header");
        assert!(cmap.contains("endcmap"), "CMap should contain footer");
        assert!(
            !cmap.contains("beginbfchar"),
            "Empty chars should not produce bfchar section"
        );
    }

    #[test]
    fn test_font_metrics_from_font() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let metrics = FontMetrics::from_font(&font);

        assert!(!metrics.name.is_empty(), "Name should not be empty");
        assert!(!metrics.family.is_empty(), "Family should not be empty");
        assert!(metrics.units_per_em > 0);
        assert!(metrics.ascender > 0);
        assert!(metrics.descender < 0);
        assert!(metrics.cap_height > 0);
        assert!(metrics.x_height > 0);
        assert!(!metrics.is_bold);
        assert!(!metrics.is_italic);
    }

    #[test]
    fn test_font_metrics_to_pdf_units() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let metrics = FontMetrics::from_font(&font);

        let pdf_asc = metrics.pdf_ascender();
        assert!(pdf_asc > 0, "PDF ascender should be positive, got: {}", pdf_asc);

        let pdf_desc = metrics.pdf_descender();
        assert!(pdf_desc < 0, "PDF descender should be negative, got: {}", pdf_desc);

        let pdf_cap = metrics.pdf_cap_height();
        assert!(pdf_cap > 0, "PDF cap height should be positive, got: {}", pdf_cap);
    }

    #[test]
    fn test_font_metrics_pdf_bbox() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let metrics = FontMetrics::from_font(&font);

        let (x_min, y_min, x_max, y_max) = metrics.pdf_bbox();
        assert!(x_max > x_min, "PDF bbox x_max should be > x_min");
        assert!(y_max > y_min, "PDF bbox y_max should be > y_min");
    }

    #[test]
    fn test_font_metrics_to_pdf_units_calculation() {
        let data = match load_dejavu_sans() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let metrics = FontMetrics::from_font(&font);

        let test_value: i16 = 500;
        let expected = (test_value as i32 * 1000) / metrics.units_per_em as i32;
        let actual = metrics.to_pdf_units(test_value);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_font_metrics_bold() {
        let data = match load_dejavu_sans_bold() {
            Some(d) => d,
            None => return,
        };
        let font = TrueTypeFont::parse(&data).unwrap();
        let metrics = FontMetrics::from_font(&font);

        assert!(metrics.is_bold, "Bold font metrics should report is_bold");
        assert_eq!(metrics.stem_v, 140, "Bold stem_v should be 140");
    }

    #[test]
    fn test_truetype_error_display_empty_font() {
        let err = TrueTypeError::EmptyFont;
        let msg = format!("{}", err);
        assert!(msg.contains("empty or invalid"), "Got: {}", msg);
    }

    #[test]
    fn test_truetype_error_display_parse_error() {
        let err = TrueTypeError::ParseError("bad header".to_string());
        let msg = format!("{}", err);
        assert!(msg.contains("bad header"), "Got: {}", msg);
    }

    #[test]
    fn test_truetype_error_display_missing_table() {
        let err = TrueTypeError::MissingTable("cmap".to_string());
        let msg = format!("{}", err);
        assert!(msg.contains("cmap"), "Got: {}", msg);
    }

    #[test]
    fn test_truetype_error_display_glyph_not_found() {
        let err = TrueTypeError::GlyphNotFound(0x1234);
        let msg = format!("{}", err);
        assert!(msg.contains("1234"), "Got: {}", msg);
    }

    #[test]
    fn test_truetype_error_io_conversion() {
        let io_err = io::Error::new(io::ErrorKind::NotFound, "file missing");
        let tt_err: TrueTypeError = io_err.into();
        assert!(matches!(tt_err, TrueTypeError::IoError(_)));
        let msg = format!("{}", tt_err);
        assert!(msg.contains("file missing"), "Got: {}", msg);
    }

    #[test]
    fn test_parse_truncated_data() {
        let truncated = vec![0x00, 0x01, 0x00, 0x00];
        let result = TrueTypeFont::parse(&truncated);
        assert!(result.is_err(), "Truncated font data should fail to parse");
    }

    #[test]
    fn test_parse_random_bytes() {
        let random_data = vec![0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE, 0x00, 0x00];
        let result = TrueTypeFont::parse(&random_data);
        assert!(result.is_err(), "Random bytes should fail to parse as font");
    }
}