flpdf 0.7.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Appearance-stream generators for AcroForm widgets.
//!
//! qpdf correspondence: `QPDFFormFieldObjectHelper.cc` rendering primitives.
//!
//! This module builds the `/AP/N` (normal-appearance) Form XObject for
//! AcroForm **Tx** and **Ch** widgets. Button appearance generation is not
//! part of the production path: qpdf's
//! `QPDFFormFieldObjectHelper::generateAppearance` dispatches only `/Tx` and
//! `/Ch` (`QPDFFormFieldObjectHelper.cc:472-478`).
//! New streams install an independently built dictionary through
//! `ObjectHandle::replace_stream_dict`, mirroring qpdf's `replaceDict`
//! (`QPDFFormFieldObjectHelper.cc:773-778`, `QPDF_Stream.cc:688-692`).
//!
//! The production route follows qpdf's limited generator rather than adding a
//! font-metrics layout engine: quadding is ignored, and text is encoded as
//! ASCII unless qpdf finds a `/Encoding /WinAnsiEncoding` or
//! `/MacRomanEncoding` font in the existing appearance resources or
//! document-level `/AcroForm /DR` (`QPDFFormFieldObjectHelper.cc:576-577,
//! 811-849`).

use std::cell::RefCell;
use std::io::{Read, Seek};
use std::rc::Rc;

use crate::annotation_object_helper::AnnotationObjectHelper;
use crate::content_stream::{
    parse_content_stream_handles_with_recoverable_warnings, ObjectHandleParserCallbacks,
    ParseControl,
};
use crate::default_appearance::parse_default_appearance;
use crate::form_field_object_helper::FormFieldObjectHelper;
use crate::object_handle::ObjectHandle;
use crate::page_object_helper::PageBox;
use crate::pdf_syntax::{qpdf_real_value, write_string_value};
use crate::pipeline::PipelineResult;
use crate::token_filter::{TokenFilter, TokenFilterOutput};
use crate::tokenizer::{Token, TokenType};
use crate::{Error, ObjectRef, Pdf, Result};

/// Read a rectangle-shaped array (`/Rect`, `/BBox`, …) at `key` through a
/// live handle. qpdf's `QPDFObjectHandle::getArrayAsRectangle` accepts any
/// four numeric entries and normalizes the two corners with min/max before
/// returning the rectangle (`libqpdf/QPDFObjectHandle.cc:816-836`).
fn resolve_rectangle_canonical(handle: &ObjectHandle, key: &[u8]) -> Result<Option<PageBox>> {
    let rect = handle.try_get_key(key)?;
    let Some(items) = rect.try_as_array()? else {
        return Ok(None);
    };
    if items.len() != 4 {
        return Ok(None);
    }

    let mut values = [0.0; 4];
    for (index, item) in items.into_iter().enumerate() {
        if !item.try_is_number()? {
            return Ok(None);
        }
        values[index] = item.try_get_numeric_value()?;
    }
    Ok(Some(PageBox::new(
        values[0].min(values[2]),
        values[1].min(values[3]),
        values[0].max(values[2]),
        values[1].max(values[3]),
    )))
}

/// Read a widget rectangle through the live annotation handle.
fn resolve_rect_canonical(widget: &ObjectHandle) -> Result<Option<PageBox>> {
    resolve_rectangle_canonical(widget, b"/Rect")
}

/// Resolve the bounding box used to size a widget's `/AP/N` appearance
/// content.
///
/// qpdf's `QPDFFormFieldObjectHelper::generateTextAppearance` only derives
/// the box from the widget's `/Rect` when creating a fresh `/AP/N` stream.
/// When `/AP/N` is *already* a stream, it lays out content against that
/// stream's own `/BBox` instead -- never against the current `/Rect` -- and
/// leaves `/BBox` itself completely untouched
/// (`libqpdf/QPDFFormFieldObjectHelper.cc:766-793`). If that existing
/// `/BBox` is not a valid four-number rectangle, qpdf warns and aborts
/// appearance generation entirely rather than falling back to `/Rect`
/// (`QPDFFormFieldObjectHelper.cc:788-791`).
/// A fresh stream's `/BBox` is `[0 0 rect_width rect_height]`, so the fallback
/// below returns that normalized coordinate system rather than the Widget's
/// absolute `/Rect` origin (`QPDFFormFieldObjectHelper.cc:778-782`).
///
/// Verified against a real `qpdf 11.9.0 --generate-appearances` run: a
/// widget with an existing `/AP/N` `/BBox [0 0 190 20]` and an enlarged
/// `/Rect [10 10 400 130]` is rewritten with `/BBox` still `[0 0 190 20]`,
/// and the appearance content's `Td` offsets are computed from that
/// unchanged 190×20 box.
fn resolve_appearance_bbox_canonical<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    widget: &ObjectHandle,
) -> Result<Option<PageBox>> {
    let normal = resolve_normal_appearance_canonical(pdf, widget)?;
    normal.try_dereference()?;
    if let Some(stream_dict) = normal.as_stream_dict() {
        return resolve_rectangle_canonical(&stream_dict, b"/BBox");
    }
    let Some(rect) = resolve_rect_canonical(widget)? else {
        return Ok(None);
    };
    Ok(Some(PageBox::new(
        0.0,
        0.0,
        rect.urx - rect.llx,
        rect.ury - rect.lly,
    )))
}

/// Select `/AP/N`, including qpdf's `/AS` lookup when `/N` is a state
/// dictionary. The annotation helper owns this qpdf responsibility.
fn resolve_normal_appearance_canonical<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    widget: &ObjectHandle,
) -> Result<ObjectHandle> {
    let mut annotation = AnnotationObjectHelper::from_object_handle(widget.clone(), pdf);
    annotation.get_appearance_stream(b"N", None)
}

#[derive(Clone, Copy)]
enum AppearanceEncoding {
    Ascii,
    WinAnsi,
    MacRoman,
}

#[derive(Clone)]
struct AppearanceFont {
    resource_name: Vec<u8>,
    font: ObjectHandle,
    encoding: AppearanceEncoding,
    from_default_resources: bool,
}

