oxidize-pdf 2.8.0

A pure Rust PDF generation and manipulation library with zero external dependencies
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
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
use crate::text::Font;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Character width information for standard PDF fonts
/// All widths are in 1/1000 of a unit (font size 1.0)
#[derive(Clone, Debug)]
pub struct FontMetrics {
    widths: HashMap<char, u16>,
    default_width: u16,
}

impl FontMetrics {
    pub fn new(default_width: u16) -> Self {
        Self {
            widths: HashMap::new(),
            default_width,
        }
    }

    pub fn with_widths(mut self, widths: &[(char, u16)]) -> Self {
        for &(ch, width) in widths {
            self.widths.insert(ch, width);
        }
        self
    }

    /// Create metrics from a pre-built character width map
    pub fn from_char_map(widths: HashMap<char, u16>, default_width: u16) -> Self {
        Self {
            widths,
            default_width,
        }
    }

    pub fn char_width(&self, ch: char) -> u16 {
        self.widths.get(&ch).copied().unwrap_or(self.default_width)
    }
}

/// Per-Document store of custom font metrics.
///
/// Cheap to clone (Arc-backed). The lifetime of registered metrics is bound
/// to the lifetime of the owning Document — when the Document is dropped,
/// the metrics are freed (assuming no other Arc clones survive).
///
/// This type was introduced in v2.8.0 to replace the process-wide
/// `CUSTOM_FONT_METRICS` lazy_static registry, which leaked across
/// Document lifetimes (issue #230).
#[derive(Clone, Debug)]
pub struct FontMetricsStore {
    inner: Arc<RwLock<HashMap<String, Arc<FontMetrics>>>>,
}

impl FontMetricsStore {
    /// Create a new empty store.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Register or replace metrics for `font_name`. Last-writer-wins on the
    /// same name. Concurrent calls into the same store are serialised by the
    /// internal RwLock; concurrent calls into the same Document are
    /// prevented by `Document::add_font_from_bytes` taking `&mut self`.
    pub fn register(&self, font_name: impl Into<String>, metrics: FontMetrics) {
        let name = font_name.into();
        match self.inner.write() {
            Ok(mut map) => {
                map.insert(name, Arc::new(metrics));
            }
            Err(e) => {
                tracing::warn!(
                    "FontMetricsStore lock is poisoned; could not register '{}': {}",
                    name,
                    e
                );
            }
        }
    }

    /// Look up metrics by name. Returns `None` on miss; no side effects.
    pub fn get(&self, font_name: &str) -> Option<Arc<FontMetrics>> {
        let map = self.inner.read().ok()?;
        map.get(font_name).cloned()
    }

    /// Number of registered fonts. Diagnostic / test introspection.
    pub fn len(&self) -> usize {
        self.inner.read().map(|m| m.len()).unwrap_or(0)
    }

    /// Whether the store contains no fonts.
    pub fn is_empty(&self) -> bool {
        self.inner.read().map(|m| m.is_empty()).unwrap_or(true)
    }
}

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

// Dynamic registry for custom font metrics
lazy_static::lazy_static! {
    static ref CUSTOM_FONT_METRICS: RwLock<HashMap<String, FontMetrics>> =
        RwLock::new(HashMap::new());
}

