flpdf-cli 0.10.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
1253
1254
1255
1256
1257
//! Integration tests: AcroForm/annotation transform observable equivalence
//!
//! Covers: generate-appearances (Tx value→Tj, checkbox/radio state sync,
//! combo value→Tj), flatten=all (Do in page content, Annots empty),
//! flatten=print (Print-bit annot removed, non-Print annot kept),
//! flatten-rotation (CLI e2e).
//!
//! # Observable-equivalence strategy
//!
//! These tests do **not** perform byte-level or pixel comparisons.  Instead,
//! they re-parse the output PDF and assert on structural/content markers:
//!
//! - Appearance generation: widget `/AP/N` is present and, where possible,
//!   its (uncompressed) content stream contains the expected operators.
//! - Flattening: annotation removed from `/Annots`, `Do` appears in page
//!   content stream (decoded).
//! - flatten=print: two annotations — one with Print bit (0x4 in /F), one
//!   without — only the Print-bit one is removed.
//!
//! Tests that inspect raw page or unfiltered appearance bytes use
//! `--compress-streams=n`. Appearance-generation tests that assert the
//! token-filtered content use `--stream-data=uncompress`, which is qpdf's
//! explicit generalized-decode request. The existing-appearance reuse test
//! intentionally uses `--compress-streams=y` and decodes through the canonical
//! `ObjectHandle` API so the token-filter writer path is exercised.
//!
//! # qpdf divergence
//!
//! See `docs/qpdf-compat-decisions.md` §AcroForm & annotation transforms.

use assert_cmd::Command;
use flpdf::{AnnotationObjectHelper, DecodeLevel, Pdf};
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::process::Command as ProcessCommand;

mod common;
use common::PdfCanonicalTestExt;
use common::{first_widget_ref, page_annotation_handles};

const EXPECTED_QPDF_VERSION: &str = "qpdf version 11.9.0";

/// `true` when the pinned qpdf oracle is runnable, mirroring the optional
/// oracle gate the other differential suites use. The version is pinned
/// because a differential assertion against a different qpdf is not a parity
/// result.
fn qpdf_available() -> bool {
    ProcessCommand::new("qpdf")
        .arg("--version")
        .output()
        .map(|output| {
            output.status.success()
                && String::from_utf8_lossy(&output.stdout)
                    .lines()
                    .next()
                    .is_some_and(|line| line.trim() == EXPECTED_QPDF_VERSION)
        })
        .unwrap_or(false)
}

// ── Fixture helpers ───────────────────────────────────────────────────────────

/// Build a minimal PDF from a flat list of object bodies (1-indexed from 1).
fn assemble_pdf(objects: &[Vec<u8>]) -> Vec<u8> {
    use std::io::Write;
    let mut bytes = b"%PDF-1.7\n".to_vec();
    let mut offsets = Vec::with_capacity(objects.len());
    for object in objects {
        offsets.push(bytes.len() as u32);
        bytes.extend_from_slice(object);
    }
    let start_xref = bytes.len();
    // Write directly into the byte buffer (writeln! to a Vec<u8> is infallible)
    // instead of allocating an intermediate String per line.
    let _ = writeln!(&mut bytes, "xref\n0 {}", objects.len() + 1);
    bytes.extend_from_slice(b"0000000000 65535 f \n");
    for &offset in &offsets {
        let _ = writeln!(&mut bytes, "{offset:010} 00000 n ");
    }
    let _ = writeln!(
        &mut bytes,
        "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF",
        objects.len() + 1,
        start_xref
    );
    bytes
}

/// Single-page AcroForm PDF with a Tx widget that has `/V` but no `/AP`.
/// Objects: 1=Catalog, 2=Pages, 3=Page, 4=Widget, 5=Contents
fn tx_widget_without_ap() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        // Widget: /FT /Tx, /V (Hello), /DA, /Rect with non-degenerate size
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
          /V (Hello) /DA (/Helv 12 Tf 0 g) \
          /Rect [100 700 300 720] /P 3 0 R >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// Same fixture as [`tx_widget_without_ap`], but requires viewer-side
/// appearance generation until the CLI's generation pass clears the flag.
fn tx_widget_without_ap_needing_appearances() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
          /V (Hello) /DA (/Helv 12 Tf 0 g) \
          /Rect [100 700 300 720] /P 3 0 R >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// A Tx widget with an existing normal appearance whose `/BBox` endpoints are