fn font_from_resources(
    resources: ObjectHandle,
    resource_name: &[u8],
) -> Result<Option<ObjectHandle>> {
    if !resources.try_is_dictionary()? {
        return Ok(None);
    }
    let font_dict = resources.try_get_key(b"/Font")?;
    if !font_dict.try_is_dictionary()? {
        return Ok(None);
    }
    let resource_key = {
        let mut key = Vec::with_capacity(resource_name.len() + 1);
        key.push(b'/');
        key.extend_from_slice(resource_name);
        key
    };
    let font = font_dict.try_get_key(&resource_key)?;
    Ok((!font.try_is_null()?).then_some(font))
}

fn appearance_font_encoding(font: &ObjectHandle) -> Result<AppearanceEncoding> {
    font.try_dereference()?;
    let encoding = font.try_get_key(b"/Encoding")?;
    Ok(match encoding.try_as_name()?.as_deref() {
        Some(b"WinAnsiEncoding") => AppearanceEncoding::WinAnsi,
        Some(b"MacRomanEncoding") => AppearanceEncoding::MacRoman,
        _ => AppearanceEncoding::Ascii,
    })
}

fn lookup_appearance_font<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    field: ObjectHandle,
    normal_appearance: &ObjectHandle,
    resource_name: Option<&[u8]>,
) -> Result<Option<AppearanceFont>> {
    let Some(resource_name) = resource_name.filter(|name| !name.is_empty()) else {
        return Ok(None);
    };

    normal_appearance.try_dereference()?;
    if let Some(stream_dict) = normal_appearance.as_stream_dict() {
        let resources = stream_dict.try_get_key(b"/Resources")?;
        if let Some(font) = font_from_resources(resources, resource_name)? {
            let encoding = appearance_font_encoding(&font)?;
            return Ok(Some(AppearanceFont {
                resource_name: resource_name.to_vec(),
                font,
                encoding,
                from_default_resources: false,
            }));
        }
    }

    let resources = FormFieldObjectHelper::from_object_handle(field, pdf).default_resources()?;
    let Some(resources) = resources else {
        return Ok(None);
    };
    let Some(font) = font_from_resources(resources, resource_name)? else {
        return Ok(None);
    };
    // qpdf merges a document-level fallback font only when the resolved
    // resource is a dictionary (`QPDFFormFieldObjectHelper.cc:817-832`).
    // A malformed scalar `/DR` entry is treated as no usable font rather
    // than being copied into the appearance resource dictionary.
    if !font.try_is_dictionary()? {
        return Ok(None);
    }
    let encoding = appearance_font_encoding(&font)?;
    Ok(Some(AppearanceFont {
        resource_name: resource_name.to_vec(),
        font,
        encoding,
        from_default_resources: true,
    }))
}

fn encode_appearance_text(value: &str, encoding: AppearanceEncoding) -> Vec<u8> {
    match encoding {
        AppearanceEncoding::Ascii => crate::qutil::utf8_to_ascii(value.as_bytes()),
        AppearanceEncoding::WinAnsi => crate::qutil::utf8_to_win_ansi(value.as_bytes()),
        AppearanceEncoding::MacRoman => crate::qutil::utf8_to_mac_roman(value.as_bytes()),
    }
}

#[derive(Clone, Copy)]
enum AppearanceFilterState {
    Top,
    Bmc,
    Emc,
    End,
}

/// qpdf's `ValueSetter` boundary for an existing `/AP/N` stream. The
/// generated appearance is stored as the replacement body only: the original
/// `/Tx BMC` prefix and any post-`EMC` tokens remain owned by the source
/// stream, exactly as `QPDFFormFieldObjectHelper.cc:524-570` does.
struct AppearanceTokenFilter {
    replacement_body: Vec<u8>,
    state: AppearanceFilterState,
    replaced: bool,
}

impl AppearanceTokenFilter {
    fn new(content: &[u8]) -> Self {
        const PREFIX: &[u8] = b"/Tx BMC\n";
        const SUFFIX: &[u8] = b"EMC\n";
        let replacement_body = content
            .strip_prefix(PREFIX)
            .and_then(|content| content.strip_suffix(SUFFIX))
            .unwrap_or(content)
            .to_vec();
        Self {
            replacement_body,
            state: AppearanceFilterState::Top,
            replaced: false,
        }
    }
}

impl TokenFilter for AppearanceTokenFilter {
    fn handle_token(
        &mut self,
        token: &Token,
        output: &mut TokenFilterOutput<'_>,
    ) -> PipelineResult<()> {
        let mut replace = false;
        match self.state {
            AppearanceFilterState::Top => {
                output.write_token(token)?;
                if token.is_word_value(b"BMC") {
                    self.state = AppearanceFilterState::Bmc;
                }
            }
            AppearanceFilterState::Bmc => {
                if matches!(token.token_type, TokenType::Space | TokenType::Comment) {
                    output.write_token(token)?;
                } else {
                    self.state = AppearanceFilterState::Emc;
                    if token.is_word_value(b"EMC") {
                        replace = true;
                        self.state = AppearanceFilterState::End;
                    }
                }
            }
            AppearanceFilterState::Emc => {
                if token.is_word_value(b"EMC") {
                    replace = true;
                    self.state = AppearanceFilterState::End;
                }
            }
            AppearanceFilterState::End => output.write_token(token)?,
        }
        if replace {
            self.replaced = true;
            output.write(&self.replacement_body)?;
            output.write(b"EMC")?;
        }
        Ok(())
    }

    fn handle_eof(&mut self, output: &mut TokenFilterOutput<'_>) -> PipelineResult<()> {
        if !self.replaced {
            output.write(b"/Tx BMC\n")?;
            output.write(&self.replacement_body)?;
            output.write(b"EMC")?;
            self.replaced = true;
        }
        Ok(())
    }
}

