ovid 0.1.5

fast, bidirectional PDF and Image converter
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
use anyhow::{Context, Result};
use clap::ValueEnum;
use std::path::PathBuf;

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ImageFormat {
    Png,
    Jpg,
}

/// PNG compression level
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum PngCompression {
    /// fastest encoding, larger files
    #[default]
    Fast,
    /// smaller files, slower encoding
    Small,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum PageSize {
    A4,
    Letter,
    Legal,
    A3,
}

impl PageSize {
    pub fn dimensions_pt(self) -> (f32, f32) {
        match self {
            PageSize::A4 => (595.28, 841.89),
            PageSize::Letter => (612.0, 792.0),
            PageSize::Legal => (612.0, 1008.0),
            PageSize::A3 => (841.89, 1190.55),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum Orientation {
    #[default]
    Auto,
    Portrait,
    Landscape,
}

impl std::fmt::Display for Orientation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Orientation::Auto => write!(f, "auto"),
            Orientation::Portrait => write!(f, "portrait"),
            Orientation::Landscape => write!(f, "landscape"),
        }
    }
}

/// parse page range string like "1,3-5,10" into 0-indexed page indices
pub fn parse_page_ranges(s: &str, num_pages: i32) -> Result<Vec<i32>> {
    let mut pages = Vec::new();
    for part in s.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        if let Some((start, end)) = part.split_once('-') {
            let start: i32 = start.trim().parse().context("Invalid page number in range")?;
            let end: i32 = end.trim().parse().context("Invalid page number in range")?;
            anyhow::ensure!(
                start >= 1 && end >= start && end <= num_pages,
                "Page range {}-{} out of bounds (document has {} pages)",
                start,
                end,
                num_pages
            );
            for p in start..=end {
                pages.push(p - 1);
            }
        } else {
            let p: i32 = part.parse().context("Invalid page number")?;
            anyhow::ensure!(
                p >= 1 && p <= num_pages,
                "Page {} out of bounds (document has {} pages)",
                p,
                num_pages
            );
            pages.push(p - 1);
        }
    }
    anyhow::ensure!(!pages.is_empty(), "No pages specified");
    pages.dedup();
    Ok(pages)
}

/// check if a path string contains glob pattern characters
fn is_glob_pattern(s: &str) -> bool {
    s.contains('*') || s.contains('?') || s.contains('[')
}

/// expand dirs and glob patterns in input list into sorted image files
pub fn expand_image_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
    const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "tiff", "tif", "bmp", "gif"];
    let mut result = Vec::new();
    for path in paths {
        let path_str = path.to_string_lossy();
        if is_glob_pattern(&path_str) {
            // expand glob pattern
            let mut entries: Vec<PathBuf> = glob::glob(&path_str)
                .with_context(|| format!("Invalid glob pattern: {}", path_str))?
                .filter_map(|e| e.ok())
                .filter(|p| p.is_file())
                .collect();
            entries.sort();
            anyhow::ensure!(
                !entries.is_empty(),
                "No files matched pattern: {}",
                path_str
            );
            result.extend(entries);
        } else if path.is_dir() {
            let mut entries: Vec<PathBuf> = std::fs::read_dir(path)
                .with_context(|| format!("Cannot read directory: {}", path.display()))?
                .filter_map(|e| e.ok())
                .map(|e| e.path())
                .filter(|p| {
                    p.extension()
                        .and_then(|e| e.to_str())
                        .is_some_and(|ext| IMAGE_EXTENSIONS.contains(&ext.to_lowercase().as_str()))
                })
                .collect();
            entries.sort();
            anyhow::ensure!(
                !entries.is_empty(),
                "No image files found in {}",
                path.display()
            );
            result.extend(entries);
        } else {
            result.push(path.clone());
        }
    }
    Ok(result)
}

pub struct JpegInfo {
    pub width: u32,
    pub height: u32,
    pub components: u8,
    /// APP14 Adobe color transform: None = no Adobe marker, Some(0) = CMYK, Some(2) = YCCK
    pub adobe_color_transform: Option<u8>,
    /// DPI from JFIF APP0 marker (if present and units==1 for DPI)
    pub dpi: Option<u32>,
    /// ICC profile data reassembled from APP2 markers
    pub icc_profile: Option<Vec<u8>>,
}