/// reversed. qpdf normalizes the box before its ValueSetter computes `Td`.
/// Objects: 1=Catalog, 2=Pages, 3=Page, 4=Widget, 5=Contents, 6=AP/N.
fn tx_widget_with_reversed_bbox() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
          /V (Hello) /DA (/Helv 12 Tf 0 g) /Rect [10 10 200 30] \
          /P 3 0 R /AP << /N 6 0 R >> >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 100 200 0] \
          /Resources <<>> /Length 4 >>\nstream\nq Q\nendstream\nendobj\n"
            .to_vec(),
    ])
}

/// Same as [`tx_widget_without_ap_needing_appearances`], except `/AP/N` is an
/// indirect null. qpdf treats that as a missing normal appearance and replaces
/// it while generating appearances.
fn tx_widget_with_null_ap_n_needing_appearances() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
          /V (Hello) /DA (/Helv 12 Tf 0 g) \
          /Rect [100 700 300 720] /P 3 0 R /AP << /N 6 0 R >> >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"6 0 obj\nnull\nendobj\n".to_vec(),
    ])
}

/// Single-page AcroForm PDF with a Tx widget that has `/V` AND an existing
/// `/AP/N` Form XObject containing the literal value bytes.
/// Objects: 1=Catalog, 2=Pages, 3=Page, 4=Widget, 5=Contents, 6=AP/N XObject
fn tx_widget_with_ap() -> Vec<u8> {
    tx_widget_with_ap_needing(false)
}

/// Same existing-appearance fixture, with `/NeedAppearances true` so the
/// input also exercises qpdf's outer appearance-generation gate.
fn tx_widget_with_ap_needing_appearances() -> Vec<u8> {
    tx_widget_with_ap_needing(true)
}

fn tx_widget_with_ap_needing(need_appearances: bool) -> Vec<u8> {
    let acroform = if need_appearances {
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec()
    } else {
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec()
    };
    assemble_pdf(&[
        acroform,
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
          /V (Hello) /DA (/Helv 12 Tf 0 g) \
          /Rect [100 700 300 720] /P 3 0 R \
          /AP << /N 6 0 R >> >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 200 20] \
          /Length 17 >>\nstream\nBT (Hello) Tj ET\nendstream\nendobj\n"
            .to_vec(),
    ])
}

/// A nested Tx field whose merged terminal widget carries a local value that
/// differs from its top-level ancestor. qpdf's appearance-generation route
/// resolves the widget association directly, so it must render
/// `(child-value)` rather than the ancestor's `(parent-value)`.
fn nested_tx_widget_with_local_value() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true \
          /DR << /Font << /Helv 7 0 R >> >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 6 0 R /Annots [5 0 R] >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /FT /Tx /T (parent) /V (parent-value) /DA (/Helv 12 Tf 0 g) \
          /Kids [5 0 R] >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (child) \
          /V (child-value) /DA (/Helv 12 Tf 0 g) /Parent 4 0 R \
          /Rect [100 700 300 720] /P 3 0 R \
          /AP << /N 8 0 R >> >>\nendobj\n"
            .to_vec(),
        b"6 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"7 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n".to_vec(),
        b"8 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 200 20] \
          /Resources << /ProcSet [/PDF /Text] /Font << /Helv 7 0 R >> >> \
          /Length 33 >>\nstream\n/Tx BMC\nBT (old-value) Tj ET\nEMC\nendstream\nendobj\n"
            .to_vec(),
    ])
}

fn widget_normal_appearance_data(path: &Path) -> Vec<u8> {
    let mut pdf = Pdf::open(BufReader::new(File::open(path).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    helper
        .get_appearance_stream(b"N", None)
        .unwrap()
        .get_stream_data(DecodeLevel::Generalized)
        .unwrap()
        .to_vec()
}

/// Single-page AcroForm PDF with a checkbox (Btn, no pushbutton/radio bits).
/// Widget has /FT /Btn, /AS /Off (unchecked state), /Rect, no /AP.
fn checkbox_widget_without_ap() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /DR << >> >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        // Checkbox: /Ff 0 (no pushbutton bit 17, no radio bit 16)
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (cb1) \
          /Ff 0 /AS /Off \
          /Rect [100 700 120 720] /P 3 0 R >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// Checkbox whose non-`/Off` value has no normal appearance dictionary.
/// qpdf still routes every `/Btn` through `setV(getValue())`, normalizing the
/// fallback on-state to `/Yes` even though it cannot update `/AS` without an
/// identifiable appearance-bearing widget.
fn checkbox_widget_with_value_without_ap_needing_appearances() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> >> >>\nendobj\n".to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n".to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (cb1) /Ff 0 /V /On /AS /Off /Rect [100 700 120 720] /P 3 0 R >>\nendobj\n".to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// Checkbox whose existing state appearances disagree with its `/V`.
/// qpdf 11.9.0 leaves those appearances in place and resets `/AS` to `/V`.
fn checkbox_widget_with_ap_needing_appearances() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> >> >>\nendobj\n".to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n".to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (cb1) /Ff 0 /V /Yes /AS /Off /Rect [100 700 120 720] /P 3 0 R /AP << /N << /Off 6 0 R /Yes 7 0 R >> >> >>\nendobj\n".to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
        b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
    ])
}

