flpdf-cli 0.2.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
//! Integration tests: AcroForm/annotation transform observable equivalence
//!
//! Covers: generate-appearances (Tx value→Tj, checkbox/radio state-dict,
//! 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.
//!
//! All rewrite calls use `--compress-streams=n` so that page content and
//! appearance streams can be inspected as raw bytes without a FlateDecode
//! decoding step.
//!
//! # qpdf divergence
//!
//! See `docs/qpdf-compat-decisions.md` §AcroForm & annotation transforms.

use assert_cmd::Command;
use flpdf::{AnnotationObjectHelper, Object, Pdf};
use std::fs::File;
use std::io::BufReader;

mod common;
use common::first_widget_ref;

// ── 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(),
    ])
}

/// 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> {
    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(),
        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(),
    ])
}

/// 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(),
    ])
}

/// 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] /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(),
    ])
}

/// Resolve the object referred to by `obj`, following a single level of
/// indirect reference when needed.
fn resolve_one<R: std::io::Read + std::io::Seek>(
    pdf: &mut Pdf<R>,
    obj: Object,
) -> flpdf::Result<Object> {
    match obj {
        Object::Reference(r) => pdf.resolve(r),
        other => Ok(other),
    }
}

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

/// `--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()).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);

    // /AP/N must be present after generate-appearances.
    // Use a block to end the borrow of `pdf` before the resolve call below.
    let n_val = {
        let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
        let ap = helper
            .appearance()
            .unwrap()
            .expect("Tx widget should have /AP after --generate-appearances");
        ap.get("N").cloned().expect("/AP should have /N entry")
    };

    // Resolve the /N value to the XObject stream.
    let n_obj = resolve_one(&mut pdf, n_val).unwrap();
    let stream = n_obj
        .as_stream()
        .expect("/AP/N should be a Form XObject stream");

    // The uncompressed content stream must contain "Tj" (the text-show operator).
    // We use --compress-streams=n so stream.data is the raw uncompressed bytes.
    assert!(
        stream.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(&stream.data).unwrap_or("<non-utf8>")
    );
}

/// `--generate-appearances` does **not** overwrite a widget that already has
/// `/AP/N` — the original XObject is preserved (observable: existing appearance
/// is not discarded).
#[test]
fn generate_appearances_tx_skips_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()).unwrap();

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

    // /AP/N must still be present; the existing stream content must contain the
    // original literal "(Hello) Tj ET" — not overwritten with a newly generated one.
    let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
    let widget_ref = first_widget_ref(&mut pdf);
    let n_val = {
        let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
        let ap = helper
            .appearance()
            .unwrap()
            .expect("/AP must survive --generate-appearances for widget that already has one");
        ap.get("N").cloned().expect("/AP/N must be present")
    };

    let n_obj = resolve_one(&mut pdf, n_val).unwrap();
    let stream = n_obj.as_stream().expect("/AP/N must be a stream");
    let data = &stream.data;
    let as_str = std::str::from_utf8(data).unwrap_or("<non-utf8>");

    // The widget arrived with a hand-authored appearance `BT (Hello) Tj ET`.
    // --generate-appearances must NOT overwrite it. A regenerated appearance
    // would (a) drop the original byte sequence and (b) carry the generator's
    // distinctive markers — a `/Tx BMC` marked-content wrapper and a `Tf`
    // font-selection operator — neither of which the original fixture has.
    // (Asserting "(Hello) Tj" alone is insufficient: a regenerated appearance
    // for the value "Hello" would also contain it.)
    assert!(
        data.windows(16).any(|w| w == b"BT (Hello) Tj ET"),
        "original /AP/N content must be preserved verbatim; data={as_str:?}"
    );
    assert!(
        !data.windows(7).any(|w| w == b"/Tx BMC"),
        "original /AP/N must not be replaced by a generated appearance \
         (found /Tx BMC marker); data={as_str:?}"
    );
    assert!(
        !data.windows(2).any(|w| w == b"Tf"),
        "original /AP/N must not be replaced by a generated appearance \
         (found Tf operator); data={as_str:?}"
    );
}

