flpdf-cli 0.4.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
//! CLI E2E tests for --stream-data={preserve,uncompress,compress} (flpdf-jcd.6).
//!
//! Each test builds a minimal PDF whose object `4 0 R` carries a FlateDecode
//! stream, runs `flpdf rewrite --stream-data=<mode>` against it, then re-parses
//! the output to assert the **per-mode behavioural difference** directly:
//!
//!   preserve   → /Filter /FlateDecode kept, raw bytes round-trip
//!   uncompress → /Filter absent, raw bytes appear verbatim in the stream
//!   compress   → /Filter /FlateDecode present, decoded bytes round-trip
//!   override   → --stream-data=uncompress wins over --compress-streams=y
//!
//! flpdf-9hc.7.7 additions:
//!   LZWDecode ×3 modes, DCTDecode/JBIG2Decode/JPXDecode/CCITTFaxDecode passthrough ×3 modes,
//!   LZWDecode show-stream text-readable test.
//!
//! These assertions catch regressions where the three modes would silently
//! collapse to identical behaviour (mere "PDF is valid" would not).

use assert_cmd::Command;
use flpdf::{filters, Dictionary, Object, ObjectRef, Pdf, Stream};
use std::io::Cursor;

#[path = "support/filter_fixtures.rs"]
mod filter_fixtures;
use filter_fixtures::{
    build_pdf_with_prefiltered_stream, LZW_ABABABABABABAB_EC1, LZW_ABABABABABABAB_PLAIN,
};

// ---------------------------------------------------------------------------
// Helper: build a minimal PDF with a FlateDecode-wrapped content stream.
// ---------------------------------------------------------------------------

fn build_pdf_with_flate_stream(raw: &[u8]) -> Vec<u8> {
    let mut d = Dictionary::new();
    d.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
    let encoded = filters::encode_stream_data(&d, raw).expect("encode FlateDecode stream");

    let mut pdf_bytes: Vec<u8> = b"%PDF-1.4\n".to_vec();
    let mut offsets = Vec::<usize>::new();

    offsets.push(pdf_bytes.len());
    pdf_bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    offsets.push(pdf_bytes.len());
    pdf_bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
    offsets.push(pdf_bytes.len());
    pdf_bytes.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n",
    );

    offsets.push(pdf_bytes.len());
    let header = format!(
        "4 0 obj\n<< /Length {} /Filter /FlateDecode >>\nstream\n",
        encoded.len()
    );
    pdf_bytes.extend_from_slice(header.as_bytes());
    pdf_bytes.extend_from_slice(&encoded);
    pdf_bytes.extend_from_slice(b"\nendstream\nendobj\n");

    let xref_offset = pdf_bytes.len();
    let n = offsets.len() + 1;
    pdf_bytes.extend_from_slice(format!("xref\n0 {n}\n").as_bytes());
    pdf_bytes.extend_from_slice(b"0000000000 65535 f \n");
    for o in &offsets {
        pdf_bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
    }
    pdf_bytes.extend_from_slice(
        format!("trailer\n<< /Size {n} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
            .as_bytes(),
    );
    pdf_bytes
}

// ---------------------------------------------------------------------------
// Helper: write `src` to a temp file, run flpdf rewrite with the given extra
// args, and return the output PDF bytes.
// ---------------------------------------------------------------------------

fn rewrite_with_args(src: &[u8], extra_args: &[&str]) -> Vec<u8> {
    let temp = tempfile::tempdir().unwrap();
    let in_path = temp.path().join("in.pdf");
    let out_path = temp.path().join("out.pdf");
    std::fs::write(&in_path, src).unwrap();

    let mut cmd = Command::cargo_bin("flpdf").unwrap();
    let mut args = vec!["rewrite", in_path.to_str().unwrap()];
    args.extend_from_slice(extra_args);
    args.push(out_path.to_str().unwrap());
    cmd.args(&args).assert().success();

    std::fs::read(&out_path).unwrap()
}

// ---------------------------------------------------------------------------
// Helper: extract object `4 0 R` as a Stream from an in-memory PDF.
// ---------------------------------------------------------------------------