/// Direct radio widget with an existing appearance. qpdf only synchronizes
/// radio widgets selected through a field `/Kids` array.
fn direct_radio_widget_with_ap_needing_appearances() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> >> >>\nendobj\n".to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n".to_vec(),
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (rd1) /Ff 32768 /V /Yes /AS /Off /Rect [100 700 120 720] /P 3 0 R /AP << /N << /Off 6 0 R /Yes 7 0 R >> >> >>\nendobj\n".to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
        b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
        b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
    ])
}

/// Single-page AcroForm PDF with a radio button widget.
/// /Ff bit 16 (0x8000) = radio, bit 17 clear.
fn radio_widget_without_ap() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /DR << >> >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        // Radio: /Ff 32768 (0x8000 = bit 16 set, bit 17 clear)
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (rd1) \
          /Ff 32768 /AS /Off \
          /Rect [200 700 220 720] /P 3 0 R >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// Single-page AcroForm PDF with a combo-box (Ch, Ff bit 18 = 0x20000).
/// /V holds the selected option string; /Opt not required for appearance.
fn combo_widget_without_ap() -> Vec<u8> {
    assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
          /AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 10 Tf 0 g) >> >>\nendobj\n"
            .to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
            .to_vec(),
        // Combo: /FT /Ch, /Ff 131072 (0x20000 = bit 18), /V = selected option
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Ch /T (combo1) \
          /Ff 131072 /V (Option2) /DA (/Helv 10 Tf 0 g) \
          /Rect [100 650 300 670] /P 3 0 R >>\nendobj\n"
            .to_vec(),
        b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

/// Single-page PDF with two annotations that both have an /AP/N XObject.
/// Annotation 4: /F 4 (Print bit set)  → should be flattened in Print mode.
/// Annotation 5: /F 0 (no Print bit)   → should survive in Print mode.
/// Annotation 6, 7: the two AP/N XObjects (minimal).
fn two_annots_print_and_non_print() -> Vec<u8> {
    assemble_pdf(&[
        // 1=Catalog (no AcroForm needed; these are plain annotations)
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
          /Contents 8 0 R /Annots [4 0 R 5 0 R] >>\nendobj\n"
            .to_vec(),
        // Annot with Print bit (/F = 4 = 0x4)
        b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (f1) \
          /V (A) /F 4 /Rect [50 700 150 720] /P 3 0 R /AP << /N 6 0 R >> >>\nendobj\n"
            .to_vec(),
        // Annot without Print bit (/F = 0)
        b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (f2) \
          /V (B) /F 0 /Rect [200 700 300 720] /P 3 0 R /AP << /N 7 0 R >> >>\nendobj\n"
            .to_vec(),
        // AP/N for annot 4
        b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] \
          /Length 13 >>\nstream\nBT (A) Tj ET\nendstream\nendobj\n"
            .to_vec(),
        // AP/N for annot 5
        b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] \
          /Length 13 >>\nstream\nBT (B) Tj ET\nendstream\nendobj\n"
            .to_vec(),
        // Page content
        b"8 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
    ])
}

// ── Tests: generate-appearances ───────────────────────────────────────────────