lazy_static::lazy_static! {
    static ref FONT_METRICS: HashMap<Font, FontMetrics> = {
        let mut metrics = HashMap::new();

        // Helvetica
        metrics.insert(Font::Helvetica, FontMetrics::new(556).with_widths(&[
            (' ', 278), ('!', 278), ('"', 355), ('#', 556), ('$', 556), ('%', 889),
            ('&', 667), ('\'', 191), ('(', 333), (')', 333), ('*', 389), ('+', 584),
            (',', 278), ('-', 333), ('.', 278), ('/', 278), ('0', 556), ('1', 556),
            ('2', 556), ('3', 556), ('4', 556), ('5', 556), ('6', 556), ('7', 556),
            ('8', 556), ('9', 556), (':', 278), (';', 278), ('<', 584), ('=', 584),
            ('>', 584), ('?', 556), ('@', 1015), ('A', 667), ('B', 667), ('C', 722),
            ('D', 722), ('E', 667), ('F', 611), ('G', 778), ('H', 722), ('I', 278),
            ('J', 500), ('K', 667), ('L', 556), ('M', 833), ('N', 722), ('O', 778),
            ('P', 667), ('Q', 778), ('R', 722), ('S', 667), ('T', 611), ('U', 722),
            ('V', 667), ('W', 944), ('X', 667), ('Y', 667), ('Z', 611), ('[', 278),
            ('\\', 278), (']', 278), ('^', 469), ('_', 556), ('`', 333), ('a', 556),
            ('b', 556), ('c', 500), ('d', 556), ('e', 556), ('f', 278), ('g', 556),
            ('h', 556), ('i', 222), ('j', 222), ('k', 500), ('l', 222), ('m', 833),
            ('n', 556), ('o', 556), ('p', 556), ('q', 556), ('r', 333), ('s', 500),
            ('t', 278), ('u', 556), ('v', 500), ('w', 722), ('x', 500), ('y', 500),
            ('z', 500), ('{', 334), ('|', 260), ('}', 334), ('~', 584),
        ]));

        // Helvetica Bold
        metrics.insert(Font::HelveticaBold, FontMetrics::new(611).with_widths(&[
            (' ', 278), ('!', 333), ('"', 474), ('#', 556), ('$', 556), ('%', 889),
            ('&', 722), ('\'', 238), ('(', 333), (')', 333), ('*', 389), ('+', 584),
            (',', 278), ('-', 333), ('.', 278), ('/', 278), ('0', 556), ('1', 556),
            ('2', 556), ('3', 556), ('4', 556), ('5', 556), ('6', 556), ('7', 556),
            ('8', 556), ('9', 556), (':', 333), (';', 333), ('<', 584), ('=', 584),
            ('>', 584), ('?', 611), ('@', 975), ('A', 722), ('B', 722), ('C', 722),
            ('D', 722), ('E', 667), ('F', 611), ('G', 778), ('H', 722), ('I', 278),
            ('J', 556), ('K', 722), ('L', 611), ('M', 833), ('N', 722), ('O', 778),
            ('P', 667), ('Q', 778), ('R', 722), ('S', 667), ('T', 611), ('U', 722),
            ('V', 667), ('W', 944), ('X', 667), ('Y', 667), ('Z', 611), ('[', 333),
            ('\\', 278), (']', 333), ('^', 584), ('_', 556), ('`', 333), ('a', 556),
            ('b', 611), ('c', 556), ('d', 611), ('e', 556), ('f', 333), ('g', 611),
            ('h', 611), ('i', 278), ('j', 278), ('k', 556), ('l', 278), ('m', 889),
            ('n', 611), ('o', 611), ('p', 611), ('q', 611), ('r', 389), ('s', 556),
            ('t', 333), ('u', 611), ('v', 556), ('w', 778), ('x', 556), ('y', 556),
            ('z', 500), ('{', 389), ('|', 280), ('}', 389), ('~', 584),
        ]));

        // Times Roman
        metrics.insert(Font::TimesRoman, FontMetrics::new(500).with_widths(&[
            (' ', 250), ('!', 333), ('"', 408), ('#', 500), ('$', 500), ('%', 833),
            ('&', 778), ('\'', 180), ('(', 333), (')', 333), ('*', 500), ('+', 564),
            (',', 250), ('-', 333), ('.', 250), ('/', 278), ('0', 500), ('1', 500),
            ('2', 500), ('3', 500), ('4', 500), ('5', 500), ('6', 500), ('7', 500),
            ('8', 500), ('9', 500), (':', 278), (';', 278), ('<', 564), ('=', 564),
            ('>', 564), ('?', 444), ('@', 921), ('A', 722), ('B', 667), ('C', 667),
            ('D', 722), ('E', 611), ('F', 556), ('G', 722), ('H', 722), ('I', 333),
            ('J', 389), ('K', 722), ('L', 611), ('M', 889), ('N', 722), ('O', 722),
            ('P', 556), ('Q', 722), ('R', 667), ('S', 556), ('T', 611), ('U', 722),
            ('V', 722), ('W', 944), ('X', 722), ('Y', 722), ('Z', 611), ('[', 333),
            ('\\', 278), (']', 333), ('^', 469), ('_', 500), ('`', 333), ('a', 444),
            ('b', 500), ('c', 444), ('d', 500), ('e', 444), ('f', 333), ('g', 500),
            ('h', 500), ('i', 278), ('j', 278), ('k', 500), ('l', 278), ('m', 778),
            ('n', 500), ('o', 500), ('p', 500), ('q', 500), ('r', 333), ('s', 389),
            ('t', 278), ('u', 500), ('v', 500), ('w', 722), ('x', 500), ('y', 500),
            ('z', 444), ('{', 480), ('|', 200), ('}', 480), ('~', 541),
        ]));

        // Courier (all characters have the same width)
        metrics.insert(Font::Courier, FontMetrics::new(600).with_widths(&[
            (' ', 600), ('!', 600), ('"', 600), ('#', 600), ('$', 600), ('%', 600),
            ('&', 600), ('\'', 600), ('(', 600), (')', 600), ('*', 600), ('+', 600),
            (',', 600), ('-', 600), ('.', 600), ('/', 600), ('0', 600), ('1', 600),
            ('2', 600), ('3', 600), ('4', 600), ('5', 600), ('6', 600), ('7', 600),
            ('8', 600), ('9', 600), (':', 600), (';', 600), ('<', 600), ('=', 600),
            ('>', 600), ('?', 600), ('@', 600), ('A', 600), ('B', 600), ('C', 600),
            ('D', 600), ('E', 600), ('F', 600), ('G', 600), ('H', 600), ('I', 600),
            ('J', 600), ('K', 600), ('L', 600), ('M', 600), ('N', 600), ('O', 600),
            ('P', 600), ('Q', 600), ('R', 600), ('S', 600), ('T', 600), ('U', 600),
            ('V', 600), ('W', 600), ('X', 600), ('Y', 600), ('Z', 600), ('[', 600),
            ('\\', 600), (']', 600), ('^', 600), ('_', 600), ('`', 600), ('a', 600),
            ('b', 600), ('c', 600), ('d', 600), ('e', 600), ('f', 600), ('g', 600),
            ('h', 600), ('i', 600), ('j', 600), ('k', 600), ('l', 600), ('m', 600),
            ('n', 600), ('o', 600), ('p', 600), ('q', 600), ('r', 600), ('s', 600),
            ('t', 600), ('u', 600), ('v', 600), ('w', 600), ('x', 600), ('y', 600),
            ('z', 600), ('{', 600), ('|', 600), ('}', 600), ('~', 600),
        ]));

        // For now, use the same metrics for variations
        metrics.insert(Font::HelveticaOblique, metrics[&Font::Helvetica].clone());
        metrics.insert(Font::HelveticaBoldOblique, metrics[&Font::HelveticaBold].clone());
        metrics.insert(Font::TimesBold, metrics[&Font::TimesRoman].clone());
        metrics.insert(Font::TimesItalic, metrics[&Font::TimesRoman].clone());
        metrics.insert(Font::TimesBoldItalic, metrics[&Font::TimesRoman].clone());
        metrics.insert(Font::CourierBold, metrics[&Font::Courier].clone());
        metrics.insert(Font::CourierOblique, metrics[&Font::Courier].clone());
        metrics.insert(Font::CourierBoldOblique, metrics[&Font::Courier].clone());

        metrics
    };
}