/// Build and install a new `/AP/N` Form XObject through canonical handles.
///
/// This is the qpdf `QPDFFormFieldObjectHelper::generateTextAppearance`
/// allocation boundary. New streams and font dictionaries are registered by
/// the document's canonical allocator; the widget and its existing `/AP`
/// dictionary are then mutated in place, preserving every handle identity
/// already held by the caller.
///
/// Returns `Ok(None)` when `/AP` is present but not a dictionary: qpdf's
/// `replaceKey` no-ops (with a warning) on a non-dictionary receiver
/// (`QPDFObjectHandle::replaceKey`, `QPDFObjectHandle.cc:1199-1210`), so the
/// freshly built stream is never linked into the widget's `/AP/N`. `None`
/// keeps that outcome visible to the caller instead of returning a stream
/// ref the widget does not actually reference.
fn resource_key(name: &[u8]) -> Vec<u8> {
    let mut key = Vec::with_capacity(name.len() + 1);
    key.push(b'/');
    key.extend_from_slice(name);
    key
}

fn add_default_font_to_existing_appearance<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    normal: &ObjectHandle,
    font: &AppearanceFont,
) -> Result<()> {
    normal.try_dereference()?;
    let Some(stream_dict) = normal.as_stream_dict() else {
        return Ok(()); // cov:ignore: qpdf calls this helper only after selecting a stream appearance
    };
    let resources = stream_dict.try_get_key(b"/Resources")?;
    if !resources.try_is_dictionary()? {
        return Ok(()); // cov:ignore: the missing-resources branch is covered by the malformed AP fixture
    }
    resources.try_dereference()?;
    let resources = if resources.is_indirect() {
        let copy = resources.shallow_copy()?;
        let indirect = pdf.make_indirect_object_handle(copy)?;
        stream_dict.replace_key(b"/Resources", indirect.clone())?;
        indirect
    } else {
        resources
    };
    let empty_font = ObjectHandle::dictionary(vec![(
        b"/Font".to_vec(),
        ObjectHandle::dictionary(Vec::new()),
    )]);
    resources.merge_resources(&empty_font, None)?;
    resources
        .try_get_key(b"/Font")?
        .replace_key(&resource_key(&font.resource_name), font.font.clone())?;
    Ok(())
}

fn install_normal_appearance_canonical_handles<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    widget: ObjectHandle,
    content: Vec<u8>,
    bbox_w: f64,
    bbox_h: f64,
    font_resource: Option<AppearanceFont>,
) -> Result<Option<ObjectRef>> {
    widget.try_dereference()?;
    let normal = resolve_normal_appearance_canonical(pdf, &widget)?;
    normal.try_dereference()?;

    // qpdf keeps an existing normal appearance stream and installs a
    // `ValueSetter` token filter on that same canonical stream
    // (`QPDFFormFieldObjectHelper.cc:766-860`).
    if normal.as_stream_dict().is_some() {
        if let Some(font) = font_resource
            .as_ref()
            .filter(|font| font.from_default_resources)
        {
            add_default_font_to_existing_appearance(pdf, &normal, font)?;
        }
        normal.add_token_filter(Rc::new(RefCell::new(AppearanceTokenFilter::new(&content))))?;
        return normal
            .object_ref()
            .ok_or_else(|| {
                Error::Unsupported("normal appearance stream is not indirect".to_string())
            })
            .map(Some);
    }

    let ap = widget.try_get_key(b"/AP")?;
    // qpdf creates a fresh appearance stream with the empty `/Tx BMC ... EMC`
    // buffer first, then installs ValueSetter as a lazy token filter
    // (`QPDFFormFieldObjectHelper.cc:778-782, 851`). Keep the same split-copy
    // boundary: direct writes run the filter, while qpdf's doSplitPages copy
    // carries the original buffer without the filter state.
    let stream = pdf.new_stream_with_data(Rc::new(b"/Tx BMC\nEMC\n".to_vec()))?;
    let bbox = ObjectHandle::array(vec![
        ObjectHandle::real(0.0),
        ObjectHandle::real(0.0),
        ObjectHandle::real(qpdf_real_value(bbox_w)),
        ObjectHandle::real(qpdf_real_value(bbox_h)),
    ]);

    let resources = ObjectHandle::dictionary(vec![(
        b"/ProcSet".to_vec(),
        ObjectHandle::array(vec![
            ObjectHandle::name(b"PDF".to_vec()),
            ObjectHandle::name(b"Text".to_vec()),
        ]),
    )]);
    if let Some(font) = font_resource {
        resources.replace_key(
            b"/Font",
            ObjectHandle::dictionary(vec![(resource_key(&font.resource_name), font.font)]),
        )?; // cov:ignore: llvm-cov maps the successful resource insertion continuation to a zero-count region
    }
    let stream_dict = ObjectHandle::dictionary(vec![
        (b"/BBox".to_vec(), bbox),
        (b"/Resources".to_vec(), resources),
        (b"/Subtype".to_vec(), ObjectHandle::name(b"Form".to_vec())),
        (b"/Type".to_vec(), ObjectHandle::name(b"XObject".to_vec())),
    ]);
    stream.replace_stream_dict(stream_dict)?;

    let ap = if ap.try_is_null()? {
        let ap = ObjectHandle::dictionary(Vec::new());
        widget.replace_key(b"/AP", ap.clone())?;
        ap
    } else {
        ap
    };

    // qpdf's replaceKey is a no-op for a non-dictionary /AP value.
    if ap.try_is_dictionary()? {
        ap.replace_key(b"/N", stream.clone())?;
        stream.add_token_filter(Rc::new(RefCell::new(AppearanceTokenFilter::new(&content))))?;
    } else {
        return Ok(None);
    }

    // cov:ignore-start: new_stream_with_data always allocates an indirect stream
    let stream_ref = stream.object_ref().ok_or_else(|| {
        Error::Unsupported("canonical appearance stream is not indirect".to_string())
    })?;
    // cov:ignore-end
    Ok(Some(stream_ref))
}

/// Canonical Tx appearance generation. Graph reads and writes stay on the
/// field/widget handles; only the appearance content itself is a byte buffer.
#[cfg(test)]
pub(crate) fn render_text_field_canonical<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    field_ref: ObjectRef,
    widget_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
    let field = pdf.get_object_handle(field_ref);
    let widget = pdf.get_object_handle(widget_ref);
    render_text_field_canonical_handles(pdf, field, widget)
}