/// The qpdf-shaped top-level argv surface must route appearance generation to
/// the same canonical helper as the native rewrite subcommand.
#[test]
fn top_level_generate_appearances_routes_to_canonical_writer() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("top-level-tx.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "--qdf",
            "--no-original-object-ids",
            "--static-id",
            "--generate-appearances",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut form = flpdf::AcroFormDocumentHelper::new(&mut pdf).unwrap();
    assert!(!form.get_need_appearances().unwrap());
    drop(form);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    let appearance = helper
        .get_appearance_stream(b"N", None)
        .unwrap()
        .get_stream_data(DecodeLevel::Generalized)
        .expect("top-level generation must install /AP/N");
    // The fixture's existing /AP/N already contains "BT (Hello) Tj ET" (no
    // /Tx BMC wrapper), so a bare "Tj" check would pass whether or not this
    // ran the generated-appearance path at all -- both the stale original
    // and a freshly generated marked-content block contain "Tj". Check for
    // the "/Tx BMC" marker (QPDFFormFieldObjectHelper.cc:524-570's generated
    // wrapper) instead: qpdf's `--qdf` forces the token-filter pass to run
    // even with `--compress-streams=n` (confirmed against qpdf 11.9.0, see
    // flpdf-wthas), so this specific flag combination must produce a
    // regenerated, not stale, appearance.
    assert!(
        appearance.windows(7).any(|window| window == b"/Tx BMC"),
        "top-level --qdf --generate-appearances --compress-streams=n must \
         regenerate (not leave stale) the appearance content, matching \
         qpdf 11.9.0's observed behavior: {}",
        String::from_utf8_lossy(&appearance)
    );
}

/// Companion to the `--qdf` case above: without `--qdf`, qpdf's own
/// `QPDFWriter::willFilterStream` (`QPDFWriter.cc:1254-1314`) computes
/// `encode_flags = 0` and `decode_level = qpdf_dl_none` for
/// `--compress-streams=n`, so `QPDF_Stream::pipeStreamData`
/// (`QPDF_Stream.cc:504`) takes `filter = false` and never runs the
/// token-filter pass that installs the generated marked-content block --
/// the pre-existing "BT (Hello) Tj ET" content is written unchanged, even
/// though `--generate-appearances` ran and the widget's value did not
/// change. This is qpdf's own observed behavior (flpdf-wthas), not a flpdf
/// bug; pin it directly against qpdf 11.9.0 so it isn't mistaken for one.
///
/// `--show-object --filtered-stream-data` is a read-only inspection route
/// that is not driven by `QPDFWriter`'s `compress_streams` setting at all,
/// so it cannot observe this write-time behavior -- both tools must
/// actually write an output file and the appearance must be read back from
/// it, matching `top_level_generate_appearances_routes_to_canonical_writer`
/// above.
#[test]
fn top_level_generate_appearances_compress_streams_n_without_qdf_stays_stale_like_qpdf() {
    if !qpdf_available() {
        if std::env::var_os("CI").is_some() {
            panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
        }
        eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
        return;
    }
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("stale-ap-tx.pdf");
    std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();

    let read_appearance = |output: &Path| -> Vec<u8> {
        let mut pdf = Pdf::open(BufReader::new(File::open(output).unwrap())).unwrap();
        let widget_ref = first_widget_ref(&mut pdf);
        let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
        helper
            .get_appearance_stream(b"N", None)
            .unwrap()
            .get_stream_data(DecodeLevel::Generalized)
            .expect("/AP/N must be present after --generate-appearances")
            .to_vec()
    };

    let qpdf_output = temp.path().join("qpdf-out.pdf");
    let qpdf = ProcessCommand::new("qpdf")
        .args([
            "--static-id",
            "--generate-appearances",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&qpdf_output)
        .output()
        .expect("qpdf 11.9.0 must be available");
    assert!(qpdf.status.success(), "qpdf write failed: {qpdf:?}");
    let qpdf_appearance = read_appearance(&qpdf_output);
    assert!(
        !qpdf_appearance
            .windows(7)
            .any(|window| window == b"/Tx BMC"),
        "qpdf itself must leave the appearance stale (no /Tx BMC) for \
         --compress-streams=n without --qdf: {}",
        String::from_utf8_lossy(&qpdf_appearance)
    );
    assert!(
        qpdf_appearance
            .windows(16)
            .any(|window| window == b"BT (Hello) Tj ET"),
        "qpdf must preserve the pre-existing appearance content unchanged: {}",
        String::from_utf8_lossy(&qpdf_appearance)
    );

    let flpdf_output = temp.path().join("flpdf-out.pdf");
    let flpdf = Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "--static-id",
            "--generate-appearances",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&flpdf_output)
        .output()
        .unwrap();
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert!(flpdf.status.success(), "flpdf write failed: {flpdf:?}");
    let flpdf_appearance = read_appearance(&flpdf_output);
    assert_eq!(
        flpdf_appearance,
        qpdf_appearance,
        "stale (non-regenerated) appearance content must match qpdf 11.9.0\nqpdf: {}\nflpdf: {}",
        String::from_utf8_lossy(&qpdf_appearance),
        String::from_utf8_lossy(&flpdf_appearance)
    );
}