/// parse JPEG file's SOF, APP0, APP2, and APP14 markers
pub fn parse_jpeg_header(data: &[u8]) -> Result<JpegInfo> {
    anyhow::ensure!(
        data.len() >= 2 && data[0] == 0xFF && data[1] == 0xD8,
        "Not a valid JPEG file"
    );
    let mut pos = 2;
    let mut sof: Option<(u32, u32, u8)> = None;
    let mut adobe_color_transform: Option<u8> = None;
    let mut dpi: Option<u32> = None;
    let mut icc_chunks: Vec<(u8, u8, Vec<u8>)> = Vec::new(); // (seq, total, data)

    while pos + 4 < data.len() {
        if data[pos] != 0xFF {
            anyhow::bail!("Invalid JPEG marker at offset {}", pos);
        }
        let marker = data[pos + 1];
        // skip padding 0xFF bytes
        if marker == 0xFF {
            pos += 1;
            continue;
        }
        // skip RST markers and standalone markers (no length field)
        if marker == 0x00 || (0xD0..=0xD9).contains(&marker) {
            pos += 2;
            continue;
        }
        let len = u16::from_be_bytes([data[pos + 2], data[pos + 3]]) as usize;
        anyhow::ensure!(pos + 2 + len <= data.len(), "Truncated JPEG marker");

        // SOS marker: stop scanning (entropy-coded data follows)
        if marker == 0xDA {
            break;
        }

        // SOF markers
        if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) {
            anyhow::ensure!(len >= 8, "Truncated SOF");
            let height = u16::from_be_bytes([data[pos + 5], data[pos + 6]]) as u32;
            let width = u16::from_be_bytes([data[pos + 7], data[pos + 8]]) as u32;
            let components = data[pos + 9];
            sof = Some((width, height, components));
        }

        // APP0 (JFIF) - DPI
        if marker == 0xE0 && len >= 14 {
            let seg = &data[pos + 4..pos + 2 + len];
            if seg.len() >= 12 && &seg[..5] == b"JFIF\0" {
                let units = seg[7];
                let x_density = u16::from_be_bytes([seg[8], seg[9]]) as u32;
                let y_density = u16::from_be_bytes([seg[10], seg[11]]) as u32;
                if units == 1 && x_density == y_density && x_density > 0 {
                    dpi = Some(x_density);
                } else if units == 2 && x_density == y_density && x_density > 0 {
                    // dots per cm -> DPI
                    dpi = Some((x_density as f64 * 2.54) as u32);
                }
            }
        }

        // APP2 - ICC profile chunks (tag: "ICC_PROFILE\0")
        if marker == 0xE2 && len >= 16 {
            let seg = &data[pos + 4..pos + 2 + len];
            if seg.len() >= 14 && &seg[..12] == b"ICC_PROFILE\0" {
                let seq_no = seg[12];
                let total = seg[13];
                icc_chunks.push((seq_no, total, seg[14..].to_vec()));
            }
        }

        // APP14 (Adobe) - color transform
        if marker == 0xEE && len >= 12 {
            let seg = &data[pos + 4..pos + 2 + len];
            if seg.len() >= 12 && &seg[..5] == b"Adobe" {
                adobe_color_transform = Some(seg[11]);
            }
        }

        pos += 2 + len;
    }

    let (width, height, components) = sof.context("No SOF marker found in JPEG")?;

    // reassemble ICC profile from chunks
    let icc_profile = if !icc_chunks.is_empty() {
        icc_chunks.sort_by_key(|(seq, _, _)| *seq);
        let mut profile = Vec::new();
        for (_, _, chunk_data) in &icc_chunks {
            profile.extend_from_slice(chunk_data);
        }
        Some(profile)
    } else {
        None
    };

    Ok(JpegInfo {
        width,
        height,
        components,
        adobe_color_transform,
        dpi,
        icc_profile,
    })
}

