micropdf 0.16.0

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
//! C FFI for fz_image - MicroPDF compatible image handling
//!
//! Provides FFI bindings for image loading and rendering.

use super::{BUFFERS, Handle, HandleStore, PIXMAPS};
use crate::fitz::colorspace::Colorspace;
use crate::fitz::image::Image;
use std::sync::LazyLock;

/// Image storage
pub static IMAGES: LazyLock<HandleStore<Image>> = LazyLock::new(HandleStore::default);

/// Helper to convert fitz::colorspace::Colorspace to a colorspace handle
fn colorspace_to_handle(cs: &crate::fitz::colorspace::Colorspace) -> u64 {
    match cs.name() {
        "DeviceGray" => super::colorspace::FZ_COLORSPACE_GRAY,
        "DeviceRGB" => super::colorspace::FZ_COLORSPACE_RGB,
        "DeviceCMYK" => super::colorspace::FZ_COLORSPACE_CMYK,
        "DeviceBGR" => super::colorspace::FZ_COLORSPACE_BGR,
        _ => 0, // Unknown colorspace
    }
}

/// Create a new image from pixmap
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_image_from_pixmap(_ctx: Handle, pixmap: Handle, _mask: Handle) -> Handle {
    if let Some(pm) = PIXMAPS.get(pixmap) {
        if let Ok(guard) = pm.lock() {
            let w = guard.w();
            let h = guard.h();

            // Create image from pixmap dimensions
            // The Image will use the pixmap data internally
            let image = Image::new(w, h, None);
            return IMAGES.insert(image);
        }
    }
    0
}

/// Create a new image from data
///
/// Copies and parses the image data. Detects format by magic bytes (JPEG, PNG).
/// For decodable formats, dimensions come from the decoded image.
/// For raw data, uses w/h from parameters.
///
/// # Safety
/// Caller must ensure data points to readable memory of at least len bytes.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_image_from_data(
    _ctx: Handle,
    w: i32,
    h: i32,
    bpc: i32,
    _colorspace: Handle,
    xres: i32,
    yres: i32,
    interpolate: i32,
    imagemask: i32,
    _decode: *const f32,
    _mask: *const u8,
    data: *const u8,
    len: i32,
) -> Handle {
    if data.is_null() || len <= 0 {
        return 0;
    }

    let len = len as usize;
    let data_slice = unsafe { std::slice::from_raw_parts(data, len) };

    // Try to decode as JPEG/PNG (or other formats supported by image crate)
    if let Ok(image) = Image::from_data(data_slice) {
        let mut img = image;
        if xres > 0 || yres > 0 {
            img.set_resolution(
                if xres > 0 { xres } else { 96 },
                if yres > 0 { yres } else { 96 },
            );
        }
        return IMAGES.insert(img);
    }

    // Fallback: treat as raw data if dimensions provided
    if w <= 0 || h <= 0 {
        return 0;
    }

    let bpc = bpc.clamp(1, 16);
    let n = 3i32; // Default to RGB
    let expected_size = ((w * h * n * bpc) / 8) as usize;

    let data_copy: Vec<u8> = if data_slice.len() >= expected_size {
        data_slice[..expected_size].to_vec()
    } else {
        let mut v = data_slice.to_vec();
        v.resize(expected_size, 0);
        v
    };

    let colorspace = Colorspace::device_rgb();
    match Image::from_raw(w, h, bpc as u8, colorspace, data_copy) {
        Ok(mut img) => {
            if xres > 0 || yres > 0 {
                img.set_resolution(
                    if xres > 0 { xres } else { 96 },
                    if yres > 0 { yres } else { 96 },
                );
            }
            if imagemask != 0 {
                img.set_has_alpha(true);
            }
            IMAGES.insert(img)
        }
        Err(_) => 0,
    }
}

/// Keep (increment ref) image
#[unsafe(no_mangle)]
pub extern "C" fn fz_keep_image(_ctx: Handle, image: Handle) -> Handle {
    IMAGES.keep(image)
}

/// Drop image reference
#[unsafe(no_mangle)]
pub extern "C" fn fz_drop_image(_ctx: Handle, image: Handle) {
    let _ = IMAGES.remove(image);
}

/// Get image width
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_w(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.width();
        }
    }
    0
}