fn extract_obj4(pdf_bytes: &[u8]) -> Stream {
    let mut pdf = Pdf::open(Cursor::new(pdf_bytes.to_vec())).expect("open output PDF");
    match pdf.resolve(ObjectRef::new(4, 0)).expect("resolve 4 0 R") {
        Object::Stream(s) => s,
        other => panic!("expected stream, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Test: --stream-data=preserve keeps /FlateDecode and original encoded bytes
// ---------------------------------------------------------------------------

#[test]
fn cli_stream_data_preserve_keeps_filter() {
    let raw = b"preserve-mode-payload: keep my /Filter /FlateDecode verbatim";
    let src = build_pdf_with_flate_stream(raw);
    let out = rewrite_with_args(&src, &["--stream-data=preserve"]);

    let stream = extract_obj4(&out);
    assert_eq!(
        stream.dict.get("Filter"),
        Some(&Object::Name(b"FlateDecode".to_vec())),
        "--stream-data=preserve must keep /Filter /FlateDecode on the output stream"
    );
    // Decode the preserved stream to confirm content is untouched (preserve
    // passes encoded bytes through verbatim; decode_stream_data round-trips).
    let decoded = filters::decode_stream_data(&stream.dict, &stream.data).expect("decode");
    assert_eq!(
        decoded.as_slice(),
        raw,
        "preserve must yield the original raw payload after decode"
    );
}

// ---------------------------------------------------------------------------
// Test: --stream-data=uncompress strips /Filter and writes raw bytes
// ---------------------------------------------------------------------------

#[test]
fn cli_stream_data_uncompress_strips_filter() {
    let raw = b"uncompress-mode-payload: my /Filter should be gone in the output";
    let src = build_pdf_with_flate_stream(raw);
    let out = rewrite_with_args(&src, &["--stream-data=uncompress"]);

    let stream = extract_obj4(&out);
    assert!(
        stream.dict.get("Filter").is_none(),
        "--stream-data=uncompress must drop /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data, raw,
        "uncompress must write the decoded raw payload directly"
    );
}

// ---------------------------------------------------------------------------
// Test: --stream-data=compress keeps /FlateDecode wrapper and round-trips data
// ---------------------------------------------------------------------------

#[test]
fn cli_stream_data_compress_wraps_with_flate() {
    let raw = b"compress-mode-payload: keep me FlateDecode-wrapped in the output";
    let src = build_pdf_with_flate_stream(raw);
    let out = rewrite_with_args(&src, &["--stream-data=compress"]);

    let stream = extract_obj4(&out);
    assert_eq!(
        stream.dict.get("Filter"),
        Some(&Object::Name(b"FlateDecode".to_vec())),
        "--stream-data=compress must keep /Filter /FlateDecode (decode→re-encode)"
    );
    let decoded = filters::decode_stream_data(&stream.dict, &stream.data).expect("decode");
    assert_eq!(
        decoded.as_slice(),
        raw,
        "compress must round-trip the original payload via FlateDecode"
    );
}

// ---------------------------------------------------------------------------
// Test: --stream-data wins over --compress-streams when both are supplied
// ---------------------------------------------------------------------------

#[test]
fn cli_stream_data_overrides_compress_streams() {
    let raw = b"override-mode-payload: --stream-data must beat --compress-streams=y";
    let src = build_pdf_with_flate_stream(raw);
    // uncompress should win over the conflicting compress-streams=y.
    let out = rewrite_with_args(&src, &["--stream-data=uncompress", "--compress-streams=y"]);

    let stream = extract_obj4(&out);
    assert!(
        stream.dict.get("Filter").is_none(),
        "--stream-data=uncompress must take precedence and strip /Filter even when \
         --compress-streams=y is also passed; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data, raw,
        "override path must still write the decoded raw payload"
    );
}

// ===========================================================================
// flpdf-9hc.7.7: LZWDecode × 3 modes + passthrough × 3 modes
// ===========================================================================

// ---------------------------------------------------------------------------
// LZWDecode × 3 modes
// ---------------------------------------------------------------------------

/// --stream-data=preserve: /Filter /LZWDecode kept, decoded payload round-trips.
#[test]
fn cli_stream_data_lzw_preserve() {
    let src = build_pdf_with_prefiltered_stream(LZW_ABABABABABABAB_EC1, "/LZWDecode", None);
    let out = rewrite_with_args(&src, &["--stream-data=preserve"]);

    let stream = extract_obj4(&out);
    assert_eq!(
        stream.dict.get("Filter"),
        Some(&Object::Name(b"LZWDecode".to_vec())),
        "--stream-data=preserve must keep /Filter /LZWDecode"
    );
    let decoded = filters::decode_stream_data(&stream.dict, &stream.data).expect("lzw decode");
    assert_eq!(
        decoded.as_slice(),
        LZW_ABABABABABABAB_PLAIN,
        "preserve: decoded payload must match the original"
    );
}

/// --stream-data=uncompress: /Filter stripped, raw LZW payload written directly.
#[test]
fn cli_stream_data_lzw_uncompress() {
    let src = build_pdf_with_prefiltered_stream(LZW_ABABABABABABAB_EC1, "/LZWDecode", None);
    let out = rewrite_with_args(&src, &["--stream-data=uncompress"]);

    let stream = extract_obj4(&out);
    assert!(
        stream.dict.get("Filter").is_none(),
        "--stream-data=uncompress must strip /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        LZW_ABABABABABABAB_PLAIN,
        "uncompress: stream data must be the decoded LZW payload"
    );
}

/// --stream-data=compress: LZW decoded and re-encoded as FlateDecode.
#[test]
fn cli_stream_data_lzw_compress() {
    let src = build_pdf_with_prefiltered_stream(LZW_ABABABABABABAB_EC1, "/LZWDecode", None);
    let out = rewrite_with_args(&src, &["--stream-data=compress"]);

    let stream = extract_obj4(&out);
    assert_eq!(
        stream.dict.get("Filter"),
        Some(&Object::Name(b"FlateDecode".to_vec())),
        "--stream-data=compress must change /Filter to /FlateDecode"
    );
    let decoded = filters::decode_stream_data(&stream.dict, &stream.data).expect("flate decode");
    assert_eq!(
        decoded.as_slice(),
        LZW_ABABABABABABAB_PLAIN,
        "compress: FlateDecode-wrapped stream must round-trip to original LZW payload"
    );
}

// ---------------------------------------------------------------------------
// DCTDecode passthrough × 3 modes
//
// All three --stream-data modes must leave a passthrough codec intact:
// /Filter preserved, stream data byte-identical.  This is guaranteed by the
// decode-failure early-return in apply_stream_compress_policy.
//
// --remove-unreferenced-resources=no is used to prevent the resources scanner
// from trying to decode the passthrough content stream. (flpdf-s9s)
// ---------------------------------------------------------------------------

/// DCTDecode × preserve: /Filter preserved, data byte-identical.
#[test]
fn cli_stream_data_dct_preserve() {
    let fake_jpeg: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0xAA, 0xBB];
    let src = build_pdf_with_prefiltered_stream(fake_jpeg, "/DCTDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=preserve",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"DCTDecode"),
        "DCTDecode preserve: /Filter must remain /DCTDecode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpeg,
        "DCTDecode preserve: stream data must be byte-identical"
    );
}

/// DCTDecode × uncompress: passthrough codec cannot be decoded — /Filter and
/// data must be left intact (decode-failure verbatim path in writer).
#[test]
fn cli_stream_data_dct_uncompress() {
    let fake_jpeg: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0xAA, 0xBB];
    let src = build_pdf_with_prefiltered_stream(fake_jpeg, "/DCTDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=uncompress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"DCTDecode"),
        "DCTDecode uncompress: passthrough must keep /Filter /DCTDecode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpeg,
        "DCTDecode uncompress: stream data must be byte-identical (passthrough intact)"
    );
}