/// Canonical Tx appearance generation from live field and Widget handles.
pub(crate) fn render_text_field_canonical_handles<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    field: ObjectHandle,
    widget: ObjectHandle,
) -> Result<Option<ObjectRef>> {
    let field_type = FormFieldObjectHelper::from_object_handle(field.clone(), pdf).field_type()?;
    if field_type.as_deref() != Some(b"/Tx") {
        return Ok(None);
    }

    let value = FormFieldObjectHelper::from_object_handle(field.clone(), pdf).value_as_string()?;
    widget.try_dereference()?;
    let Some(rect) = resolve_appearance_bbox_canonical(pdf, &widget)? else {
        return Ok(None);
    };
    let bbox_w = rect.urx - rect.llx;
    let bbox_h = rect.ury - rect.lly;
    // qpdf's QPDFObjectHandle::isRectangle validates only that all four
    // entries are numbers (`QPDFObjectHandle.cc:788-800`). It does not impose
    // a positive or minimum width/height before generateTextAppearance builds
    // the appearance from the rectangle (`QPDFFormFieldObjectHelper.cc:766-851`).
    if !bbox_w.is_finite() || !bbox_h.is_finite() {
        return Ok(None);
    }

    let mut helper = FormFieldObjectHelper::from_object_handle(field.clone(), pdf);
    let default_appearance = helper.default_appearance()?;
    let da = parse_default_appearance(default_appearance.as_bytes());
    drop(helper);

    let normal_appearance = resolve_normal_appearance_canonical(pdf, &widget)?;
    let font = lookup_appearance_font(
        pdf,
        field.clone(),
        &normal_appearance,
        da.font_name.as_deref(),
    )?; // cov:ignore: lookup error propagation is covered by the qpdf-shaped helper tests
    let encoding = font
        .as_ref()
        .map(|font| font.encoding)
        .unwrap_or(AppearanceEncoding::Ascii);
    // qpdf's ValueSetter ignores quadding and uses 11pt when the /DA Tf
    // operand is absent or auto-sized (`QPDFFormFieldObjectHelper.cc:797-860`).
    let font_size = if da.auto_size { 11.0 } else { da.font_size };
    let content = build_qpdf_choice_appearance_content(
        default_appearance.as_bytes(),
        &encode_appearance_text(&value, encoding),
        &[],
        rect,
        font_size,
        true,
    );
    install_normal_appearance_canonical_handles(pdf, widget, content, bbox_w, bbox_h, font)
}

/// Canonical Ch appearance generation from live field and Widget handles.
pub(crate) fn render_choice_field_canonical_handles<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    field: ObjectHandle,
    widget: ObjectHandle,
) -> Result<Option<ObjectRef>> {
    let field_type = FormFieldObjectHelper::from_object_handle(field.clone(), pdf).field_type()?;
    if field_type.as_deref() != Some(b"/Ch") {
        return Ok(None);
    }

    widget.try_dereference()?;
    let Some(rect) = resolve_appearance_bbox_canonical(pdf, &widget)? else {
        return Ok(None);
    };
    let bbox_w = rect.urx - rect.llx;
    let bbox_h = rect.ury - rect.lly;
    // Keep qpdf's numeric-rectangle contract: a finite subunit or zero-sized
    // rectangle still reaches the ValueSetter/content builder.
    if !bbox_w.is_finite() || !bbox_h.is_finite() {
        return Ok(None);
    }

    let mut helper = FormFieldObjectHelper::from_object_handle(field.clone(), pdf);
    let default_appearance = helper.default_appearance()?;
    let da = parse_default_appearance(default_appearance.as_bytes());
    // qpdf's `getFlags()` returns a signed C++ `int` and tests the combo
    // bit directly on that signed value (`getFlags() & ff_ch_combo`,
    // `QPDFFormFieldObjectHelper.cc:231-234,800`): for `/Ff -1`, all bits
    // are set in two's complement, so the combo bit reads as set. Do not
    // route through `u32::try_from`, which fails (and previously defaulted
    // to zero) for any negative `/Ff`, incorrectly clearing the combo bit.
    //
    // qpdf's `getFlags()` reads `/Ff` through
    // `QPDFObjectHandle::getIntValueAsInt` (`QPDFObjectHandle.cc:525-540`),
    // which *saturates* an out-of-`int`-range value to `INT_MIN`/`INT_MAX`
    // rather than passing its bit pattern through -- so it is the
    // saturated 32-bit value, not the raw stored integer, that qpdf masks
    // against `ff_ch_combo`. Clamp to the `i32` range before masking so an
    // out-of-range `/Ff` (e.g. `4294967296`, which saturates to `INT_MAX`
    // and so has the combo bit set) agrees with qpdf instead of testing a
    // bit pattern qpdf never actually forms.
    let flags = helper
        .field_flags()?
        .unwrap_or(0)
        .clamp(i64::from(i32::MIN), i64::from(i32::MAX));
    let value = helper.value_as_string()?;
    let options = helper.choices()?;
    drop(helper);

    let normal_appearance = resolve_normal_appearance_canonical(pdf, &widget)?;
    let font = lookup_appearance_font(
        pdf,
        field.clone(),
        &normal_appearance,
        da.font_name.as_deref(),
    )?; // cov:ignore: lookup error propagation is covered by the qpdf-shaped helper tests
    let encoding = font
        .as_ref()
        .map(|font| font.encoding)
        .unwrap_or(AppearanceEncoding::Ascii);
    // qpdf's ValueSetter starts from the Tf operand in /DA. A missing or
    // auto-sized Tf uses its source default of 11pt; it does not invent a
    // field-height-dependent size here.
    let font_size = if da.auto_size { 11.0 } else { da.font_size };
    let content = build_qpdf_choice_appearance_content(
        default_appearance.as_bytes(),
        &encode_appearance_text(&value, encoding),
        &options
            .iter()
            .map(|option| encode_appearance_text(option, encoding))
            .collect::<Vec<_>>(),
        rect,
        font_size,
        flags & 0x20000 != 0,
    );
    install_normal_appearance_canonical_handles(pdf, widget, content, bbox_w, bbox_h, font)
}