pub struct PngInfo {
    pub width: u32,
    pub height: u32,
    pub bit_depth: u8,
    pub color_type: u8,
    pub interlace: u8,
    pub idat_data: Vec<u8>,
    pub plte_data: Vec<u8>,
    pub has_trns: bool,
    /// DPI from pHYs chunk (if units == 1, meters -> DPI)
    pub dpi: Option<u32>,
    /// ICC profile from iCCP chunk (decompressed)
    pub icc_profile: Option<Vec<u8>>,
}

/// parse a PNG file to extract IHDR info and concatenated IDAT chunk data
pub fn parse_png_header(data: &[u8]) -> Result<PngInfo> {
    const SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
    anyhow::ensure!(
        data.len() >= 8 && data[..8] == SIGNATURE,
        "Not a valid PNG file"
    );

    let mut pos = 8;
    let mut width = 0u32;
    let mut height = 0u32;
    let mut bit_depth = 0u8;
    let mut color_type = 0u8;
    let mut interlace = 0u8;
    let mut idat_data = Vec::new();
    let mut plte_data = Vec::new();
    let mut has_trns = false;
    let mut dpi: Option<u32> = None;
    let mut icc_profile: Option<Vec<u8>> = None;
    let mut got_ihdr = false;

    while pos + 8 <= data.len() {
        let chunk_len =
            u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
        let chunk_type = &data[pos + 4..pos + 8];
        let chunk_data_start = pos + 8;
        let chunk_end = chunk_data_start + chunk_len + 4; // +4 for CRC
        anyhow::ensure!(chunk_end <= data.len(), "Truncated PNG chunk");

        if chunk_type == b"IHDR" {
            anyhow::ensure!(chunk_len >= 13, "Truncated IHDR");
            let d = &data[chunk_data_start..];
            width = u32::from_be_bytes([d[0], d[1], d[2], d[3]]);
            height = u32::from_be_bytes([d[4], d[5], d[6], d[7]]);
            bit_depth = d[8];
            color_type = d[9];
            interlace = d[12];
            got_ihdr = true;
        } else if chunk_type == b"PLTE" {
            plte_data.extend_from_slice(&data[chunk_data_start..chunk_data_start + chunk_len]);
        } else if chunk_type == b"tRNS" {
            has_trns = true;
        } else if chunk_type == b"pHYs" && chunk_len >= 9 {
            let d = &data[chunk_data_start..];
            let x_ppu = u32::from_be_bytes([d[0], d[1], d[2], d[3]]);
            let y_ppu = u32::from_be_bytes([d[4], d[5], d[6], d[7]]);
            let unit = d[8];
            if unit == 1 && x_ppu == y_ppu && x_ppu > 0 {
                // unit 1 = meter, convert to DPI
                dpi = Some((x_ppu as f64 / 39.3701).round() as u32);
            }
        } else if chunk_type == b"iCCP" && chunk_len > 2 {
            let d = &data[chunk_data_start..chunk_data_start + chunk_len];
            // iCCP: profile name (null-terminated) + compression method (1 byte) + compressed data
            if let Some(null_pos) = d.iter().position(|&b| b == 0) {
                if null_pos + 2 < d.len() {
                    // d[null_pos + 1] is compression method (always 0 = deflate)
                    let compressed = &d[null_pos + 2..];
                    if let Ok(decompressed) = decompress_zlib(compressed) {
                        icc_profile = Some(decompressed);
                    }
                }
            }
        } else if chunk_type == b"IDAT" {
            idat_data.extend_from_slice(&data[chunk_data_start..chunk_data_start + chunk_len]);
        } else if chunk_type == b"IEND" {
            break;
        }

        pos = chunk_end;
    }

    anyhow::ensure!(got_ihdr, "No IHDR chunk found in PNG");
    anyhow::ensure!(!idat_data.is_empty(), "No IDAT chunks found in PNG");

    Ok(PngInfo {
        width,
        height,
        bit_depth,
        color_type,
        interlace,
        idat_data,
        plte_data,
        has_trns,
        dpi,
        icc_profile,
    })
}