/// Get image height
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_h(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.height();
        }
    }
    0
}

/// Get image X resolution
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_xres(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.xres();
        }
    }
    96 // Default DPI
}

/// Get image Y resolution
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_yres(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.yres();
        }
    }
    96 // Default DPI
}

/// Get image colorspace
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_colorspace(_ctx: Handle, image: Handle) -> Handle {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            if let Some(cs) = guard.colorspace() {
                return colorspace_to_handle(cs);
            }
        }
    }
    0
}

/// Check if image is a mask
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_is_mask(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return i32::from(guard.is_mask());
        }
    }
    0
}

/// Get pixmap from image
#[unsafe(no_mangle)]
pub extern "C" fn fz_get_pixmap_from_image(
    _ctx: Handle,
    image: Handle,
    _subarea: *const super::geometry::fz_irect,
    _ctm: *mut super::geometry::fz_matrix,
    w: *mut i32,
    h: *mut i32,
) -> Handle {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            // Generate pixmap from image
            let img_w = guard.width();
            let img_h = guard.height();

            // Set output dimensions
            if !w.is_null() {
                unsafe {
                    *w = img_w;
                }
            }
            if !h.is_null() {
                unsafe {
                    *h = img_h;
                }
            }

            // Create pixmap using FFI Pixmap type
            let cs_handle = match guard.colorspace() {
                Some(cs) => colorspace_to_handle(cs),
                None => 0,
            };
            // Use colorspace handle directly with Pixmap
            let pixmap = super::pixmap::Pixmap::new(cs_handle, img_w, img_h, true);
            return PIXMAPS.insert(pixmap);
        }
    }
    0
}

/// Decode image to pixmap
#[unsafe(no_mangle)]
pub extern "C" fn fz_decode_image(
    _ctx: Handle,
    image: Handle,
    _l2factor: i32,
    _subarea: *const super::geometry::fz_irect,
) -> Handle {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            let img_w = guard.width();
            let img_h = guard.height();

            // Create pixmap from image data using FFI Pixmap type
            let cs_handle = match guard.colorspace() {
                Some(cs) => colorspace_to_handle(cs),
                None => 0,
            };
            // Use colorspace handle directly with Pixmap
            let pixmap = super::pixmap::Pixmap::new(cs_handle, img_w, img_h, true);
            return PIXMAPS.insert(pixmap);
        }
    }
    0
}

/// Decode a scaled version of the image
#[unsafe(no_mangle)]
pub extern "C" fn fz_decode_image_scaled(
    _ctx: Handle,
    image: Handle,
    w: i32,
    h: i32,
    _l2factor: i32,
    _subarea: *const super::geometry::fz_irect,
) -> Handle {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            // Create scaled pixmap using FFI Pixmap type
            let cs_handle = match guard.colorspace() {
                Some(cs) => colorspace_to_handle(cs),
                None => 0,
            };
            // Use colorspace handle directly with Pixmap
            let pixmap = super::pixmap::Pixmap::new(cs_handle, w, h, true);
            return PIXMAPS.insert(pixmap);
        }
    }
    0
}

/// Load image from file
///
/// # Safety
/// Caller must ensure filename is a valid null-terminated C string.
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_image_from_file(
    _ctx: Handle,
    filename: *const std::ffi::c_char,
) -> Handle {
    if filename.is_null() {
        return 0;
    }

    // SAFETY: Caller guarantees filename is a valid null-terminated C string
    let c_str = unsafe { std::ffi::CStr::from_ptr(filename) };
    let path = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    // Read file
    match std::fs::read(path) {
        Ok(data) => {
            // Try to decode image
            match Image::from_data(&data) {
                Ok(image) => IMAGES.insert(image),
                Err(_) => 0,
            }
        }
        Err(_) => 0,
    }
}

/// Load image from buffer
#[unsafe(no_mangle)]
pub extern "C" fn fz_new_image_from_buffer(_ctx: Handle, buffer: Handle) -> Handle {
    if let Some(buf) = BUFFERS.get(buffer) {
        if let Ok(guard) = buf.lock() {
            let data = guard.as_slice();

            // Try to decode image
            match Image::from_data(data) {
                Ok(image) => IMAGES.insert(image),
                Err(_) => 0,
            }
        } else {
            0
        }
    } else {
        0
    }
}