/// Canonical Ch appearance generation. Graph reads and writes stay on the
/// field/widget handles; only the appearance content itself is a byte buffer.
#[cfg(test)]
pub(crate) fn render_choice_field_canonical<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    field_ref: ObjectRef,
    widget_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
    let field = pdf.get_object_handle(field_ref);
    let widget = pdf.get_object_handle(widget_ref);
    render_choice_field_canonical_handles(pdf, field, widget)
}

/// Substitute `/DA`'s `Tf` size operand with `resolved_font_size` when it
/// differs from the parsed literal by more than qpdf's `0.001` tolerance,
/// mirroring `TfFinder::getDA()` (`QPDFFormFieldObjectHelper.cc:729-746`).
///
/// Returns `default_appearance` unchanged when no numeric token precedes a
/// `Tf` operator. qpdf's `TfFinder` records the last numeric token globally,
/// rather than requiring a valid `<name> <size>` operand pair, and replaces only
/// the numeric token belonging to the last `Tf` (`QPDFFormFieldObjectHelper.cc:
/// 667-745`). Preserve that token-level recovery for malformed/default-size
/// appearances such as `0 Tf 0 g`, where qpdf substitutes its 11pt fallback.
fn substitute_da_tf_operand(default_appearance: &[u8], resolved_font_size: f64) -> Vec<u8> {
    struct TfOperandFinder {
        last_number: Option<(usize, usize, f64)>,
        tf_size_span: Option<(usize, usize, f64)>,
    }

    impl ObjectHandleParserCallbacks for TfOperandFinder {
        fn handle_object(
            &mut self,
            object: ObjectHandle,
            offset: usize,
            length: usize,
        ) -> Result<ParseControl> {
            if let Some(value) = object
                .as_real()
                .or_else(|| object.as_integer().map(|number| number as f64))
            {
                // qpdf's TfFinder keeps this number across every token and
                // operator; it does not clear the candidate at `rg`, `g`, or
                // another malformed operator boundary.
                self.last_number = Some((offset, length, value));
            } else if object
                .as_operator()
                .is_some_and(|operator| operator.as_slice() == b"Tf")
            {
                self.tf_size_span = self.last_number;
            }
            Ok(ParseControl::Continue)
        }

        fn handle_eof(&mut self) -> Result<()> {
            Ok(())
        }
    }

    let mut finder = TfOperandFinder {
        last_number: None,
        tf_size_span: None,
    };
    // qpdf's `TfFinder` is a token filter fed by `Pl_QPDFTokenizer`
    // (`QPDFFormFieldObjectHelper.cc:804-810`): a bad token passes through as
    // raw text and never stops the scan, so a later `Tf` is still found. Use
    // the warning-and-continue context; a structural error partway through
    // still leaves whatever valid Tf occurrence was already found in place.
    let _ =
        parse_content_stream_handles_with_recoverable_warnings(default_appearance, "", &mut finder);

    let Some((offset, length, raw_value)) = finder.tf_size_span else {
        return default_appearance.to_vec();
    };
    if (raw_value - resolved_font_size).abs() <= 0.001 {
        return default_appearance.to_vec();
    }

    let mut out = Vec::with_capacity(default_appearance.len());
    out.extend_from_slice(&default_appearance[..offset]);
    out.extend_from_slice(fmt_f64(resolved_font_size).as_bytes());
    out.extend_from_slice(&default_appearance[offset + length..]);
    out
}

/// Reproduce qpdf 11.9.0's `ValueSetter::writeAppearance` layout. In
/// particular, `/I` and `/TI` are intentionally not consulted: the qpdf
/// implementation reads only `/V` and (for non-combo fields) `/Opt` before
/// selecting the visible rows (`QPDFFormFieldObjectHelper.cc:797-860`).
fn build_qpdf_choice_appearance_content(
    default_appearance: &[u8],
    value: &[u8],
    options: &[Vec<u8>],
    bbox: PageBox,
    font_size: f64,
    is_combo: bool,
) -> Vec<u8> {
    let tfh = 1.2 * font_size;
    let bbox_w = bbox.urx - bbox.llx;
    let bbox_h = bbox.ury - bbox.lly;
    // `bbox_h` and `font_size` are attacker-controlled (`/Rect`, `/DA`): for
    // a small font_size and/or a huge bbox_h, `bbox_h / tfh` can exceed
    // `usize::MAX` as an f64, and `as usize` saturates rather than
    // overflowing (Rust's documented float-to-int cast behavior since
    // 1.45). Clamping immediately — before any signed arithmetic or
    // slicing — removes that saturation risk entirely. The bound is
    // `options.len() + 1`, not `options.len()`: the *found* branch below
    // replaces `lines` outright with a slice of `options` (needs at most
    // `options.len()` rows, and the fixup loop converges to the same
    // window for any max_rows at or above that), but the *not-found*
    // branch keeps the unmatched value as its own row and appends up to
    // `max_rows - 1` options on top, so it needs room for the value plus
    // every option -- `options.len() + 1` rows -- when the bounding box is
    // tall enough to hold them (the clamp in this function under-served
    // this branch by exactly one row).
    let max_rows = ((bbox_h / tfh).max(0.0) as usize).min(options.len().saturating_add(1));
    let mut lines = vec![value.to_vec()];
    let mut highlight = false;
    let mut highlight_index = 0usize;

    if !is_combo && !options.is_empty() && max_rows >= 2 {
        if let Some(found_index) = options.iter().position(|option| option == value) {
            // All-`usize` window arithmetic (no `as isize` bit
            // reinterpretation): `max_rows >= 2` here, so `first + max_rows
            // - 1` cannot underflow, and the fixup loop only decrements
            // `last` while it is still `>= options.len() >= 1`, so it can
            // never underflow past 0 either.
            let mut first = found_index.saturating_sub(1);
            let mut last = first + max_rows - 1;
            while last >= options.len() {
                first = first.saturating_sub(1);
                last -= 1;
            }
            highlight = true;
            highlight_index = found_index - first;
            lines = options[first..=last].to_vec();
        } else {
            highlight = true;
            lines.extend(options.iter().take(max_rows - 1).cloned());
        }
    }

    let mut out = Vec::new();
    out.extend_from_slice(b"/Tx BMC\n");
    let line_count = lines.len() as f64;
    // Keep qpdf's absolute coordinate system for existing appearance streams:
    // `ValueSetter` centers against `/BBox`'s `ury` and `lly`, then adds `lly`
    // to the rectangle/text placement (`QPDFFormFieldObjectHelper.cc:623-647`).
    let mut y = bbox.ury - ((bbox_h - (line_count * tfh)) / 2.0);
    if highlight {
        out.extend_from_slice(b"q\n0.85 0.85 0.85 rg\n");
        out.extend_from_slice(fmt_f64(bbox.llx).as_bytes());
        out.push(b' ');
        out.extend_from_slice(
            fmt_f64(bbox.lly + y - tfh * (highlight_index as f64 + 1.0)).as_bytes(),
        );
        out.push(b' ');
        out.extend_from_slice(fmt_f64(bbox_w).as_bytes());
        out.push(b' ');
        out.extend_from_slice(fmt_f64(tfh).as_bytes());
        out.extend_from_slice(b" re f\nQ\n");
    }
    y -= font_size;
    out.extend_from_slice(b"q\nBT\n");
    out.extend_from_slice(&substitute_da_tf_operand(default_appearance, font_size));
    out.push(b'\n');
    for (index, line) in lines.iter().enumerate() {
        if index == 0 {
            out.extend_from_slice(fmt_f64(bbox.llx + 1.0).as_bytes());
            out.push(b' ');
            out.extend_from_slice(fmt_f64(bbox.lly + y).as_bytes());
            out.extend_from_slice(b" Td\n");
        } else {
            out.extend_from_slice(b"0 ");
            out.extend_from_slice(fmt_f64(-tfh).as_bytes());
            out.extend_from_slice(b" Td\n");
        }
        // qpdf writes each generated value with `QPDF_String::unparse`, which
        // selects literal or hexadecimal syntax from the encoded bytes. This
        // matters for a single-byte value such as PDFDocEncoding 0xf7:
        // `10\xf7` becomes `<3130f7>`, not a UTF-8 lossy literal.
        crate::writer::output::with_buffer_sink(&mut out, |sink| write_string_value(sink, line))
            .expect("writing a PDF string to a Vec cannot fail");
        out.extend_from_slice(b" Tj\n");
    }
    out.extend_from_slice(b"ET\nQ\nEMC\n");
    out
}