/// DCTDecode × compress: passthrough codec cannot be decoded — /Filter and
/// data must remain intact.
#[test]
fn cli_stream_data_dct_compress() {
    let fake_jpeg: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0xAA, 0xBB];
    let src = build_pdf_with_prefiltered_stream(fake_jpeg, "/DCTDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=compress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"DCTDecode"),
        "DCTDecode compress: passthrough must keep /Filter /DCTDecode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpeg,
        "DCTDecode compress: stream data must be byte-identical (passthrough intact)"
    );
}

// ---------------------------------------------------------------------------
// CCITTFaxDecode passthrough × 3 modes
// ---------------------------------------------------------------------------

/// CCITTFaxDecode × preserve: intact.
#[test]
fn cli_stream_data_ccitt_preserve() {
    let fake_ccitt: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD, 0xFC];
    let src = build_pdf_with_prefiltered_stream(
        fake_ccitt,
        "/CCITTFaxDecode",
        Some("<< /K -1 /Columns 8 >>"),
    );
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=preserve",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"CCITTFaxDecode"),
        "CCITTFaxDecode preserve: /Filter must remain /CCITTFaxDecode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_ccitt,
        "CCITTFaxDecode preserve: stream data must be byte-identical"
    );
}

/// CCITTFaxDecode × uncompress: passthrough intact.
#[test]
fn cli_stream_data_ccitt_uncompress() {
    let fake_ccitt: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD, 0xFC];
    let src = build_pdf_with_prefiltered_stream(
        fake_ccitt,
        "/CCITTFaxDecode",
        Some("<< /K -1 /Columns 8 >>"),
    );
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=uncompress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"CCITTFaxDecode"),
        "CCITTFaxDecode uncompress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_ccitt,
        "CCITTFaxDecode uncompress: stream data must be byte-identical"
    );
}

/// CCITTFaxDecode × compress: passthrough intact.
#[test]
fn cli_stream_data_ccitt_compress() {
    let fake_ccitt: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD, 0xFC];
    let src = build_pdf_with_prefiltered_stream(
        fake_ccitt,
        "/CCITTFaxDecode",
        Some("<< /K -1 /Columns 8 >>"),
    );
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=compress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"CCITTFaxDecode"),
        "CCITTFaxDecode compress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_ccitt,
        "CCITTFaxDecode compress: stream data must be byte-identical"
    );
}