/// qpdf applies generateAppearances before its read-only object inspection.
/// The top-level CLI must expose the same transformed widget, not merely
/// accept and discard the flag.
#[test]
fn top_level_generate_appearances_runs_before_show_object_like_qpdf() {
    if !qpdf_available() {
        if std::env::var_os("CI").is_some() {
            panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
        }
        eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
        return;
    }
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("inspection-tx.pdf");
    std::fs::write(&input, tx_widget_without_ap_needing_appearances()).unwrap();

    let qpdf = ProcessCommand::new("qpdf")
        .args(["--show-object=4", "--generate-appearances"])
        .arg(&input)
        .output()
        .expect("qpdf 11.9.0 must be available");
    assert!(qpdf.status.success(), "qpdf show-object failed: {qpdf:?}");
    assert!(
        qpdf.stdout
            .windows(b"/AP".len())
            .any(|window| window == b"/AP"),
        "qpdf must expose the generated normal appearance: {}",
        String::from_utf8_lossy(&qpdf.stdout)
    );

    let flpdf = Command::cargo_bin("flpdf")
        .unwrap()
        .args(["--show-object=4", "--generate-appearances"])
        .arg(&input)
        .output()
        .unwrap();
    assert_eq!(
        flpdf.status.code(),
        qpdf.status.code(),
        "flpdf must accept the same inspection combination as qpdf"
    );
    assert_eq!(
        flpdf.stdout,
        qpdf.stdout,
        "flpdf must render the transformed widget exactly like qpdf: {}",
        String::from_utf8_lossy(&flpdf.stdout)
    );
    assert_eq!(
        flpdf.stderr, qpdf.stderr,
        "flpdf must preserve qpdf diagnostics for the transformed inspection"
    );
}

#[test]
fn reversed_bbox_appearance_matches_qpdf_11_9_0_live() {
    if !qpdf_available() {
        if std::env::var_os("CI").is_some() {
            panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
        }
        eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
        return;
    }

    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("reversed-bbox.pdf");
    std::fs::write(&input, tx_widget_with_reversed_bbox()).unwrap();

    let qpdf = ProcessCommand::new("qpdf")
        .args([
            "--show-object=6",
            "--filtered-stream-data",
            "--generate-appearances",
        ])
        .arg(&input)
        .output()
        .expect("qpdf 11.9.0 must be available");
    assert!(qpdf.status.success(), "qpdf show-object failed: {qpdf:?}");

    let flpdf = Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "--show-object=6",
            "--filtered-stream-data",
            "--generate-appearances",
        ])
        .arg(&input)
        .output()
        .unwrap();
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(
        flpdf.stdout,
        qpdf.stdout,
        "reversed /BBox appearance must match qpdf 11.9.0\nqpdf: {}\nflpdf: {}",
        String::from_utf8_lossy(&qpdf.stdout),
        String::from_utf8_lossy(&flpdf.stdout)
    );
    assert_eq!(flpdf.stderr, qpdf.stderr);
}

/// qpdf accepts the linearized combination even though its two-pass writer
/// may expose the known stale token-filter content on the second pass. The
/// CLI must preserve qpdf's acceptance and output lifecycle rather than
/// rejecting the option combination before the writer runs.
#[test]
fn native_linearize_generate_appearances_is_accepted_like_qpdf() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("linearized-tx.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--static-id",
            "--generate-appearances",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();
    assert!(
        output.is_file(),
        "accepted linearized job must write output"
    );

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["check-linearization", output.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicates::str::contains("no linearization errors"));
}

/// qpdf's `generateAppearancesIfNeeded` returns before scanning pages when
/// `/NeedAppearances` is absent or false. The CLI option must preserve that
/// gate rather than treating the option as an unconditional renderer switch.
#[test]
fn generate_appearances_without_need_marker_is_a_noop() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx-no-marker.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_without_ap()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    assert!(
        helper.get_appearance_dictionary().unwrap().is_null(),
        "qpdf leaves a widget without /AP unchanged when /NeedAppearances is false"
    );
}