/// decompress zlib-compressed data
fn decompress_zlib(data: &[u8]) -> Result<Vec<u8>> {
    use flate2::read::ZlibDecoder;
    use std::io::Read;
    let mut decoder = ZlibDecoder::new(data);
    let mut out = Vec::new();
    decoder.read_to_end(&mut out)?;
    Ok(out)
}

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

    #[test]
    fn parse_pages_single() {
        assert_eq!(parse_page_ranges("1", 10).unwrap(), vec![0]);
        assert_eq!(parse_page_ranges("5", 10).unwrap(), vec![4]);
        assert_eq!(parse_page_ranges("10", 10).unwrap(), vec![9]);
    }

    #[test]
    fn parse_pages_multiple() {
        assert_eq!(parse_page_ranges("1,3,5", 10).unwrap(), vec![0, 2, 4]);
    }

    #[test]
    fn parse_pages_range() {
        assert_eq!(parse_page_ranges("2-5", 10).unwrap(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn parse_pages_mixed() {
        assert_eq!(
            parse_page_ranges("1,3-5,10", 10).unwrap(),
            vec![0, 2, 3, 4, 9]
        );
    }

    #[test]
    fn parse_pages_single_page_range() {
        assert_eq!(parse_page_ranges("3-3", 5).unwrap(), vec![2]);
    }

    #[test]
    fn parse_pages_whitespace() {
        assert_eq!(
            parse_page_ranges(" 1 , 3 - 5 , 10 ", 10).unwrap(),
            vec![0, 2, 3, 4, 9]
        );
    }

    #[test]
    fn parse_pages_trailing_comma() {
        assert_eq!(parse_page_ranges("1,2,", 5).unwrap(), vec![0, 1]);
    }

    #[test]
    fn parse_pages_dedup_adjacent() {
        assert_eq!(parse_page_ranges("3,3", 5).unwrap(), vec![2]);
    }

    #[test]
    fn parse_pages_no_dedup_nonadjacent() {
        let result = parse_page_ranges("1,3,1", 5).unwrap();
        assert_eq!(result, vec![0, 2, 0]);
    }

    #[test]
    fn parse_pages_all_pages() {
        assert_eq!(parse_page_ranges("1-3", 3).unwrap(), vec![0, 1, 2]);
    }

    #[test]
    fn parse_pages_err_zero() {
        assert!(parse_page_ranges("0", 10).is_err());
    }

    #[test]
    fn parse_pages_err_exceeds_count() {
        assert!(parse_page_ranges("11", 10).is_err());
    }

    #[test]
    fn parse_pages_err_range_exceeds() {
        assert!(parse_page_ranges("5-11", 10).is_err());
    }

    #[test]
    fn parse_pages_err_reversed_range() {
        assert!(parse_page_ranges("5-3", 10).is_err());
    }

    #[test]
    fn parse_pages_err_empty() {
        assert!(parse_page_ranges("", 10).is_err());
    }

    #[test]
    fn parse_pages_err_garbage() {
        assert!(parse_page_ranges("abc", 10).is_err());
    }

    #[test]
    fn parse_pages_err_negative() {
        assert!(parse_page_ranges("-1", 10).is_err());
    }

    fn make_minimal_jpeg(width: u16, height: u16, components: u8) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        let sof_len: u16 = 8 + 3 * components as u16;
        buf.extend_from_slice(&[0xFF, 0xC0]);
        buf.extend_from_slice(&sof_len.to_be_bytes());
        buf.push(8);
        buf.extend_from_slice(&height.to_be_bytes());
        buf.extend_from_slice(&width.to_be_bytes());
        buf.push(components);
        for i in 0..components {
            buf.push(i + 1);
            buf.push(0x11);
            buf.push(0);
        }
        buf.extend_from_slice(&[0xFF, 0xD9]);
        buf
    }

    #[test]
    fn jpeg_header_rgb() {
        let data = make_minimal_jpeg(640, 480, 3);
        let info = parse_jpeg_header(&data).unwrap();
        assert_eq!((info.width, info.height, info.components), (640, 480, 3));
        assert_eq!(info.adobe_color_transform, None);
        assert_eq!(info.dpi, None);
    }

    #[test]
    fn jpeg_header_grayscale() {
        let data = make_minimal_jpeg(100, 200, 1);
        let info = parse_jpeg_header(&data).unwrap();
        assert_eq!((info.width, info.height, info.components), (100, 200, 1));
    }

    #[test]
    fn jpeg_header_large_dimensions() {
        let data = make_minimal_jpeg(4096, 3000, 3);
        let info = parse_jpeg_header(&data).unwrap();
        assert_eq!((info.width, info.height, info.components), (4096, 3000, 3));
    }

    #[test]
    fn jpeg_header_with_app0_before_sof() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        buf.extend_from_slice(&[0xFF, 0xE0]);
        let app0_payload = vec![0u8; 14];
        let app0_len = (app0_payload.len() + 2) as u16;
        buf.extend_from_slice(&app0_len.to_be_bytes());
        buf.extend_from_slice(&app0_payload);
        let sof_len: u16 = 8 + 3 * 3;
        buf.extend_from_slice(&[0xFF, 0xC0]);
        buf.extend_from_slice(&sof_len.to_be_bytes());
        buf.push(8);
        buf.extend_from_slice(&480u16.to_be_bytes());
        buf.extend_from_slice(&640u16.to_be_bytes());
        buf.push(3);
        for i in 0..3u8 {
            buf.push(i + 1);
            buf.push(0x11);
            buf.push(0);
        }
        buf.extend_from_slice(&[0xFF, 0xD9]);
        let info = parse_jpeg_header(&buf).unwrap();
        assert_eq!((info.width, info.height, info.components), (640, 480, 3));
    }

    #[test]
    fn jpeg_header_sof2_progressive() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        let sof_len: u16 = 8 + 3 * 3;
        buf.extend_from_slice(&[0xFF, 0xC2]);
        buf.extend_from_slice(&sof_len.to_be_bytes());
        buf.push(8);
        buf.extend_from_slice(&768u16.to_be_bytes());
        buf.extend_from_slice(&1024u16.to_be_bytes());
        buf.push(3);
        for i in 0..3u8 {
            buf.push(i + 1);
            buf.push(0x11);
            buf.push(0);
        }
        buf.extend_from_slice(&[0xFF, 0xD9]);
        let info = parse_jpeg_header(&buf).unwrap();
        assert_eq!((info.width, info.height, info.components), (1024, 768, 3));
    }

    #[test]
    fn jpeg_header_with_jfif_dpi() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        // APP0 JFIF with 300 DPI
        buf.extend_from_slice(&[0xFF, 0xE0]);
        let mut app0 = Vec::new();
        app0.extend_from_slice(b"JFIF\0"); // identifier
        app0.extend_from_slice(&[1, 1]); // version 1.1
        app0.push(1); // units = DPI
        app0.extend_from_slice(&300u16.to_be_bytes()); // X density
        app0.extend_from_slice(&300u16.to_be_bytes()); // Y density
        app0.extend_from_slice(&[0, 0]); // thumbnail
        let app0_len = (app0.len() + 2) as u16;
        buf.extend_from_slice(&app0_len.to_be_bytes());
        buf.extend_from_slice(&app0);
        // SOF
        let sof_len: u16 = 8 + 3 * 3;
        buf.extend_from_slice(&[0xFF, 0xC0]);
        buf.extend_from_slice(&sof_len.to_be_bytes());
        buf.push(8);
        buf.extend_from_slice(&480u16.to_be_bytes());
        buf.extend_from_slice(&640u16.to_be_bytes());
        buf.push(3);
        for i in 0..3u8 {
            buf.push(i + 1);
            buf.push(0x11);
            buf.push(0);
        }
        buf.extend_from_slice(&[0xFF, 0xD9]);
        let info = parse_jpeg_header(&buf).unwrap();
        assert_eq!(info.dpi, Some(300));
    }

    #[test]
    fn jpeg_header_with_adobe_app14() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        // APP14 Adobe marker with color transform = 2 (YCCK)
        buf.extend_from_slice(&[0xFF, 0xEE]);
        let mut app14 = Vec::new();
        app14.extend_from_slice(b"Adobe");
        app14.extend_from_slice(&[1, 0]); // version
        app14.extend_from_slice(&[0, 0]); // flags0
        app14.extend_from_slice(&[0, 0]); // flags1
        app14.push(2); // color transform: 2 = YCCK
        let app14_len = (app14.len() + 2) as u16;
        buf.extend_from_slice(&app14_len.to_be_bytes());
        buf.extend_from_slice(&app14);
        // SOF with 4 components
        let sof_len: u16 = 8 + 3 * 4;
        buf.extend_from_slice(&[0xFF, 0xC0]);
        buf.extend_from_slice(&sof_len.to_be_bytes());
        buf.push(8);
        buf.extend_from_slice(&100u16.to_be_bytes());
        buf.extend_from_slice(&100u16.to_be_bytes());
        buf.push(4);
        for i in 0..4u8 {
            buf.push(i + 1);
            buf.push(0x11);
            buf.push(0);
        }
        buf.extend_from_slice(&[0xFF, 0xD9]);
        let info = parse_jpeg_header(&buf).unwrap();
        assert_eq!(info.adobe_color_transform, Some(2));
        assert_eq!(info.components, 4);
    }

    #[test]
    fn jpeg_header_err_not_jpeg() {
        assert!(parse_jpeg_header(&[0x89, 0x50]).is_err());
    }

    #[test]
    fn jpeg_header_err_too_short() {
        assert!(parse_jpeg_header(&[0xFF]).is_err());
    }

    #[test]
    fn jpeg_header_err_no_sof() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[0xFF, 0xD8]);
        buf.extend_from_slice(&[0xFF, 0xD9]);
        assert!(parse_jpeg_header(&buf).is_err());
    }

    fn crc32_chunk(chunk_type: &[u8], data: &[u8]) -> u32 {
        let mut crc: u32 = 0xFFFF_FFFF;
        for &b in chunk_type.iter().chain(data.iter()) {
            let idx = ((crc ^ b as u32) & 0xFF) as usize;
            crc = CRC_TABLE[idx] ^ (crc >> 8);
        }
        crc ^ 0xFFFF_FFFF
    }

    const CRC_TABLE: [u32; 256] = {
        let mut table = [0u32; 256];
        let mut n = 0;
        while n < 256 {
            let mut c = n as u32;
            let mut k = 0;
            while k < 8 {
                if c & 1 != 0 {
                    c = 0xEDB8_8320 ^ (c >> 1);
                } else {
                    c >>= 1;
                }
                k += 1;
            }
            table[n] = c;
            n += 1;
        }
        table
    };

    fn make_minimal_png(width: u32, height: u32, color_type: u8, bit_depth: u8) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);

        fn write_chunk(buf: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
            buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
            buf.extend_from_slice(chunk_type);
            buf.extend_from_slice(data);
            let crc = crc32_chunk(chunk_type, data);
            buf.extend_from_slice(&crc.to_be_bytes());
        }

        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&width.to_be_bytes());
        ihdr.extend_from_slice(&height.to_be_bytes());
        ihdr.push(bit_depth);
        ihdr.push(color_type);
        ihdr.push(0);
        ihdr.push(0);
        ihdr.push(0);
        write_chunk(&mut buf, b"IHDR", &ihdr);

        if color_type == 3 {
            let palette = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255];
            write_chunk(&mut buf, b"PLTE", &palette);
        }

        let channels: usize = match color_type {
            0 => 1,
            2 => 3,
            3 => 1,
            4 => 2,
            6 => 4,
            _ => 1,
        };
        let row_bytes = width as usize * channels * (bit_depth as usize / 8);
        let mut raw = Vec::new();
        for _ in 0..height {
            raw.push(0);
            raw.extend(vec![128u8; row_bytes]);
        }
        let mut encoder =
            flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
        encoder.write_all(&raw).unwrap();
        let compressed = encoder.finish().unwrap();
        write_chunk(&mut buf, b"IDAT", &compressed);

        write_chunk(&mut buf, b"IEND", &[]);
        buf
    }

    #[test]
    fn png_header_rgb() {
        let data = make_minimal_png(16, 8, 2, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.width, 16);
        assert_eq!(info.height, 8);
        assert_eq!(info.color_type, 2);
        assert_eq!(info.bit_depth, 8);
        assert_eq!(info.interlace, 0);
        assert!(!info.has_trns);
        assert!(!info.idat_data.is_empty());
        assert!(info.plte_data.is_empty());
    }

    #[test]
    fn png_header_grayscale() {
        let data = make_minimal_png(32, 32, 0, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.width, 32);
        assert_eq!(info.height, 32);
        assert_eq!(info.color_type, 0);
        assert_eq!(info.bit_depth, 8);
    }

    #[test]
    fn png_header_palette() {
        let data = make_minimal_png(4, 4, 3, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.color_type, 3);
        assert_eq!(info.plte_data.len(), 12);
    }

    #[test]
    fn png_header_rgba() {
        let data = make_minimal_png(10, 10, 6, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.color_type, 6);
        assert_eq!(info.bit_depth, 8);
    }

    #[test]
    fn png_header_gray_alpha() {
        let data = make_minimal_png(10, 10, 4, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.color_type, 4);
    }

    #[test]
    fn png_header_16bit() {
        let data = make_minimal_png(8, 8, 2, 16);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.bit_depth, 16);
        assert_eq!(info.color_type, 2);
    }

    #[test]
    fn png_header_large_dimensions() {
        let data = make_minimal_png(4096, 3000, 2, 8);
        let info = parse_png_header(&data).unwrap();
        assert_eq!(info.width, 4096);
        assert_eq!(info.height, 3000);
    }

    #[test]
    fn png_header_err_not_png() {
        assert!(parse_png_header(&[0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0]).is_err());
    }

    #[test]
    fn png_header_err_too_short() {
        assert!(parse_png_header(&[137, 80, 78, 71]).is_err());
    }

    #[test]
    fn png_header_err_no_idat() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);
        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.push(8);
        ihdr.push(2);
        ihdr.push(0);
        ihdr.push(0);
        ihdr.push(0);
        buf.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
        buf.extend_from_slice(b"IHDR");
        buf.extend_from_slice(&ihdr);
        let crc = crc32_chunk(b"IHDR", &ihdr);
        buf.extend_from_slice(&crc.to_be_bytes());
        buf.extend_from_slice(&0u32.to_be_bytes());
        buf.extend_from_slice(b"IEND");
        let crc = crc32_chunk(b"IEND", &[]);
        buf.extend_from_slice(&crc.to_be_bytes());
        assert!(parse_png_header(&buf).is_err());
    }

    #[test]
    fn png_header_multiple_idat_chunks() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);

        fn write_chunk_with(buf: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
            buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
            buf.extend_from_slice(chunk_type);
            buf.extend_from_slice(data);
            let mut crc: u32 = 0xFFFF_FFFF;
            for &b in chunk_type.iter().chain(data.iter()) {
                let idx = ((crc ^ b as u32) & 0xFF) as usize;
                crc = super::tests::CRC_TABLE[idx] ^ (crc >> 8);
            }
            crc ^= 0xFFFF_FFFF;
            buf.extend_from_slice(&crc.to_be_bytes());
        }

        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.push(8);
        ihdr.push(2);
        ihdr.push(0);
        ihdr.push(0);
        ihdr.push(0);
        write_chunk_with(&mut buf, b"IHDR", &ihdr);

        let mut raw = Vec::new();
        for _ in 0..4u32 {
            raw.push(0);
            raw.extend(vec![128u8; 12]);
        }
        let mut encoder =
            flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
        encoder.write_all(&raw).unwrap();
        let compressed = encoder.finish().unwrap();
        let mid = compressed.len() / 2;
        write_chunk_with(&mut buf, b"IDAT", &compressed[..mid]);
        write_chunk_with(&mut buf, b"IDAT", &compressed[mid..]);
        write_chunk_with(&mut buf, b"IEND", &[]);

        let info = parse_png_header(&buf).unwrap();
        assert_eq!(info.width, 4);
        assert_eq!(info.height, 4);
        assert_eq!(info.idat_data.len(), compressed.len());
    }

    #[test]
    fn expand_paths_files_only() {
        let dir = std::env::temp_dir().join("ovid_test_expand_files");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let p1 = dir.join("a.png");
        let p2 = dir.join("b.jpg");
        std::fs::write(&p1, b"fake").unwrap();
        std::fs::write(&p2, b"fake").unwrap();
        let result = expand_image_paths(&[p1.clone(), p2.clone()]).unwrap();
        assert_eq!(result, vec![p1, p2]);
    }

    #[test]
    fn expand_paths_directory() {
        let dir = std::env::temp_dir().join("ovid_test_expand_dir");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("c.png"), b"fake").unwrap();
        std::fs::write(dir.join("a.jpg"), b"fake").unwrap();
        std::fs::write(dir.join("b.tiff"), b"fake").unwrap();
        std::fs::write(dir.join("notes.txt"), b"not an image").unwrap();
        let result = expand_image_paths(&[dir.clone()]).unwrap();
        assert_eq!(result.len(), 3);
        assert!(
            result[0].file_name().unwrap().to_str().unwrap()
                < result[1].file_name().unwrap().to_str().unwrap()
        );
        assert!(result.iter().all(|p| p.extension().unwrap() != "txt"));
    }

    #[test]
    fn expand_paths_mixed() {
        let dir = std::env::temp_dir().join("ovid_test_expand_mixed");
        let _ = std::fs::remove_dir_all(&dir);
        let subdir = dir.join("sub");
        std::fs::create_dir_all(&subdir).unwrap();
        let explicit = dir.join("first.png");
        std::fs::write(&explicit, b"fake").unwrap();
        std::fs::write(subdir.join("a.jpg"), b"fake").unwrap();
        std::fs::write(subdir.join("b.png"), b"fake").unwrap();
        let result = expand_image_paths(&[explicit.clone(), subdir]).unwrap();
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], explicit);
    }

    #[test]
    fn expand_paths_empty_dir() {
        let dir = std::env::temp_dir().join("ovid_test_expand_empty");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        assert!(expand_image_paths(&[dir]).is_err());
    }

    #[test]
    fn expand_paths_case_insensitive_ext() {
        let dir = std::env::temp_dir().join("ovid_test_expand_case");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("photo.JPG"), b"fake").unwrap();
        std::fs::write(dir.join("scan.Png"), b"fake").unwrap();
        std::fs::write(dir.join("doc.TIFF"), b"fake").unwrap();
        let result = expand_image_paths(&[dir]).unwrap();
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn expand_paths_all_extensions() {
        let dir = std::env::temp_dir().join("ovid_test_expand_allext");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        for ext in &["png", "jpg", "jpeg", "tiff", "tif", "bmp", "gif"] {
            std::fs::write(dir.join(format!("file.{}", ext)), b"fake").unwrap();
        }
        let result = expand_image_paths(&[dir]).unwrap();
        assert_eq!(result.len(), 7);
    }

    #[test]
    fn page_size_dimensions() {
        let (w, h) = PageSize::A4.dimensions_pt();
        assert!((w - 595.28).abs() < 0.01);
        assert!((h - 841.89).abs() < 0.01);

        let (w, h) = PageSize::Letter.dimensions_pt();
        assert!((w - 612.0).abs() < 0.01);
        assert!((h - 792.0).abs() < 0.01);

        let (w, h) = PageSize::Legal.dimensions_pt();
        assert!((w - 612.0).abs() < 0.01);
        assert!((h - 1008.0).abs() < 0.01);

        let (w, h) = PageSize::A3.dimensions_pt();
        assert!((w - 841.89).abs() < 0.01);
        assert!((h - 1190.55).abs() < 0.01);
    }

    #[test]
    fn page_size_portrait_orientation() {
        for ps in [PageSize::A4, PageSize::Letter, PageSize::Legal, PageSize::A3] {
            let (w, h) = ps.dimensions_pt();
            assert!(h > w);
        }
    }
}