/// Measure the width of a text string in a given font and size.
///
/// Variant of `measure_text` that consults a `FontMetricsStore` for
/// `Font::Custom` lookups before falling back to the legacy global
/// registry. Used internally by `TextFlowContext`, `TextContext`, and
/// `measure_text_block_with` to scope measurement to a single Document.
pub fn measure_text_with(
    text: &str,
    font: &Font,
    font_size: f64,
    store: Option<&FontMetricsStore>,
) -> f64 {
    if font.is_symbolic() {
        return text.len() as f64 * font_size * 0.6;
    }
    let metrics = lookup(font, store);
    let width_units: u32 = text.chars().map(|ch| metrics.char_width(ch) as u32).sum();
    (width_units as f64 / 1000.0) * font_size
}

/// Measure the width of a text string in a given font and size.
///
/// Back-compat shim. Delegates to `measure_text_with(text, font, font_size, None)`.
/// Custom fonts not registered globally fall back to default widths plus a
/// rate-limited diagnostic warning. For new code, prefer `measure_text_with`
/// or use `Document::new_page_a4()` so the measurement context carries a
/// `FontMetricsStore` automatically.
#[inline]
pub fn measure_text(text: &str, font: &Font, font_size: f64) -> f64 {
    measure_text_with(text, font, font_size, None)
}

/// Measure the width of a single character in a given font and size.
///
/// Variant of `measure_char` that consults a `FontMetricsStore` for
/// `Font::Custom` lookups before falling back to the legacy global
/// registry. Takes the font by value (matching the existing
/// `measure_char` signature, which predates this scope-aware variant).
pub fn measure_char_with(
    ch: char,
    font: Font,
    font_size: f64,
    store: Option<&FontMetricsStore>,
) -> f64 {
    if font.is_symbolic() {
        return font_size * 0.6;
    }
    let metrics = lookup(&font, store);
    (metrics.char_width(ch) as f64 / 1000.0) * font_size
}

/// Back-compat shim — see `measure_char_with`.
#[inline]
pub fn measure_char(ch: char, font: Font, font_size: f64) -> f64 {
    measure_char_with(ch, font, font_size, None)
}

/// Split text into words, preserving spaces
pub fn split_into_words(text: &str) -> Vec<&str> {
    let mut words = Vec::new();
    let mut start = 0;
    let mut in_space = false;

    for (i, ch) in text.char_indices() {
        if ch.is_whitespace() {
            if !in_space {
                if i > start {
                    words.push(&text[start..i]);
                }
                start = i;
                in_space = true;
            }
        } else if in_space {
            if i > start {
                words.push(&text[start..i]);
            }
            start = i;
            in_space = false;
        }
    }

    if start < text.len() {
        words.push(&text[start..]);
    }

    words
}

/// Register metrics for a custom font
#[deprecated(
    since = "2.8.0",
    note = "use Document::add_font_from_bytes; the global registry is process-wide and not bounded — see issue #230"
)]
pub fn register_custom_font_metrics(font_name: String, metrics: FontMetrics) {
    match CUSTOM_FONT_METRICS.write() {
        Ok(mut custom_metrics) => {
            custom_metrics.insert(font_name, metrics);
        }
        Err(e) => {
            tracing::warn!(
                "Font metrics registry lock is poisoned; \
                 could not register metrics for font '{}': {}",
                font_name,
                e
            );
        }
    }
}

/// Get metrics for a custom font
#[deprecated(
    since = "2.8.0",
    note = "use FontMetricsStore::get via a Document — the global registry is process-wide and not bounded — see issue #230"
)]
pub fn get_custom_font_metrics(font_name: &str) -> Option<FontMetrics> {
    if let Ok(custom_metrics) = CUSTOM_FONT_METRICS.read() {
        custom_metrics.get(font_name).cloned()
    } else {
        None
    }
}

/// Look up font metrics for any font (standard or custom).
///
/// Resolution order for `Font::Custom(name)`:
/// 1. Document scope (`store`) — takes precedence when present.
/// 2. Legacy global registry — hierarchical fallback (deprecated in Task 12 of #230).
/// 3. Default metrics + rate-limited warning via `warn_unknown_custom_font_once`.
///
/// Read path only — no side effects on either registry.
fn lookup(font: &Font, store: Option<&FontMetricsStore>) -> FontMetrics {
    match font {
        Font::Custom(font_name) => {
            // 1. Document scope (precedence)
            if let Some(s) = store {
                if let Some(arc_m) = s.get(font_name) {
                    return (*arc_m).clone();
                }
            }
            // 2. Legacy global (deprecated, hierarchical fallback)
            if let Some(custom_metrics) = get_custom_font_metrics_internal(font_name) {
                return custom_metrics;
            }
            // 3. Default + warn-once
            warn_unknown_custom_font_once(font_name);
            (*default_custom_metrics_arc()).clone()
        }
        _ => FONT_METRICS.get(font).cloned().unwrap_or_else(|| {
            tracing::debug!(
                "Warning: Standard font metrics not found for {:?}, using default",
                font
            );
            (*default_custom_metrics_arc()).clone()
        }),
    }
}