/// Check if image is valid
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_is_valid(_ctx: Handle, image: Handle) -> i32 {
    if IMAGES.get(image).is_some() { 1 } else { 0 }
}

/// Clone an image
#[unsafe(no_mangle)]
pub extern "C" fn fz_clone_image(_ctx: Handle, image: Handle) -> Handle {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            let cloned = guard.clone();
            return IMAGES.insert(cloned);
        }
    }
    0
}

/// Get image BPP (bits per pixel)
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_bpp(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.bits_per_pixel();
        }
    }
    8 // Fallback for invalid handle
}

/// Check if image has alpha channel
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_has_alpha(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return i32::from(guard.has_alpha());
        }
    }
    0
}

/// Get image orientation (EXIF-style: 0=unset, 1-8 per EXIF spec)
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_orientation(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.orientation() as i32;
        }
    }
    0
}

/// Get image width
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_width(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.width();
        }
    }
    0
}

/// Get image height
#[unsafe(no_mangle)]
pub extern "C" fn fz_image_height(_ctx: Handle, image: Handle) -> i32 {
    if let Some(img) = IMAGES.get(image) {
        if let Ok(guard) = img.lock() {
            return guard.height();
        }
    }
    0
}

/// Load image from raw buffer data
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fz_new_image_from_buffer_data(
    _ctx: Handle,
    data: *const u8,
    len: usize,
) -> Handle {
    if data.is_null() || len == 0 {
        return 0;
    }

    // SAFETY: Caller guarantees data points to readable memory of len bytes
    let slice = unsafe { std::slice::from_raw_parts(data, len) };

    // Try to decode image
    match Image::from_data(slice) {
        Ok(image) => IMAGES.insert(image),
        Err(_) => 0,
    }
}

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

    #[test]
    fn test_new_image_from_pixmap() {
        // Create a pixmap first using device RGB colorspace handle
        use crate::ffi::colorspace::FZ_COLORSPACE_RGB;
        use crate::ffi::pixmap::Pixmap;
        let pixmap = Pixmap::new(FZ_COLORSPACE_RGB, 10, 10, true);
        let pixmap_handle = PIXMAPS.insert(pixmap);

        let image_handle = fz_new_image_from_pixmap(0, pixmap_handle, 0);
        assert_ne!(image_handle, 0);

        fz_drop_image(0, image_handle);
        PIXMAPS.remove(pixmap_handle);
    }

    #[test]
    fn test_keep_image() {
        let image = Image::new(10, 10, None);
        let image_handle = IMAGES.insert(image);

        let kept = fz_keep_image(0, image_handle);
        assert_eq!(kept, image_handle);

        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_image_dimensions() {
        let image = Image::new(100, 200, None);
        let image_handle = IMAGES.insert(image);

        assert_eq!(fz_image_w(0, image_handle), 100);
        assert_eq!(fz_image_h(0, image_handle), 200);

        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_image_resolution() {
        let image = Image::new(100, 100, None);
        let image_handle = IMAGES.insert(image);

        let xres = fz_image_xres(0, image_handle);
        let yres = fz_image_yres(0, image_handle);
        assert!(xres > 0);
        assert!(yres > 0);

        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_image_colorspace() {
        let image = Image::new(10, 10, None);
        let image_handle = IMAGES.insert(image);

        let cs_handle = fz_image_colorspace(0, image_handle);
        assert_ne!(cs_handle, 0);

        super::super::colorspace::COLORSPACES.remove(cs_handle);
        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_image_is_mask() {
        let image = Image::new(10, 10, None);
        let image_handle = IMAGES.insert(image);

        let _is_mask = fz_image_is_mask(0, image_handle);

        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_get_pixmap_from_image() {
        let image = Image::new(50, 50, None);
        let image_handle = IMAGES.insert(image);

        let mut w = 0i32;
        let mut h = 0i32;
        let pixmap_handle = fz_get_pixmap_from_image(
            0,
            image_handle,
            std::ptr::null(),
            std::ptr::null_mut(),
            &mut w as *mut i32,
            &mut h as *mut i32,
        );

        assert_ne!(pixmap_handle, 0);
        assert_eq!(w, 50);
        assert_eq!(h, 50);

        PIXMAPS.remove(pixmap_handle);
        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_decode_image() {
        let image = Image::new(20, 20, None);
        let image_handle = IMAGES.insert(image);

        let pixmap_handle = fz_decode_image(0, image_handle, 0, std::ptr::null());
        assert_ne!(pixmap_handle, 0);

        PIXMAPS.remove(pixmap_handle);
        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_decode_image_scaled() {
        let image = Image::new(100, 100, None);
        let image_handle = IMAGES.insert(image);

        let pixmap_handle = fz_decode_image_scaled(0, image_handle, 50, 50, 0, std::ptr::null());
        assert_ne!(pixmap_handle, 0);

        PIXMAPS.remove(pixmap_handle);
        fz_drop_image(0, image_handle);
    }

    #[test]
    fn test_new_image_from_data_null() {
        assert_eq!(
            fz_new_image_from_data(
                0,
                10,
                10,
                8,
                0,
                96,
                96,
                0,
                0,
                std::ptr::null(),
                std::ptr::null(),
                std::ptr::null(),
                0
            ),
            0
        );
    }

    #[test]
    fn test_new_image_from_data_raw() {
        let w = 10i32;
        let h = 10i32;
        let bpc = 8;
        let size = ((w * h * 3 * bpc) / 8) as usize;
        let data = vec![128u8; size];
        let h_img = fz_new_image_from_data(
            0,
            w,
            h,
            bpc,
            0,
            96,
            96,
            0,
            0,
            std::ptr::null(),
            std::ptr::null(),
            data.as_ptr(),
            size as i32,
        );
        if h_img != 0 {
            assert_eq!(fz_image_w(0, h_img), 10);
            fz_drop_image(0, h_img);
        }
    }

    #[test]
    fn test_new_image_from_data_invalid_dims() {
        let data = [0u8; 100];
        assert_eq!(
            fz_new_image_from_data(
                0,
                0,
                0,
                8,
                0,
                96,
                96,
                0,
                0,
                std::ptr::null(),
                std::ptr::null(),
                data.as_ptr(),
                100
            ),
            0
        );
    }

    #[test]
    fn test_image_invalid_handle() {
        assert_eq!(fz_image_w(0, 0), 0);
        assert_eq!(fz_image_h(0, 0), 0);
        assert_eq!(fz_image_xres(0, 0), 96);
        assert_eq!(fz_image_yres(0, 0), 96);
        assert_eq!(fz_image_colorspace(0, 0), 0);
        assert_eq!(fz_image_is_mask(0, 0), 0);
        assert_eq!(fz_image_bpp(0, 0), 8);
        assert_eq!(fz_image_has_alpha(0, 0), 0);
        assert_eq!(fz_image_orientation(0, 0), 0);
        assert_eq!(fz_image_width(0, 0), 0);
        assert_eq!(fz_image_height(0, 0), 0);
        assert_eq!(fz_image_is_valid(0, 0), 0);
        assert_eq!(fz_clone_image(0, 0), 0);
    }

    #[test]
    fn test_get_pixmap_from_image_null_dims() {
        let image = Image::new(20, 20, None);
        let h = IMAGES.insert(image);
        let pm = fz_get_pixmap_from_image(
            0,
            h,
            std::ptr::null(),
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            std::ptr::null_mut(),
        );
        assert_ne!(pm, 0);
        PIXMAPS.remove(pm);
        fz_drop_image(0, h);
    }

    #[test]
    fn test_new_image_from_file_null() {
        assert_eq!(fz_new_image_from_file(0, std::ptr::null()), 0);
    }

    #[test]
    fn test_new_image_from_buffer_invalid() {
        assert_eq!(fz_new_image_from_buffer(0, 99999), 0);
    }

    #[test]
    fn test_new_image_from_buffer_data_null() {
        assert_eq!(
            unsafe { fz_new_image_from_buffer_data(0, std::ptr::null(), 100) },
            0
        );
        assert_eq!(
            unsafe { fz_new_image_from_buffer_data(0, [1u8].as_ptr(), 0) },
            0
        );
    }

    #[test]
    fn test_fz_new_image_from_buffer_data_valid() {
        let png_header = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
        let h = unsafe { fz_new_image_from_buffer_data(0, png_header.as_ptr(), png_header.len()) };
        if h != 0 {
            fz_drop_image(0, h);
        }
    }
}