/// `--generate-appearances` on a Tx widget adds `/AP/N`, and the uncompressed
/// content stream of that XObject contains a `Tj` operator (the value text is
/// rendered).
#[test]
fn generate_appearances_tx_ap_n_contains_tj() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_without_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--generate-appearances",
            "--stream-data=uncompress",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);

    // /AP/N must be present after generate-appearances, and resolve to the
    // Form XObject stream.
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    let n = helper.get_appearance_stream(b"N", None).unwrap();
    let data = n
        .get_stream_data(DecodeLevel::Generalized)
        .expect("Tx widget should have /AP/N after --generate-appearances");

    // The uncompressed content stream must contain "Tj" (the text-show operator).
    // --stream-data=uncompress both requests the token-filter pass and leaves
    // the resulting stream data uncompressed, matching qpdf's option contract.
    assert!(
        data.windows(2).any(|w| w == b"Tj"),
        "/AP/N content stream must contain Tj operator (observable: value rendered); \
         stream bytes: {:?}",
        std::str::from_utf8(&data).unwrap_or("<non-utf8>")
    );
}

/// `--generate-appearances` updates a non-button widget that already has
/// `/AP/N`, matching qpdf's `ValueSetter` reuse path.
#[test]
fn generate_appearances_tx_reuses_existing_ap() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx_ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=y"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    // /AP/N must still be present and must have gone through the canonical
    // renderer's existing-stream token-filter path.
    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    let n_handle = helper
        .get_appearance_stream(b"N", None)
        .expect("/AP must survive --generate-appearances for widget that already has one");

    assert!(
        n_handle.object_ref().is_some(),
        "/AP/N must remain an indirect stream reference"
    );
    assert!(
        n_handle.as_stream_dict().is_some(),
        "/AP/N must be a stream"
    );
    let data = n_handle.get_stream_data(DecodeLevel::Generalized).unwrap();
    let as_str = std::str::from_utf8(data.as_slice()).unwrap_or("<non-utf8>");

    assert!(
        data.windows(7).any(|w| w == b"/Tx BMC"),
        "existing /AP/N must be updated through the generated-appearance path; data={as_str:?}"
    );
    assert!(
        data.windows(2).any(|w| w == b"Tf"),
        "generated /AP/N must carry the default-appearance font selection; data={as_str:?}"
    );
    // This fixture has no `/Tx BMC` wrapper. qpdf's ValueSetter therefore
    // keeps the source tokens and appends a generated marked-content block at
    // EOF (`QPDFFormFieldObjectHelper.cc:524-570`), rather than discarding the
    // original bytes.
    assert!(
        data.windows(16).any(|w| w == b"BT (Hello) Tj ET"),
        "qpdf's no-wrapper fallback must preserve source appearance content; data={as_str:?}"
    );
}

/// Appearance generation must use qpdf's direct widget-to-field association,
/// not the top-level projection exposed by page annotation enumeration.
#[test]
fn generate_appearances_uses_nested_terminal_field_value() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("nested-tx.pdf");
    let flpdf_output = temp.path().join("flpdf.pdf");
    std::fs::write(&input, nested_tx_widget_with_local_value()).unwrap();
    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=y"])
        .arg(&input)
        .arg(&flpdf_output)
        .assert()
        .success();

    let flpdf_data = widget_normal_appearance_data(&flpdf_output);
    assert!(
        flpdf_data
            .windows(b"child-value".len())
            .any(|w| w == b"child-value"),
        "flpdf must render the same terminal field value; data={flpdf_data:?}"
    );
    assert!(
        !flpdf_data
            .windows(b"parent-value".len())
            .any(|w| w == b"parent-value"),
        "flpdf must not render the top-level ancestor's value; data={flpdf_data:?}"
    );
}

/// qpdf does not synthesize button appearances when none exists.
#[test]
fn generate_appearances_checkbox_without_ap_leaves_ap_absent() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("cb.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, checkbox_widget_without_ap()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    assert!(
        helper.get_appearance_dictionary().unwrap().is_null(),
        "qpdf leaves a button without /AP unchanged"
    );
}

#[test]
fn generate_appearances_routes_checkbox_without_ap_through_set_value() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("cb-value-no-ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(
        &input,
        checkbox_widget_with_value_without_ap_needing_appearances(),
    )
    .unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .failure()
        .code(3)
        .stderr(predicates::str::contains(
            "unable to set the value of this checkbox",
        ));

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let widget = pdf.resolve_canonical_object(widget_ref).unwrap();
    assert_eq!(
        widget.try_get_key(b"/V").unwrap().as_name(),
        Some(b"Yes".to_vec())
    );
    assert_eq!(
        widget.try_get_key(b"/AS").unwrap().as_name(),
        Some(b"Off".to_vec())
    );
    assert!(!widget.try_has_key(b"/AP").unwrap());
}