/// `--generate-appearances` on a checkbox widget installs `/AP/N` as a state
/// dictionary (with at least one non-Off key) — observable equivalence for
/// on/off checkbox rendering.
#[test]
fn generate_appearances_checkbox_creates_state_dict() {
    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 n_val = {
        let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
        let ap = helper
            .appearance()
            .unwrap()
            .expect("checkbox widget should have /AP after --generate-appearances");
        ap.get("N").cloned().expect("/AP should have /N entry")
    };

    // For checkbox/radio the /AP/N value must be a Dictionary (state dict),
    // not a stream directly.  It contains at least an "Off" state key and an
    // on-state key (e.g. "Yes").
    let n_obj = resolve_one(&mut pdf, n_val).unwrap();
    let state_dict = n_obj
        .as_dict()
        .expect("/AP/N for checkbox must be a state dictionary, not a bare stream");

    // "Off" key must be present (empty/transparent appearance for unchecked state).
    assert!(
        state_dict.get("Off").is_some(),
        "checkbox /AP/N state dict must have an 'Off' entry"
    );

    // At least one non-Off key must exist (the checked-state appearance).
    let has_on_state = state_dict.iter().any(|(k, _)| k != b"Off");
    assert!(
        has_on_state,
        "checkbox /AP/N state dict must have a non-Off (on-state) entry"
    );

    // Confirm at least 2 total entries (on-state + Off).
    let entry_count = state_dict.iter().count();
    assert!(
        entry_count >= 2,
        "checkbox /AP/N state dict should have >=2 entries (on-state + Off), got {}",
        entry_count
    );
}

/// `--generate-appearances` on a radio button widget installs `/AP/N` as a
/// state dictionary — same structural requirement as checkbox.
#[test]
fn generate_appearances_radio_creates_state_dict() {
    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 n_val = {
        let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
        let ap = helper
            .appearance()
            .unwrap()
            .expect("radio widget should have /AP after --generate-appearances");
        ap.get("N").cloned().expect("/AP should have /N entry")
    };

    let n_obj = resolve_one(&mut pdf, n_val).unwrap();
    let state_dict = n_obj
        .as_dict()
        .expect("/AP/N for radio must be a state dictionary");

    let entry_count = state_dict.iter().count();
    assert!(
        entry_count >= 2,
        "radio /AP/N state dict should have >=2 entries, got {}",
        entry_count
    );
    assert!(
        state_dict.get("Off").is_some(),
        "radio /AP/N state dict must have an 'Off' entry"
    );
}

/// `--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", "--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 n_val = {
        let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
        let ap = helper
            .appearance()
            .unwrap()
            .expect("combo widget should have /AP after --generate-appearances");
        ap.get("N").cloned().expect("/AP should have /N entry")
    };

    let n_obj = resolve_one(&mut pdf, n_val).unwrap();
    let stream = n_obj.as_stream().expect("/AP/N for combo must be a stream");
    assert!(
        stream.data.windows(2).any(|w| w == b"Tj"),
        "combo /AP/N content stream must contain Tj (selected value rendered); \
         stream={:?}",
        std::str::from_utf8(&stream.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 = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
    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()).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 = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
    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>")
    );
}

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

/// `--flatten-annotations=print` removes only annotations with the Print bit
/// (bit 3, /F & 0x4 != 0) and leaves annotations without it in `/Annots`.
#[test]
fn flatten_print_removes_print_bit_annot_only() {
    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();

    // Exactly one annotation must remain (the non-Print one).
    let annots = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
    assert_eq!(
        annots.len(),
        1,
        "flatten=print must leave exactly 1 annotation (the non-Print one), found {}",
        annots.len()
    );

    // The surviving annotation must be the non-Print widget. Identify it by
    // the behavioral property (Print bit clear in /F) rather than its object
    // number, which is unstable under the Catalog-first renumber. An absent /F
    // means no flags set, i.e. no Print bit — that is exactly the survivor.
    let survivor = pdf.resolve(annots[0].annot_ref).unwrap();
    let survivor_dict = survivor
        .as_dict()
        .expect("surviving annotation must resolve to a dictionary");
    // An absent /F means no flags set, i.e. no Print bit — that is the survivor.
    let f = survivor_dict
        .get("F")
        .and_then(|o| o.as_integer())
        .unwrap_or(0);
    assert_eq!(
        f & 0x4,
        0,
        "surviving annotation must be the non-Print widget (Print bit clear in /F), got /F={f}"
    );

    // 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(page_ref).unwrap();
        let Object::Dictionary(dict) = page_obj else {
            panic!("page {} is not a dictionary", i + 1);
        };
        let rotate = dict.get("Rotate").and_then(|o| o.as_integer());
        assert!(
            rotate.is_none() || rotate == Some(0),
            "page {} /Rotate should be absent or 0 after --flatten-rotation, got {rotate:?}",
            i + 1
        );
    }
}