// ---------------------------------------------------------------------------
// JBIG2Decode passthrough × 3 modes
// ---------------------------------------------------------------------------

/// JBIG2Decode × preserve: /Filter preserved, data byte-identical.
#[test]
fn cli_stream_data_jbig2_preserve() {
    let fake_jbig2: &[u8] = &[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
    let src = build_pdf_with_prefiltered_stream(fake_jbig2, "/JBIG2Decode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=preserve",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JBIG2Decode"),
        "JBIG2Decode preserve: /Filter must remain /JBIG2Decode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jbig2,
        "JBIG2Decode preserve: stream data must be byte-identical"
    );
}

/// JBIG2Decode × uncompress: passthrough intact.
#[test]
fn cli_stream_data_jbig2_uncompress() {
    let fake_jbig2: &[u8] = &[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
    let src = build_pdf_with_prefiltered_stream(fake_jbig2, "/JBIG2Decode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=uncompress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JBIG2Decode"),
        "JBIG2Decode uncompress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jbig2,
        "JBIG2Decode uncompress: stream data must be byte-identical"
    );
}

/// JBIG2Decode × compress: passthrough intact.
#[test]
fn cli_stream_data_jbig2_compress() {
    let fake_jbig2: &[u8] = &[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
    let src = build_pdf_with_prefiltered_stream(fake_jbig2, "/JBIG2Decode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=compress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JBIG2Decode"),
        "JBIG2Decode compress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jbig2,
        "JBIG2Decode compress: stream data must be byte-identical"
    );
}

// ---------------------------------------------------------------------------
// JPXDecode passthrough × 3 modes
// ---------------------------------------------------------------------------

/// JPXDecode × preserve: /Filter preserved, data byte-identical.
#[test]
fn cli_stream_data_jpx_preserve() {
    let fake_jpx: &[u8] = &[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0xDD, 0xEE];
    let src = build_pdf_with_prefiltered_stream(fake_jpx, "/JPXDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=preserve",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JPXDecode"),
        "JPXDecode preserve: /Filter must remain /JPXDecode; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpx,
        "JPXDecode preserve: stream data must be byte-identical"
    );
}

/// JPXDecode × uncompress: passthrough intact.
#[test]
fn cli_stream_data_jpx_uncompress() {
    let fake_jpx: &[u8] = &[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0xDD, 0xEE];
    let src = build_pdf_with_prefiltered_stream(fake_jpx, "/JPXDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=uncompress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JPXDecode"),
        "JPXDecode uncompress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpx,
        "JPXDecode uncompress: stream data must be byte-identical"
    );
}

/// JPXDecode × compress: passthrough intact.
#[test]
fn cli_stream_data_jpx_compress() {
    let fake_jpx: &[u8] = &[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0xDD, 0xEE];
    let src = build_pdf_with_prefiltered_stream(fake_jpx, "/JPXDecode", None);
    let out = rewrite_with_args(
        &src,
        &[
            "--stream-data=compress",
            "--full-rewrite",
            "--remove-unreferenced-resources=no", // flpdf-s9s
        ],
    );

    let stream = extract_obj4(&out);
    assert!(
        matches!(stream.dict.get("Filter"), Some(Object::Name(n)) if n.as_slice() == b"JPXDecode"),
        "JPXDecode compress: passthrough must keep /Filter; got {:?}",
        stream.dict.get("Filter")
    );
    assert_eq!(
        stream.data.as_slice(),
        fake_jpx,
        "JPXDecode compress: stream data must be byte-identical"
    );
}

// ---------------------------------------------------------------------------
// show-stream: LZWDecode → text-readable (flpdf-9hc.7.7)
//
// show-stream must decode a standalone /LZWDecode stream and emit the raw
// payload bytes (text-readable ASCII in this case).
// cli_show_stream.rs already covers the passthrough marker cases for all four
// image codecs; this adds the missing LZW-decode case.
// ---------------------------------------------------------------------------

/// show-stream decodes a /LZWDecode stream and emits text-readable bytes.
#[test]
fn cli_show_stream_lzw_text_readable() {
    let src = build_pdf_with_prefiltered_stream(LZW_ABABABABABABAB_EC1, "/LZWDecode", None);

    let temp = tempfile::tempdir().unwrap();
    let pdf_path = temp.path().join("lzw.pdf");
    std::fs::write(&pdf_path, &src).unwrap();

    let stdout = Command::cargo_bin("flpdf")
        .unwrap()
        .args(["show-stream", "4 0"])
        .arg(&pdf_path)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    assert_eq!(
        stdout.as_slice(),
        LZW_ABABABABABABAB_PLAIN,
        "show-stream must decode /LZWDecode and emit text-readable payload"
    );
}