/// qpdf does not synthesize radio appearances when none exists.
#[test]
fn generate_appearances_radio_without_ap_leaves_ap_absent() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("rd.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, radio_widget_without_ap()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    assert!(
        helper.get_appearance_dictionary().unwrap().is_null(),
        "qpdf leaves a radio button without /AP unchanged"
    );
}

/// Existing checkbox appearances are preserved while `/AS` is synchronized to `/V`.
#[test]
fn generate_appearances_checkbox_with_ap_synchronizes_as_to_value() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("cb-existing-ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, checkbox_widget_with_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let widget = pdf.resolve_canonical_object(widget_ref).unwrap();
    assert_eq!(
        widget.try_get_key(b"/AS").unwrap().as_name(),
        Some(b"Yes".to_vec())
    );
    let ap = widget.try_get_key(b"/AP").unwrap();
    let normal = ap.try_get_key(b"/N").unwrap();
    assert!(normal.try_has_key(b"/Off").unwrap() && normal.try_has_key(b"/Yes").unwrap());
}

/// A direct radio widget retains `/AS`; qpdf requires a parent field `/Kids`
/// array before it can identify and synchronize its child widget.
#[test]
fn generate_appearances_direct_radio_with_ap_leaves_as_unchanged() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("rd-existing-ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, direct_radio_widget_with_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--generate-appearances", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .failure()
        .code(3)
        .stderr(predicates::str::contains(
            "don't know how to set the value of this field as a radio button",
        ));

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let widget = pdf.resolve_canonical_object(widget_ref).unwrap();
    assert_eq!(
        widget.try_get_key(b"/AS").unwrap().as_name(),
        Some(b"Off".to_vec())
    );
    let ap = widget.try_get_key(b"/AP").unwrap();
    let normal = ap.try_get_key(b"/N").unwrap();
    assert!(normal.try_has_key(b"/Off").unwrap() && normal.try_has_key(b"/Yes").unwrap());
}

/// `--generate-appearances` on a combo-box widget adds `/AP/N`, and the
/// content stream contains `Tj` (the selected option value is rendered).
#[test]
fn generate_appearances_combo_ap_n_contains_tj() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("combo.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, combo_widget_without_ap()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--generate-appearances",
            "--stream-data=uncompress",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
    let n = helper.get_appearance_stream(b"N", None).unwrap();
    let data = n
        .get_stream_data(DecodeLevel::Generalized)
        .expect("combo widget should have /AP/N after --generate-appearances");
    assert!(
        data.windows(2).any(|w| w == b"Tj"),
        "combo /AP/N content stream must contain Tj (selected value rendered); \
         stream={:?}",
        std::str::from_utf8(&data).unwrap_or("<non-utf8>")
    );
}

// ── Tests: flatten=all ────────────────────────────────────────────────────────

/// `--flatten-annotations=all` bakes the widget's appearance into page content:
/// - the annotation is removed from `/Annots`
/// - the page content stream contains a `Do` operator (the XObject invocation)
#[test]
fn flatten_all_annot_removed_and_do_in_content() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx_ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_with_ap()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--flatten-annotations=all",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();

    // Annotation must be gone from /Annots.
    let annots = page_annotation_handles(&mut pdf, page_refs[0]);
    assert!(
        annots.is_empty(),
        "flatten=all must remove widget from /Annots, found {} annotation(s)",
        annots.len()
    );

    // Page content must contain a Do operator (the flattened XObject).
    let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
    assert!(
        content.windows(2).any(|w| w == b"Do"),
        "flatten=all must insert a Do operator into page content; \
         content={:?}",
        std::str::from_utf8(&content).unwrap_or("<non-utf8>")
    );
}

/// `--generate-appearances` + `--flatten-annotations=all` pipeline: a Tx
/// widget without an initial `/AP` gets an appearance generated, then is
/// flattened.  Both steps must leave the annotation absent from `/Annots` and
/// a `Do` in page content.
#[test]
fn generate_then_flatten_all_do_in_content() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx_no_ap.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_without_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--generate-appearances",
            "--flatten-annotations=all",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();

    let annots = page_annotation_handles(&mut pdf, page_refs[0]);
    assert!(
        annots.is_empty(),
        "generate+flatten=all must remove widget from /Annots, found {} annotation(s)",
        annots.len()
    );

    let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
    assert!(
        content.windows(2).any(|w| w == b"Do"),
        "generate+flatten=all must insert Do into page content; \
         content={:?}",
        std::str::from_utf8(&content).unwrap_or("<non-utf8>")
    );
}