/// Format an f64 for use in a PDF content stream (locale-independent).
fn fmt_f64(value: f64) -> String {
    if !value.is_finite() {
        return "0".to_string();
    }
    let formatted = format!("{value:.4}");
    let formatted = formatted.trim_end_matches('0');
    let formatted = formatted.trim_end_matches('.');
    if formatted.is_empty() || formatted == "-" {
        "0".to_string() // cov:ignore: fixed four-decimal formatting cannot produce an empty string or lone minus
    } else {
        formatted.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::{buffer::Buffer, qpdf_tokenizer::QpdfTokenizer, Pipeline};
    use std::io::Cursor;

    fn run_appearance_filter(source: &[u8], replacement: &[u8]) -> Vec<u8> {
        let mut filter = AppearanceTokenFilter::new(replacement);
        let mut sink = Buffer::new("appearance filter test", None);
        let mut tokenizer =
            QpdfTokenizer::new("appearance filter test", &mut filter, Some(&mut sink));
        tokenizer.write(source).expect("tokenizer write");
        tokenizer.finish().expect("tokenizer finish");
        drop(tokenizer);
        sink.take_buffer().expect("appearance filter output")
    }

    fn pdf_with_objects(objects: &[String]) -> Vec<u8> {
        let mut pdf = b"%PDF-1.4\n".to_vec();
        let mut offsets = Vec::with_capacity(objects.len());
        for (index, object) in objects.iter().enumerate() {
            offsets.push(pdf.len());
            pdf.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", index + 1, object).as_bytes());
        }
        let xref_start = pdf.len();
        pdf.extend_from_slice(
            format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
        );
        for offset in offsets {
            pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
                objects.len() + 1
            )
            .as_bytes(),
        );
        pdf
    }

    fn minimal_tx_pdf() -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /Rect [10 10 200 30] >>".to_string(),
        ])
    }

    fn reversed_rect_tx_pdf() -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /Rect [250 150 50 50] >>".to_string(),
        ])
    }

    fn existing_ap_with_bbox_pdf(field: &str, da: &str, bbox: &str, rect: &str) -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 10 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            format!(
                "<< /Type /Annot /Subtype /Widget /FT {field} /V (B) /Opt [(A) (B) (C) (D)] /DA {da} /Rect {rect} /AP << /N 5 0 R >> >>"
            ),
            format!("<< /Type /XObject /Subtype /Form /BBox {bbox} /Resources <<>> /Length 4 >>\nstream\nq Q\nendstream"),
        ])
    }

    fn tx_without_rect_pdf() -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) >>".to_string(),
        ])
    }

    fn dr_font_tx_pdf(encoding: Option<&str>, value: &str) -> Vec<u8> {
        let font_encoding = encoding
            .map(|name| format!(" /Encoding /{name}"))
            .unwrap_or_default();
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR << /Font << /F1 5 0 R >> >> /DA (/F1 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            format!("<< /Type /Annot /Subtype /Widget /FT /Tx /V {value} /Rect [10 10 200 30] >>"),
            format!("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica{font_encoding} >>"),
        ])
    }

    fn malformed_dr_font_tx_pdf() -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR << /Font << /F1 5 0 R >> >> /DA (/F1 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /Rect [10 10 200 30] >>".to_string(),
            "42".to_string(),
        ])
    }

    fn generated_stream<R: Read + Seek>(pdf: &mut Pdf<R>, reference: ObjectRef) -> ObjectHandle {
        let stream = pdf.get_object_handle(reference);
        stream.try_is_scalar().expect("resolve appearance");
        stream
    }

    fn generated_stream_data<R: Read + Seek>(pdf: &mut Pdf<R>, reference: ObjectRef) -> Vec<u8> {
        generated_stream(pdf, reference)
            .get_stream_data(crate::DecodeLevel::Generalized)
            .expect("read generated appearance")
            .to_vec()
    }

    fn existing_ap_with_dr_font_pdf(resources_indirect: bool) -> Vec<u8> {
        let resources = if resources_indirect { "7 0 R" } else { "<<>>" };
        let mut objects = vec![
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR << /Font << /F1 6 0 R >> >> /DA (/F1 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /Rect [10 10 200 30] /AP << /N 5 0 R >> >>".to_string(),
            format!("<< /Type /XObject /Subtype /Form /BBox [0 0 190 20] /Resources {resources} /Length 4 >>\nstream\nq Q\nendstream"),
            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
        ];
        if resources_indirect {
            objects.push("<<>>".to_string());
        }
        pdf_with_objects(&objects)
    }

    fn replace_bytes_once(input: &mut Vec<u8>, from: &[u8], to: &[u8]) {
        let start = input
            .windows(from.len())
            .position(|window| window == from)
            .expect("fixture replacement must be present");
        input.splice(start..start + from.len(), to.iter().copied());
    }

    #[test]
    fn canonical_tx_adds_a_dr_font_to_direct_and_indirect_existing_resources() {
        for resources_indirect in [false, true] {
            let mut pdf = Pdf::open(Cursor::new(existing_ap_with_dr_font_pdf(
                resources_indirect,
            )))
            .expect("parse existing AP");
            let reference =
                render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                    .expect("generate")
                    .expect("Tx handled");
            assert_eq!(reference, ObjectRef::new(5, 0));
            let stream = generated_stream(&mut pdf, reference);
            let resources = stream
                .as_stream_dict()
                .expect("stream dictionary")
                .try_get_key(b"/Resources")
                .unwrap();
            resources.try_is_scalar().expect("resolve resources");
            let fonts = resources.try_get_key(b"/Font").unwrap();
            fonts.try_is_scalar().expect("resolve fonts");
            assert_eq!(
                fonts.try_get_key(b"/F1").unwrap().object_ref(),
                Some(ObjectRef::new(6, 0))
            );
        }
    }

    #[test]
    fn canonical_tx_leaves_existing_appearance_without_resources_unchanged() {
        let mut raw = existing_ap_with_dr_font_pdf(false);
        replace_bytes_once(&mut raw, b"/Resources <<>> ", b"");
        let mut pdf = Pdf::open(Cursor::new(raw)).expect("parse missing resources");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        assert_eq!(reference, ObjectRef::new(5, 0));
    }

    #[test]
    fn canonical_tx_uses_a_local_winansi_appearance_font() {
        let raw = pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /DA (/F1 12 Tf 0 g) /Rect [10 10 200 30] /AP << /N 5 0 R >> >>".to_string(),
            "<< /Type /XObject /Subtype /Form /BBox [0 0 190 20] /Resources << /Font << /F1 6 0 R >> >> /Length 4 >>\nstream\nq Q\nendstream".to_string(),
            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
        ]);
        let mut pdf = Pdf::open(Cursor::new(raw)).expect("parse local AP resource");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        assert_eq!(reference, ObjectRef::new(5, 0));
    }

    #[test]
    fn canonical_choice_uses_the_same_resource_lookup_boundary() {
        let raw = pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Ch /V (Beta) /Opt [(Alpha) (Beta)] /DA (/Helv 10 Tf 0 g) /Rect [10 10 200 30] >>".to_string(),
        ]);
        let mut pdf = Pdf::open(Cursor::new(raw)).expect("parse choice");
        assert!(render_choice_field_canonical(
            &mut pdf,
            ObjectRef::new(4, 0),
            ObjectRef::new(4, 0)
        )
        .expect("generate choice")
        .is_some());
    }

    #[test]
    fn appearance_token_filter_matches_qpdf_value_setter_boundary() {
        let replacement = b"/Tx BMC\nreplacement\nEMC\n";
        assert_eq!(
            run_appearance_filter(b"/Tx BMC %old\n EMC q", replacement),
            b"/Tx BMC %old\n replacement\nEMC q"
        );
        assert_eq!(
            run_appearance_filter(b"q", replacement),
            b"q/Tx BMC\nreplacement\nEMC"
        );
    }

    #[test]
    fn canonical_tx_without_dr_has_procset_only_and_no_form_type() {
        let mut pdf = Pdf::open(Cursor::new(minimal_tx_pdf())).expect("parse");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        let stream = generated_stream(&mut pdf, reference);
        let dict = stream.as_stream_dict().expect("stream dictionary");
        let resources = dict.try_get_key(b"/Resources").unwrap();
        resources.try_is_scalar().expect("resolve resources");
        assert!(resources.try_get_key(b"/Font").unwrap().is_null());
        assert!(dict.try_get_key(b"/FormType").unwrap().is_null());
    }

    #[test]
    fn canonical_tx_reuses_dr_font_resource() {
        let mut pdf = Pdf::open(Cursor::new(dr_font_tx_pdf(None, "(Hello)"))).expect("parse");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        assert_eq!(reference, ObjectRef::new(6, 0));
        let stream = generated_stream(&mut pdf, reference);
        let resources = stream
            .as_stream_dict()
            .expect("stream dictionary")
            .try_get_key(b"/Resources")
            .unwrap();
        resources.try_is_scalar().expect("resolve resources");
        let fonts = resources.try_get_key(b"/Font").unwrap();
        fonts.try_is_scalar().expect("resolve fonts");
        assert_eq!(
            fonts.try_get_key(b"/F1").unwrap().object_ref(),
            Some(ObjectRef::new(5, 0))
        );
    }

    #[test]
    fn canonical_tx_ignores_a_non_dictionary_dr_font_resource() {
        let mut pdf = Pdf::open(Cursor::new(malformed_dr_font_tx_pdf())).expect("parse");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        let stream = generated_stream(&mut pdf, reference);
        let resources = stream
            .as_stream_dict()
            .expect("stream dictionary")
            .try_get_key(b"/Resources")
            .unwrap();
        resources.try_is_scalar().expect("resolve resources");
        assert!(resources.try_get_key(b"/Font").unwrap().is_null());
    }

    #[test]
    fn canonical_tx_reuses_the_state_selected_stream() {
        let mut pdf = Pdf::open(Cursor::new(state_appearance_pdf())).expect("parse state AP");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        assert_eq!(reference, ObjectRef::new(5, 0));
    }

    #[test]
    fn canonical_tx_without_rect_skips_appearance_generation() {
        let mut pdf = Pdf::open(Cursor::new(tx_without_rect_pdf())).expect("parse missing Rect");
        assert!(
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generation with missing Rect")
                .is_none()
        );
    }

    #[test]
    fn canonical_tx_normalizes_reversed_fresh_rect_like_qpdf() {
        let mut pdf = Pdf::open(Cursor::new(reversed_rect_tx_pdf())).expect("parse reversed Rect");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        let data = generated_stream_data(&mut pdf, reference);
        assert!(
            data.windows(b"1 45.2 Td".len())
                .any(|window| window == b"1 45.2 Td"),
            "qpdf normalizes reversed /Rect before fresh appearance sizing"
        );
    }

    #[test]
    fn canonical_tx_normalizes_reversed_existing_bbox_like_qpdf() {
        let mut pdf = Pdf::open(Cursor::new(existing_ap_with_bbox_pdf(
            "/Tx",
            "(/Helv 12 Tf 0 g)",
            "[0 100 200 0]",
            "[10 10 200 30]",
        )))
        .expect("parse reversed BBox");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        let data = generated_stream_data(&mut pdf, reference);
        assert!(
            data.windows(b"1 45.2 Td".len())
                .any(|window| window == b"1 45.2 Td"),
            "qpdf normalizes reversed /BBox before appearance layout"
        );
    }

    #[test]
    fn canonical_choice_normalizes_reversed_bbox_for_rows_and_highlight_like_qpdf() {
        let mut pdf = Pdf::open(Cursor::new(existing_ap_with_bbox_pdf(
            "/Ch",
            "(/Helv 10 Tf 0 g)",
            "[0 100 200 0]",
            "[10 10 200 110]",
        )))
        .expect("parse reversed choice BBox");
        let reference =
            render_choice_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("choice handled");
        let data = generated_stream_data(&mut pdf, reference);
        for value in [b"(A) Tj".as_slice(), b"(B) Tj", b"(C) Tj", b"(D) Tj"] {
            assert!(
                data.windows(value.len()).any(|window| window == value),
                "qpdf lays out all four rows for normalized choice /BBox"
            );
        }
        assert!(
            data.windows(b"0.85 0.85 0.85 rg".len())
                .any(|window| window == b"0.85 0.85 0.85 rg"),
            "qpdf highlights the selected row after /BBox normalization"
        );
    }

    fn state_appearance_pdf() -> Vec<u8> {
        pdf_with_objects(&[
            "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DR <<>> /DA (/Helv 12 Tf 0 g) >> >>".to_string(),
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>".to_string(),
            "<< /Type /Annot /Subtype /Widget /FT /Tx /V (Hello) /Rect [10 10 200 30] /AP << /N << /On 5 0 R >> >> /AS /On >>".to_string(),
            "<< /Type /XObject /Subtype /Form /BBox [0 0 190 20] /Length 4 >>\nstream\nq Q\nendstream".to_string(),
        ])
    }

    #[test]
    fn canonical_tx_uses_qpdf_macroman_conversion() {
        let mut pdf = Pdf::open(Cursor::new(dr_font_tx_pdf(
            Some("MacRomanEncoding"),
            "<e9>",
        )))
        .expect("parse");
        let reference =
            render_text_field_canonical(&mut pdf, ObjectRef::new(4, 0), ObjectRef::new(4, 0))
                .expect("generate")
                .expect("Tx handled");
        let stream = generated_stream(&mut pdf, reference);
        let data = stream
            .get_stream_data(crate::DecodeLevel::Generalized)
            .expect("filtered appearance data");
        assert!(data.windows(b"<8e>".len()).any(|window| window == b"<8e>"));
    }

    #[test]
    fn qpdf_choice_builder_ignores_quadding_and_selects_visible_rows() {
        let content = build_qpdf_choice_appearance_content(
            b"/Helv 10 Tf 0 g",
            b"B",
            &[b"A".to_vec(), b"B".to_vec(), b"C".to_vec()],
            PageBox::new(0.0, 0.0, 100.0, 36.0),
            10.0,
            false,
        );
        assert!(content
            .windows(b"0.85 0.85 0.85 rg".len())
            .any(|window| { window == b"0.85 0.85 0.85 rg" }));
        assert!(content
            .windows(b"(B) Tj".len())
            .any(|window| window == b"(B) Tj"));
    }

    #[test]
    fn substitute_da_tf_follows_qpdf_tolerance_and_missing_operator() {
        assert_eq!(
            substitute_da_tf_operand(b"/Helv 12 Tf 0 g", 12.0005),
            b"/Helv 12 Tf 0 g"
        );
        assert_eq!(
            substitute_da_tf_operand(b"/Helv 12 Tf 0 g", 11.0),
            b"/Helv 11 Tf 0 g"
        );
        assert_eq!(substitute_da_tf_operand(b"0 Tf 0 g", 11.0), b"11 Tf 0 g");
        assert_eq!(substitute_da_tf_operand(b"0 g", 11.0), b"0 g");
    }

    /// qpdf's `TfFinder` sees the bad hexstring as a raw token and still
    /// records the later `Tf` (`QPDFFormFieldObjectHelper.cc:689-711`), so a
    /// malformed token before the operator must not leave `0 Tf` in place.
    #[test]
    fn substitute_da_tf_recovers_after_a_malformed_token() {
        assert_eq!(
            substitute_da_tf_operand(b"<0g> /Helv 0 Tf 0 g", 11.0),
            b"<0g> /Helv 11 Tf 0 g"
        );
    }

    #[test]
    fn fmt_f64_matches_qpdf_numeric_formatting() {
        assert_eq!(fmt_f64(12.0), "12");
        assert_eq!(fmt_f64(1.5), "1.5");
        assert_eq!(fmt_f64(0.00001), "0");
        assert_eq!(fmt_f64(f64::NAN), "0");
    }
}