/// Internal accessor for the legacy global registry. Wraps
/// `get_custom_font_metrics` (which Task 12 of #230 will mark `#[deprecated]`)
/// so the lookup path does not itself produce a deprecation warning at
/// every internal call site once Task 12 lands.
fn get_custom_font_metrics_internal(font_name: &str) -> Option<FontMetrics> {
    if let Ok(custom_metrics) = CUSTOM_FONT_METRICS.read() {
        custom_metrics.get(font_name).cloned()
    } else {
        None
    }
}

lazy_static::lazy_static! {
    /// Cached default metrics for unknown custom fonts. Building this map
    /// once (lazy_static) means subsequent fallbacks reuse the same data
    /// rather than rebuilding the CJK table on every miss.
    static ref DEFAULT_CUSTOM_METRICS_ARC: Arc<FontMetrics> =
        Arc::new(create_default_custom_metrics());
}

fn default_custom_metrics_arc() -> Arc<FontMetrics> {
    DEFAULT_CUSTOM_METRICS_ARC.clone()
}

lazy_static::lazy_static! {
    /// Names already warned about. Rate-limits the unknown-font warning to
    /// one emission per name per process.
    static ref WARNED_UNKNOWN_FONTS: RwLock<std::collections::HashSet<String>> =
        RwLock::new(std::collections::HashSet::new());
}

fn warn_unknown_custom_font_once(font_name: &str) {
    {
        if let Ok(set) = WARNED_UNKNOWN_FONTS.read() {
            if set.contains(font_name) {
                return;
            }
        }
    }
    if let Ok(mut set) = WARNED_UNKNOWN_FONTS.write() {
        if set.insert(font_name.to_string()) {
            tracing::warn!(
                "custom font '{}' measured but not registered; widths will use \
                 defaults — register via Document::add_font_from_bytes",
                font_name
            );
        }
    }
}

/// Create default metrics for a custom font (fallback when no specific metrics available).
/// Result is cached via `lazy_static` — the expensive CJK range insertion (~6,500 entries)
/// only happens once. Subsequent calls return a clone.
pub(crate) fn create_default_custom_metrics() -> FontMetrics {
    lazy_static::lazy_static! {
        static ref DEFAULT_CUSTOM_METRICS: FontMetrics = build_default_custom_metrics();
    }
    DEFAULT_CUSTOM_METRICS.clone()
}