/// qpdf clears `/NeedAppearances` after generating widget appearances, so the
/// immediately following flatten pass must not preserve those widgets.
#[test]
fn generate_then_flatten_clears_need_appearances() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx_need_appearances.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_without_ap_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--generate-appearances",
            "--flatten-annotations=all",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_ref = flpdf::pages::page_refs(&mut pdf).unwrap()[0];
    assert!(
        page_annotation_handles(&mut pdf, page_ref).is_empty(),
        "generated widget must be flattened after qpdf clears NeedAppearances"
    );
}

#[test]
fn generate_then_flatten_replaces_indirect_null_normal_appearance() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("tx_null_ap_n.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, tx_widget_with_null_ap_n_needing_appearances()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--generate-appearances",
            "--flatten-annotations=all",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_ref = flpdf::pages::page_refs(&mut pdf).unwrap()[0];
    assert!(
        page_annotation_handles(&mut pdf, page_ref).is_empty(),
        "generated widget must be flattened after qpdf clears NeedAppearances"
    );
    let content = flpdf::pages::page_content_bytes(&mut pdf, page_ref).unwrap();
    assert!(
        content.windows(2).any(|window| window == b"Do"),
        "an indirect null /AP/N must be regenerated before flattening; content={:?}",
        std::str::from_utf8(&content).unwrap_or("<non-utf8>")
    );
}

// ── Tests: flatten=print ──────────────────────────────────────────────────────

/// `--flatten-annotations=print` draws only Print annotations, but qpdf drops
/// every annotation that has a selected appearance stream.
#[test]
fn flatten_print_draws_print_bit_annot_and_removes_all_selected_appearances() {
    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("two_annots.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, two_annots_print_and_non_print()).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--flatten-annotations=print",
            "--compress-streams=n",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();

    let annots = page_annotation_handles(&mut pdf, page_refs[0]);
    assert!(annots.is_empty());

    // Page content must have a Do (from the Print-bit annotation being flattened).
    let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
    assert!(
        content.windows(2).any(|w| w == b"Do"),
        "flatten=print must insert Do for the Print-bit annotation; \
         content={:?}",
        std::str::from_utf8(&content).unwrap_or("<non-utf8>")
    );
}

// ── Tests: flatten-rotation (CLI e2e) ─────────────────────────────────────────

/// `--flatten-rotation` removes `/Rotate` from a page dictionary (e2e CLI
/// gate that complements the unit tests in the library crate).  This test
/// does not duplicate the existing `rewrite_flatten_rotation_removes_rotate`
/// in cli_tests.rs; it adds a second fixture (two-page PDF) to verify that
/// all pages are processed, not just the first.
#[test]
fn flatten_rotation_processes_all_pages() {
    // Two-page PDF: page 1 has /Rotate 90, page 2 has /Rotate 180.
    let input_bytes = assemble_pdf(&[
        b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(),
        b"2 0 obj\n<< /Type /Pages /Count 2 /Kids [3 0 R 5 0 R] >>\nendobj\n".to_vec(),
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /Rotate 90 \
          /MediaBox [0 0 200 100] /Contents 4 0 R >>\nendobj\n"
            .to_vec(),
        b"4 0 obj\n<< /Length 14 >>\nstream\nBT (p1) Tj ET\nendstream\nendobj\n".to_vec(),
        b"5 0 obj\n<< /Type /Page /Parent 2 0 R /Rotate 180 \
          /MediaBox [0 0 612 792] /Contents 6 0 R >>\nendobj\n"
            .to_vec(),
        b"6 0 obj\n<< /Length 14 >>\nstream\nBT (p2) Tj ET\nendstream\nendobj\n".to_vec(),
    ]);

    let temp = tempfile::tempdir().unwrap();
    let input = temp.path().join("two_rotated.pdf");
    let output = temp.path().join("out.pdf");
    std::fs::write(&input, input_bytes).unwrap();

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", "--flatten-rotation", "--compress-streams=n"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();
    assert_eq!(page_refs.len(), 2, "output must have 2 pages");

    for (i, &page_ref) in page_refs.iter().enumerate() {
        let page_obj = pdf.resolve_canonical_object(page_ref).unwrap();
        let rotate = page_obj.try_get_key(b"/Rotate").unwrap().as_integer();
        assert!(
            rotate.is_none() || rotate == Some(0),
            "page {} /Rotate should be absent or 0 after --flatten-rotation, got {rotate:?}",
            i + 1
        );
    }
}