fn build_default_custom_metrics() -> FontMetrics {
    let mut metrics = FontMetrics::new(556).with_widths(&[
        (' ', 278),
        ('!', 278),
        ('"', 355),
        ('#', 556),
        ('$', 556),
        ('%', 889),
        ('&', 667),
        ('\'', 191),
        ('(', 333),
        (')', 333),
        ('*', 389),
        ('+', 584),
        (',', 278),
        ('-', 333),
        ('.', 278),
        ('/', 278),
        ('0', 556),
        ('1', 556),
        ('2', 556),
        ('3', 556),
        ('4', 556),
        ('5', 556),
        ('6', 556),
        ('7', 556),
        ('8', 556),
        ('9', 556),
        (':', 278),
        (';', 278),
        ('<', 584),
        ('=', 584),
        ('>', 584),
        ('?', 556),
        ('@', 1015),
        ('A', 667),
        ('B', 667),
        ('C', 722),
        ('D', 722),
        ('E', 667),
        ('F', 611),
        ('G', 778),
        ('H', 722),
        ('I', 278),
        ('J', 500),
        ('K', 667),
        ('L', 556),
        ('M', 833),
        ('N', 722),
        ('O', 778),
        ('P', 667),
        ('Q', 778),
        ('R', 722),
        ('S', 667),
        ('T', 611),
        ('U', 722),
        ('V', 667),
        ('W', 944),
        ('X', 667),
        ('Y', 667),
        ('Z', 611),
        ('[', 278),
        ('\\', 278),
        (']', 278),
        ('^', 469),
        ('_', 556),
        ('`', 333),
        ('a', 556),
        ('b', 556),
        ('c', 500),
        ('d', 556),
        ('e', 556),
        ('f', 278),
        ('g', 556),
        ('h', 556),
        ('i', 222),
        ('j', 222),
        ('k', 500),
        ('l', 222),
        ('m', 833),
        ('n', 556),
        ('o', 556),
        ('p', 556),
        ('q', 556),
        ('r', 333),
        ('s', 500),
        ('t', 278),
        ('u', 556),
        ('v', 500),
        ('w', 722),
        ('x', 500),
        ('y', 500),
        ('z', 500),
        ('{', 334),
        ('|', 260),
        ('}', 334),
        ('~', 584),
    ]);

    // CJK characters are full-width (1000 units). Insert defaults for common ranges
    // so that even without registered font metrics, CJK text measurement is reasonable.
    let cjk_ranges: &[(u32, u32)] = &[
        (0x3000, 0x303F), // CJK Symbols and Punctuation
        (0x3040, 0x309F), // Hiragana
        (0x30A0, 0x30FF), // Katakana
        (0x4E00, 0x9FFF), // CJK Unified Ideographs
        (0xF900, 0xFAFF), // CJK Compatibility Ideographs
        (0xFF00, 0xFFEF), // Halfwidth and Fullwidth Forms
    ];
    for &(start, end) in cjk_ranges {
        for code_point in start..=end {
            if let Some(ch) = char::from_u32(code_point) {
                metrics.widths.insert(ch, 1000);
            }
        }
    }

    metrics
}

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

    #[test]
    fn test_font_metrics_creation() {
        let metrics = FontMetrics::new(500);
        assert_eq!(metrics.default_width, 500);
        assert!(metrics.widths.is_empty());
    }

    #[test]
    fn test_font_metrics_with_widths() {
        let widths = [('A', 600), ('B', 700), ('C', 650)];
        let metrics = FontMetrics::new(500).with_widths(&widths);

        assert_eq!(metrics.char_width('A'), 600);
        assert_eq!(metrics.char_width('B'), 700);
        assert_eq!(metrics.char_width('C'), 650);
        assert_eq!(metrics.char_width('Z'), 500); // Default for unmapped
    }

    #[test]
    fn test_font_metrics_clone() {
        let widths = [('A', 600), ('B', 700)];
        let metrics1 = FontMetrics::new(500).with_widths(&widths);
        let metrics2 = metrics1.clone();

        assert_eq!(metrics1.char_width('A'), metrics2.char_width('A'));
        assert_eq!(metrics1.default_width, metrics2.default_width);
    }

    #[test]
    fn test_measure_text_helvetica() {
        let text = "Hello";
        let width = measure_text(text, &Font::Helvetica, 12.0);

        // Helvetica "H" = 722, "e" = 556, "l" = 222, "l" = 222, "o" = 556
        // Total = 2278 units = 2.278 at size 1.0, * 12.0 = 27.336
        assert!((width - 27.336).abs() < 0.01);
    }

    #[test]
    fn test_measure_text_courier() {
        let text = "ABC";
        let width = measure_text(text, &Font::Courier, 10.0);

        // Courier is monospace: all chars = 600 units
        // 3 chars * 600 = 1800 units = 1.8 at size 1.0, * 10.0 = 18.0
        assert_eq!(width, 18.0);
    }

    #[test]
    fn test_measure_text_symbolic_fonts() {
        let text = "ABC";
        let symbol_width = measure_text(text, &Font::Symbol, 12.0);
        let zapf_width = measure_text(text, &Font::ZapfDingbats, 12.0);

        // Symbolic fonts use approximation: len * font_size * 0.6
        let expected = 3.0 * 12.0 * 0.6; // = 21.6
        assert_eq!(symbol_width, expected);
        assert_eq!(zapf_width, expected);
    }

    #[test]
    fn test_measure_char_helvetica() {
        let width = measure_char('A', Font::Helvetica, 12.0);

        // Helvetica "A" = 667 units = 0.667 at size 1.0, * 12.0 = 8.004
        assert!((width - 8.004).abs() < 0.01);
    }

    #[test]
    fn test_measure_char_courier() {
        let width = measure_char('X', Font::Courier, 10.0);

        // Courier "X" = 600 units = 0.6 at size 1.0, * 10.0 = 6.0
        assert_eq!(width, 6.0);
    }

    #[test]
    fn test_measure_char_symbolic() {
        let symbol_width = measure_char('A', Font::Symbol, 15.0);
        let zapf_width = measure_char('B', Font::ZapfDingbats, 15.0);

        // Symbolic fonts: font_size * 0.6
        let expected = 15.0 * 0.6; // = 9.0
        assert_eq!(symbol_width, expected);
        assert_eq!(zapf_width, expected);
    }

    #[test]
    fn test_split_into_words_simple() {
        let text = "Hello World";
        let words = split_into_words(text);

        assert_eq!(words, vec!["Hello", " ", "World"]);
    }

    #[test]
    fn test_split_into_words_multiple_spaces() {
        let text = "Hello   World";
        let words = split_into_words(text);

        assert_eq!(words, vec!["Hello", "   ", "World"]);
    }

    #[test]
    fn test_split_into_words_leading_trailing_spaces() {
        let text = " Hello World ";
        let words = split_into_words(text);

        assert_eq!(words, vec![" ", "Hello", " ", "World", " "]);
    }

    #[test]
    fn test_split_into_words_tabs_newlines() {
        let text = "Hello\tWorld\nTest";
        let words = split_into_words(text);

        assert_eq!(words, vec!["Hello", "\t", "World", "\n", "Test"]);
    }

    #[test]
    fn test_split_into_words_empty() {
        let text = "";
        let words = split_into_words(text);

        assert!(words.is_empty());
    }

    #[test]
    fn test_split_into_words_only_spaces() {
        let text = "   ";
        let words = split_into_words(text);

        assert_eq!(words, vec!["   "]);
    }

    #[test]
    fn test_split_into_words_single_word() {
        let text = "Hello";
        let words = split_into_words(text);

        assert_eq!(words, vec!["Hello"]);
    }

    #[test]
    fn test_all_font_metrics_exist() {
        let fonts = [
            Font::Helvetica,
            Font::HelveticaBold,
            Font::HelveticaOblique,
            Font::HelveticaBoldOblique,
            Font::TimesRoman,
            Font::TimesBold,
            Font::TimesItalic,
            Font::TimesBoldItalic,
            Font::Courier,
            Font::CourierBold,
            Font::CourierOblique,
            Font::CourierBoldOblique,
        ];

        for font in &fonts {
            // Should not panic - all fonts should have metrics
            let _width = measure_text("A", font, 12.0);
        }
    }

    #[test]
    fn test_helvetica_specific_characters() {
        let chars = [
            (' ', 278),
            ('A', 667),
            ('B', 667),
            ('C', 722),
            ('a', 556),
            ('b', 556),
            ('0', 556),
            ('1', 556),
            ('@', 1015),
            ('M', 833),
            ('W', 944),
            ('i', 222),
        ];

        for (ch, expected_width) in &chars {
            let width = measure_char(*ch, Font::Helvetica, 1000.0);
            let expected = *expected_width as f64;
            assert!(
                (width - expected).abs() < 0.1,
                "Character '{ch}' width mismatch: {width} vs {expected}"
            );
        }
    }

    #[test]
    fn test_times_specific_characters() {
        let chars = [
            (' ', 250),
            ('A', 722),
            ('B', 667),
            ('C', 667),
            ('a', 444),
            ('b', 500),
            ('0', 500),
            ('1', 500),
            ('@', 921),
            ('M', 889),
            ('W', 944),
            ('i', 278),
        ];

        for (ch, expected_width) in &chars {
            let width = measure_char(*ch, Font::TimesRoman, 1000.0);
            let expected = *expected_width as f64;
            assert_eq!(width, expected, "Character '{ch}' width mismatch");
        }
    }

    #[test]
    fn test_courier_monospace_property() {
        let chars = [
            ' ', 'A', 'B', 'C', 'a', 'b', '0', '1', '@', 'M', 'W', 'i', '~',
        ];

        for ch in &chars {
            let width = measure_char(*ch, Font::Courier, 1000.0);
            assert_eq!(width, 600.0, "Courier character '{ch}' should be 600 units");
        }
    }

    #[test]
    fn test_font_size_scaling() {
        let sizes = [6.0, 12.0, 18.0, 24.0, 36.0];

        for size in &sizes {
            let width = measure_char('A', Font::Helvetica, *size);
            let expected = 667.0 * size / 1000.0; // Helvetica 'A' = 667 units
            assert!(
                (width - expected).abs() < 0.01,
                "Size {size} scaling incorrect"
            );
        }
    }

    #[test]
    fn test_measure_text_empty_string() {
        let width = measure_text("", &Font::Helvetica, 12.0);
        assert_eq!(width, 0.0);
    }

    #[test]
    fn test_measure_text_consistency() {
        let text = "Hello";

        // Measuring whole text should equal sum of individual characters
        let total_width = measure_text(text, &Font::Helvetica, 12.0);
        let individual_sum: f64 = text
            .chars()
            .map(|ch| measure_char(ch, Font::Helvetica, 12.0))
            .sum();

        assert!((total_width - individual_sum).abs() < 0.01);
    }

    #[test]
    fn test_font_variants_use_base_metrics() {
        // Test that font variations use the base font metrics
        let base_width = measure_char('A', Font::Helvetica, 12.0);
        let oblique_width = measure_char('A', Font::HelveticaOblique, 12.0);
        let bold_oblique_width = measure_char('A', Font::HelveticaBoldOblique, 12.0);

        // Should use same metrics (though in reality, they'd be different)
        assert_eq!(base_width, oblique_width);

        let bold_width = measure_char('A', Font::HelveticaBold, 12.0);
        assert_eq!(bold_width, bold_oblique_width);
    }

    #[test]
    fn test_unicode_characters_default_width() {
        // Test characters not in the metrics tables
        let unicode_chars = ['β', 'π', '', ''];

        for ch in &unicode_chars {
            let helvetica_width = measure_char(*ch, Font::Helvetica, 12.0);
            let times_width = measure_char(*ch, Font::TimesRoman, 12.0);
            let courier_width = measure_char(*ch, Font::Courier, 12.0);

            // Should use default widths
            let helvetica_expected = 556.0 * 12.0 / 1000.0;
            let times_expected = 500.0 * 12.0 / 1000.0;
            let courier_expected = 600.0 * 12.0 / 1000.0;

            assert!(
                (helvetica_width - helvetica_expected).abs() < 0.01,
                "Helvetica width mismatch"
            );
            assert!(
                (times_width - times_expected).abs() < 0.01,
                "Times width mismatch"
            );
            assert!(
                (courier_width - courier_expected).abs() < 0.01,
                "Courier width mismatch"
            );
        }
    }

    #[test]
    #[allow(deprecated)]
    fn test_register_custom_font_metrics() {
        let metrics = FontMetrics::new(750).with_widths(&[('A', 800), ('B', 850)]);
        register_custom_font_metrics("TestFont".to_string(), metrics);

        let retrieved = get_custom_font_metrics("TestFont");
        assert!(retrieved.is_some());

        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved.char_width('A'), 800);
        assert_eq!(retrieved.char_width('B'), 850);
        assert_eq!(retrieved.char_width('Z'), 750); // default
    }

    #[test]
    #[allow(deprecated)]
    fn test_get_custom_font_metrics_not_found() {
        let result = get_custom_font_metrics("NonExistentFont12345");
        // May or may not be found depending on previous tests
        // Just verify no panic
        let _ = result;
    }

    #[test]
    #[allow(deprecated)]
    fn test_measure_text_custom_font() {
        // Register a custom font with known metrics
        let metrics = FontMetrics::new(500).with_widths(&[('A', 600), ('B', 600), ('C', 600)]);
        register_custom_font_metrics("MyCustomFont".to_string(), metrics);

        let width = measure_text("ABC", &Font::Custom("MyCustomFont".to_string()), 10.0);

        // 3 chars * 600 units = 1800 units = 1.8 at size 1.0 * 10.0 = 18.0
        assert!((width - 18.0).abs() < 0.01);
    }

    #[test]
    #[allow(deprecated)]
    fn test_measure_char_custom_font() {
        let metrics = FontMetrics::new(500).with_widths(&[('X', 700)]);
        register_custom_font_metrics("CustomCharTest".to_string(), metrics);

        let width = measure_char('X', Font::Custom("CustomCharTest".to_string()), 10.0);

        // 700 units / 1000 * 10.0 = 7.0
        assert!((width - 7.0).abs() < 0.01);
    }

    #[test]
    fn test_custom_font_no_auto_register_default() {
        // When using an unregistered custom font, default metrics are used but NOT
        // registered into the global. The read path must have no side effects.
        let unique = format!("NoAutoRegister_{}", std::process::id());
        let width = measure_char('A', Font::Custom(unique.clone()), 10.0);

        // Should use default metrics (Helvetica-like), A = 667
        let expected = 667.0 * 10.0 / 1000.0;
        assert!((width - expected).abs() < 0.01);

        // Must NOT be registered as a side effect
        // get_custom_font_metrics is deprecated by Task 12 of #230 (v2.8.0).
        // #[allow(deprecated)] is applied now to avoid churn when the attribute lands.
        #[allow(deprecated)]
        let metrics = get_custom_font_metrics(&unique);
        assert!(
            metrics.is_none(),
            "read path must not auto-register unknown custom fonts"
        );
    }

    #[test]
    fn test_create_default_custom_metrics() {
        let metrics = create_default_custom_metrics();

        // Test some expected values
        assert_eq!(metrics.char_width('A'), 667);
        assert_eq!(metrics.char_width(' '), 278);
        assert_eq!(metrics.char_width('0'), 556);
        assert_eq!(metrics.char_width(''), 1000); // CJK
        assert_eq!(metrics.default_width, 556);
    }

    #[test]
    fn test_create_default_custom_metrics_is_cached() {
        // With lazy_static caching, repeated calls should be fast (clone only).
        // Without caching, each call does ~6,500 HashMap inserts.
        use std::time::Instant;
        let start = Instant::now();
        for _ in 0..1000 {
            let _ = create_default_custom_metrics();
        }
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 50,
            "1000 calls took {}ms; expected < 50ms with caching",
            elapsed.as_millis()
        );
    }

    #[test]
    fn test_times_roman_metrics() {
        let width = measure_char('A', Font::TimesRoman, 10.0);
        // Times Roman 'A' = 722 units
        let expected = 722.0 * 10.0 / 1000.0;
        assert!((width - expected).abs() < 0.01);
    }

    #[test]
    fn test_helvetica_bold_metrics() {
        let width = measure_char('A', Font::HelveticaBold, 10.0);
        // Helvetica Bold 'A' = 722 units
        let expected = 722.0 * 10.0 / 1000.0;
        assert!((width - expected).abs() < 0.01);
    }

    #[test]
    fn test_times_bold_uses_base_metrics() {
        let base_width = measure_char('A', Font::TimesRoman, 12.0);
        let bold_width = measure_char('A', Font::TimesBold, 12.0);
        let italic_width = measure_char('A', Font::TimesItalic, 12.0);
        let bold_italic_width = measure_char('A', Font::TimesBoldItalic, 12.0);

        // All Times variants use base Times Roman metrics
        assert_eq!(base_width, bold_width);
        assert_eq!(base_width, italic_width);
        assert_eq!(base_width, bold_italic_width);
    }

    #[test]
    fn test_courier_variants_use_base_metrics() {
        let base_width = measure_char('X', Font::Courier, 12.0);
        let bold_width = measure_char('X', Font::CourierBold, 12.0);
        let oblique_width = measure_char('X', Font::CourierOblique, 12.0);
        let bold_oblique_width = measure_char('X', Font::CourierBoldOblique, 12.0);

        // All Courier variants use base Courier metrics
        assert_eq!(base_width, bold_width);
        assert_eq!(base_width, oblique_width);
        assert_eq!(base_width, bold_oblique_width);
    }

    // ── Task 2 tests ────────────────────────────────────────────────────────

    /// Clear the warned-set between tests that assert warn-once behaviour.
    fn reset_warned_unknown_fonts() {
        if let Ok(mut set) = WARNED_UNKNOWN_FONTS.write() {
            set.clear();
        }
    }

    #[test]
    fn test_warn_unknown_font_rate_limited_once_per_name() {
        let unique = format!("RateLimitTask2_{}", std::process::id());
        // Isolate the warned-set from any state planted by earlier tests in this
        // process. Helper is intentionally test-only.
        reset_warned_unknown_fonts();

        warn_unknown_custom_font_once(&unique);
        warn_unknown_custom_font_once(&unique);
        warn_unknown_custom_font_once(&unique);

        let set = WARNED_UNKNOWN_FONTS.read().expect("lock");
        assert!(
            set.contains(&unique),
            "name should be in the warned set after first call"
        );
        let count = set.iter().filter(|n| *n == &unique).count();
        assert_eq!(
            count, 1,
            "warn_unknown_custom_font_once must rate-limit to one entry per name"
        );
    }

    #[test]
    fn test_unknown_custom_font_does_not_register_on_read() {
        // Use a unique name so this test does not collide with other tests
        // running in parallel under cargo test.
        let unique = format!("UnknownNameTask2_{}", std::process::id());
        let _ = measure_text("hello", &Font::Custom(unique.clone()), 12.0);
        // Lookup must not have planted the name in the global registry.
        // get_custom_font_metrics is deprecated by Task 12 of #230 (v2.8.0).
        // #[allow(deprecated)] is applied now to avoid churn when the attribute lands.
        #[allow(deprecated)]
        let leaked = get_custom_font_metrics(&unique);
        assert!(
            leaked.is_none(),
            "read path must not auto-register '{}'",
            unique
        );
    }

    #[test]
    fn test_unknown_custom_font_returns_default_widths() {
        let unique = format!("UnknownReturnTask2_{}", std::process::id());
        let width = measure_text("AAAA", &Font::Custom(unique), 12.0);
        // create_default_custom_metrics maps 'A' = 667; default_width = 556 for
        // unmapped chars. Test uses "AAAA": 4 × 667 / 1000 × 12 = 32.016.
        assert!(
            (width - 32.016).abs() < 0.01,
            "unknown custom fonts must use the default metrics (A=667), got {}",
            width
        );
    }

    #[test]
    fn test_split_into_words_mixed_whitespace() {
        let words = split_into_words("A B  C   D");
        assert_eq!(words, vec!["A", " ", "B", "  ", "C", "   ", "D"]);
    }

    #[test]
    fn test_font_metrics_store_register_and_get() {
        let store = FontMetricsStore::new();
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);

        let metrics = FontMetrics::new(500).with_widths(&[('A', 700), ('B', 720)]);
        store.register("MyFont", metrics);

        assert_eq!(store.len(), 1);
        assert!(!store.is_empty());

        let got = store.get("MyFont").expect("font should be present");
        assert_eq!(got.char_width('A'), 700);
        assert_eq!(got.char_width('B'), 720);
        assert_eq!(got.char_width('Z'), 500); // default fallback
    }

    #[test]
    fn test_font_metrics_store_overwrite_same_name() {
        let store = FontMetricsStore::new();
        store.register("X", FontMetrics::new(500).with_widths(&[('A', 600)]));
        store.register("X", FontMetrics::new(500).with_widths(&[('A', 800)]));

        let got = store.get("X").unwrap();
        assert_eq!(got.char_width('A'), 800); // last writer wins
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn test_font_metrics_store_clone_shares_state() {
        let store_a = FontMetricsStore::new();
        let store_b = store_a.clone();

        store_a.register("Shared", FontMetrics::new(400));
        assert_eq!(store_b.len(), 1, "clone must share the underlying registry");
        assert!(store_b.get("Shared").is_some());

        store_b.register("AlsoShared", FontMetrics::new(400));
        assert_eq!(store_a.len(), 2);
    }

    #[test]
    fn test_font_metrics_store_get_miss_returns_none_no_side_effects() {
        let store = FontMetricsStore::new();
        assert!(store.get("Unknown").is_none());
        assert_eq!(store.len(), 0); // no auto-register
        assert!(store.is_empty());
    }

    // ── Task 3 tests ────────────────────────────────────────────────────────

    #[test]
    fn test_lookup_document_scope_takes_precedence_over_global() {
        let unique = format!("PrecedenceTask3_{}", std::process::id());

        // Plant something in the legacy global.
        // get_custom_font_metrics is deprecated by Task 12 of #230 (v2.8.0).
        // #[allow(deprecated)] is applied now to avoid churn when the attribute lands.
        #[allow(deprecated)]
        register_custom_font_metrics(
            unique.clone(),
            FontMetrics::new(500).with_widths(&[('A', 100)]),
        );

        // Per-Document store has different metrics for the same name.
        let store = FontMetricsStore::new();
        store.register(
            unique.clone(),
            FontMetrics::new(500).with_widths(&[('A', 900)]),
        );

        let resolved = lookup(&Font::Custom(unique), Some(&store));
        assert_eq!(
            resolved.char_width('A'),
            900,
            "Document scope must win over global"
        );
    }

    #[test]
    fn test_lookup_falls_through_to_global_when_store_misses() {
        let unique = format!("FallthroughTask3_{}", std::process::id());

        // get_custom_font_metrics is deprecated by Task 12 of #230 (v2.8.0).
        // #[allow(deprecated)] is applied now to avoid churn when the attribute lands.
        #[allow(deprecated)]
        register_custom_font_metrics(
            unique.clone(),
            FontMetrics::new(500).with_widths(&[('A', 333)]),
        );

        let empty_store = FontMetricsStore::new();
        let resolved = lookup(&Font::Custom(unique), Some(&empty_store));
        assert_eq!(
            resolved.char_width('A'),
            333,
            "must fall through to legacy global when Document store misses"
        );
    }

    #[test]
    fn test_lookup_with_none_store_uses_global_then_default() {
        let unique = format!("NoneStoreTask3_{}", std::process::id());

        // No global, no store. Should default+warn.
        let resolved = lookup(&Font::Custom(unique), None);
        assert_eq!(resolved.char_width('A'), 667); // create_default_custom_metrics maps 'A' = 667
    }

    // ── Task 4 tests ────────────────────────────────────────────────────────

    #[test]
    fn test_measure_text_with_uses_document_scope() {
        let unique = format!("MeasureWithTask4_{}", std::process::id());
        let store = FontMetricsStore::new();
        store.register(
            unique.clone(),
            // Each char (A through F) at 1000 units; 'A' x 4 chars = 48.0 at 12pt.
            FontMetrics::new(500).with_widths(&[('A', 1000)]),
        );

        let width = measure_text_with("AAAA", &Font::Custom(unique), 12.0, Some(&store));
        // 4 * 1000 / 1000 * 12 = 48
        assert!((width - 48.0).abs() < 0.01, "got {}", width);
    }

    #[test]
    fn test_measure_text_back_compat_shim_passes_none() {
        let unique = format!("BackCompatTask4_{}", std::process::id());
        // Without store, with empty global → default 'A' from create_default_custom_metrics
        // ('A' = 667). 4 chars × 667 / 1000 × 12 = 32.016
        let width = measure_text("AAAA", &Font::Custom(unique), 12.0);
        assert!((width - 32.016).abs() < 0.01, "got {}", width);
    }

    #[test]
    fn test_measure_char_with_uses_document_scope() {
        let unique = format!("MeasureCharWithTask4_{}", std::process::id());
        let store = FontMetricsStore::new();
        store.register(
            unique.clone(),
            FontMetrics::new(500).with_widths(&[('Z', 800)]),
        );
        let width = measure_char_with('Z', Font::Custom(unique), 10.0, Some(&store));
        // 800 / 1000 * 10 = 8
        assert!((width - 8.0).abs() < 0.01, "got {}", width);
    }
}